Link to two arrayList objects on the same objects

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:)

+3
source share
5 answers

second = first, arraylist . . , (first second), arraylist.

- , . , second = first , , ArrayList, ( Java).

+6

first = second, ArrayList . .clear , ArrayList. ArrayList.

ArrayList1 ArrayList2, - : ArrayList<String> second = new ArrayList<String>(first);

+3

(1,2 3) . 0.

ArrayList<String> second = new ArrayList<String>();
second = first;

ArrayList<String> second = first;

arraylist, arraylist. , , "" arraylist, , arraylist.

+1

ArrayList , . , , . ( , ).

+1

Java ( ) ( ) , .

for instance

second = first;

assigns a link, so the first and second now refer to the same object. Objects are not copied, neither in assignments, nor when passing arguments (what is copied / assigned is a link).

+1
source

All Articles