As far as I am aware, in Java reference types are assigned by value, but I can't understand why the following code does what it does. Consider the following code:
Integer num = new Integer(11);
List<Integer> arr = new ArrayList<>();
arr.add(num);
List arr2 = arr;
arr = null;
System.out.println(arr2);
We create an ArrayList with one element in it, then we create the second list and assign it to the first list. My understanding that the second list just points to the same memory location as the first list, so any changes I make to the first list will apply to the second list. If I set the first list to null the second list should become null as well. Why does the console still log 11 and not null?
This is what is happening in the background. I'll try to visualize it so it is easy to understand.
Creating Integer Object:
Integer num = new Integer(11);
num --> @num493857 (some reference not real of course)
@num493857 --> ------
| 11 |
------
Creating ArrayList:
List<Integer> arr = new ArrayList<>();
arr --> @arr7686
@arr7686 --> [] (empty list)
Adding num to Arraylist:
arr.add(num);
arr --> @arr7686 --> [@num493857] // @num493857 has 11 in it
^
|
num
Setting arr2 = arr:
List arr2 = arr;
arr --> @arr7686 --> [@num493857]
^ ^
| |
arr2 num
Setting arr = null:
arr = null
arr --> null
@arr7686 --> [@num493857]
^ ^
| |
arr2 num
Printing arr2:
System.out.println(arr2);
This prints whatever is in the list that is 11.