I have this code. But I do not know how to explain the result:
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 about is when you assign first = second;, so the first and second arrays will point to the same object (1,2 and 3). after clearall the elements in the second array, so the whole link between the second array and these objects will be lost (no problem here).
What I don't know is: but these objects (1,2 and 3) still contain a reference to the first array. Why the first size of the array is 0.
Please explain me.
Thank:)
source
share