简体   繁体   中英

Static number of keys and values in Java hashmap

I have a hashmap initialized in this way:

myMap = new HashMap<Integer, Integer>();
for (int i = 0; i < 4; i++) {
    myMap.put(i, 0);
}

I don't want to be able to add anymore keys to this map, but I do want to be able to change the values. If i am not mistaken an immutable hashmap would not allow me to do the latter. Is there anyway to do this?

Assuming you oversimplified your example, and you can't just use an array, you can simply encapsulate the map into your own class, and make sure that the method changing the value does something like

public void changeValue(Integer key, Integer value) {
    if (!map.containsKey(key)) {
        throw new IllegalArgumentException("Invalid key: " + key);
    }
    map.put(key, value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM