I have this code. But I don’t 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 is: when you assign first = second; so, both first and second array will point to same object (1,2 and 3). after you clear all elements on second array, so all reference between second array and these objects will loose (no problem here).
The thing I don’t know is: but these objects (1,2 and 3) still hold reference to first array. Why first array’s size is 0.
Please explain for me.
Thanks 🙂
By assigning
second = first, there is only one arraylist with two references. The references are the same. So, when call clear using one of the two references (firstorsecond), clear will be performed on the referenced arraylist.This is something else than you first thought. It’s not so that assigning the
second = firstall the references of the strings you added to the first one, will be copied into a new ArrayList object, that would be magic (in Java).