Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it ok to change the value from outside a Map?

Tags:

java

oop

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.

like image 304
Java_Sape Avatar asked Oct 01 '13 09:10

Java_Sape


People also ask

How do you set a value on a Map?

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.

How do I change the key-value of a Map in Java?

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.

How do you change a value in a HashMap?

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.

Can we update HashMap while iterating?

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 ...


1 Answers

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.

like image 54
Suresh Atta Avatar answered Oct 11 '22 13:10

Suresh Atta