So i have a code snippet here. I go this issue while i was discussing some code with my friend
Map<Integer , List<String>> myMap = new HashMap<Integer , List<String>>();
List<String> list = new ArrayList<String>();
myMap.put(45,list);
List<String> lst = myMap.get(45);
lst.add("String1");
lst.add("String2");
lst.add("String3");
System.out.println(myMap.get(45));
My question here is. -> If its ok to modify the list outside the map through another reference? I am asking from OOP design point of view.
The map. set() method is used to add key-value pairs to a Map object. It can also be used to update the value of an existing key. Each value must have a unique key so that they get mapped correctly.
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.
Well, you can't do it by iterating over the set of values in the Map (as you are doing now), because if you do that then you have no reference to the keys, and if you have no reference to the keys, then you can't update the entries in the map, because you have no way of finding out which key was associated with the ...
That is completely ok, IMHO
When you write
List<String> lst = myMap.get(45);
Still it is refering to the value in the map
, for the key 45
.
Once you get the value(reference
to the list
), It's up to you what you are doing with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With