Immutable keys - fixed length map in Java

DsCpp :

Is there a way in Java to create a collection (map) with fixed size and length? I.e., I would like to initialize it with K constant keys (e.g. strings) but still want to be able to change the values.

Edit: The test case has a fixed number of objects, each one corresponds to a number (float). Each time a specific event in the application occurs, I would like to multiply all the numbers in the collection, except the number that corresponds to the object that "caused" the event. The number is not logically an attribiute of the object.

Cardinal - Reinstate Monica :

I suggest you first look at Mike's answer to get an idea of how to go about solving this problem, then make some changes to the code he provided so it will work in your situation:

import java.util.HashMap;

public class InstrumentedHashMap<K> extends HashMap<K, Float> {

    private static final long serialVersionUID = 1L;
    private int MAX;

    public InstrumentedHashMap(int capacity) {
        super();
        MAX = capacity;
    }

    @Override
    public Float put(K key, Float value) {
        if (super.size() >= MAX && !super.containsKey(key)) {
            return null;
        } else {
            super.put(key, value);
            return value;
        }
    }

    public void event(K trigger, int multiplyAmount, float subtractAmount) {
        super.entrySet().stream().forEach(e -> {
            if (!e.getKey().equals(trigger))
                e.setValue(e.getValue() * multiplyAmount);
            else
                e.setValue(e.getValue() - subtractAmount);
        });
    }
}

You can use the InstrumentedHashMap#event method to handle your "specific event", with the multiplyAmount parameter being the value that you want to multiply your floats by.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71213&siteId=1