0

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?

BeastMaster64
  • 147
  • 1
  • 13

2 Answers2

3

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);
    }
ferrouskid
  • 466
  • 2
  • 7
  • Ah, I feel stupid, I in my mind replaced the object and kept the reference and forgot that map copies a reference to the object, thanks for pointing it out. – BeastMaster64 Jan 05 '22 at 17:24
  • 1
    Don't worry we all been there! I make silly errors all the time, what really helps me is a nice IDE (I use intellij for java and vscode for python/js/ts). Good luck! – ferrouskid Jan 05 '22 at 17:32
2

First of: Arrays::asList creates a fixed-sized list.
Second this line

obj = Arrays.asList(4,5,6);

creates a new list object.

To test your hypothesis, we need to create a modifiable list, add it to the map, then modify the list:

public static void main(String[] args) {
  List<Integer> obj = new ArrayList<>(Arrays.asList(1,2,3));
  Map<Integer, List<Integer>> a = new HashMap<>();
  a.put(0, obj);
  a.get(0).forEach(System.out::print);
  obj.clear();
  obj.add(4);
  obj.add(5);
  obj.add(6);
  System.out.println();
  a.get(0).forEach(System.out::print);
}

Ideone demo

We see the following output:

123
456

which confirms that the map does not copy the list, but only holds a reference to it.

Turing85
  • 18,217
  • 7
  • 33
  • 58