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?