Java – reference two ArrayLists to the same object
I have this code But I don't know how to explain the results:
ArrayList<String> first = new ArrayList<String>(); first.add("1"); first.add("2"); first.add("3"); ArrayList<String> second = new ArrayList<String>(); second = first; System.out.println("before modified:"+second.size()); second.clear(); System.out.println("after modified:"); System.out.println(" First:"+first.size()); System.out.println(" Second:"+second.size());
The result will be: 3 / 0 / 0
The problem I don't know is: when you assign the first = the second; Therefore, the first and second arrays will both point to the same object (1, 2, and 3) After clearing all elements on the second array, all references between the second array and these objects will be loose (no problem here)
What I don't know is that these objects (1, 2, and 3) still refer to the first array Why is the size of the first array 0
Please explain
Thank you:)
Solution
By specifying second = first, there is only one ArrayList with two references The references are the same Therefore, when clear is called with one of the two references (the first or the second), clear is performed on the referenced ArrayList
This is something else you first thought of No, it will be Magic (in Java) to assign the second = first to all the string references you add to the first string will be copied to a new ArrayList object