I have this small code snippet and want to know whether the implementations of java.Util.Map store of copy of reference variable or the copy of the object.
public static void main(String[] args) {
List<Integer> obj = Arrays.asList(1,2,3);
Map<Integer, List<Integer>> a = new HashMap<>();
a.put(0, obj);
a.get(0).forEach(System.out::print);
obj = Arrays.asList(4,5,6);
System.out.println();
a.get(0).forEach(System.out::print);
}
Output
123
123
I had a feeling that the answer to this must exist already (Ok, it may already exist but I couldn’t find it), I read the following answers but couldn’t get much about my problem
Does Java return by reference or by value
This answer says that it could have happened if Integer was mutable, but ArrayList is mutable (Is java.util.List mutable?) so why isn’t it happening?
>Solution :
I think there might be a little misunderstanding here. When you do initially List<Integer> obj = Arrays.asList(1,2,3);, the objected referenced by obj is a list containing 1,2,3. This very list is put in the map.
However, when you do obj = Arrays.asList(4,5,6);, you are assigning a new object to the reference obj.
Try this instead:
public static void main(String[] args){
List<Integer> obj = new ArrayList<>();
obj.add(1);
Map<Integer, List<Integer>> a = new HashMap<>();
a.put(0, obj);
a.get(0).forEach(System.out::println);
obj.add(2);
System.out.println();
a.get(0).forEach(System.out::println);
}