Reputation: 23
Hi i'm using the clone() method to copy the reference of my arraylist like this
import java.util.*;
public class Cloning {
public static void main(String[] args) {
ArrayList v = new ArrayList();
for(int i = 0; i < 10; i++ )
v.add(new Int(i));
System.out.println("v: " + v);
ArrayList v2 = (ArrayList)v.clone();
for(int i=0;i<v2.size();i++ )
((Int)v2.get(i)).increment();
System.out.println("v: " + v);
}
}
The output is
v: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
v: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Otherwise if i make this
import java.util.*;
public class Cloning {
public static void main(String[] args) {
ArrayList v = new ArrayList();
for(int i = 0; i < 10; i++ )
v.add(new Int(i));
System.out.println("v: " + v);
ArrayList v2 = v;
for(int i=0;i<v2.size();i++ )
((Int)v2.get(i)).increment();
System.out.println("v: " + v);
}
}
The output is the same. So my question is, if i use the clone() method for arraylist or i do ArrayList v2 = v; is the same thing?
Upvotes: -1
Views: 444
Reputation: 103263
The output is the same. So my question is, if i use the clone() method for arraylist or i do ArrayList v2 = v; is the same thing?
It isn't:
List<String> a = new ArrayList<String>();
List<String> b = makeCopy(a);
a.add("Hello");
System.out.println(b);
This code will print []
(as in, a blank list with nothing in it), if makeCopy
is:
public List<String> makeCopy(List<String> in) {
return new ArrayList<String>(in); // or .clone(), same thing.
}
But it'll print [Hello]
if makeCopy is just return in;
(the equivalent of List<String> b = a;
.
It's not the components - those aren't cloned (hence, 'shallow'). It is the list itself. An actual clone means that there are 2 list objects, and thus you can modify one list without modifying the other. The list objects just contain references (pointers), and shallow cloning the list doesn't clone those objects.
With List<String> b = a
you just have 2 references to a single list. Given that there is just the one list, if you modify a list (either a.add()
or b.add()
, well, there's only one list, so, that's the one you are changing, and a and b reflect the change identically:
b = a;
System.out.println(a.size()); // prints 1
b.add("Goodbye");
System.out.println(a.size()); // prints 2
Having a
remain a list of size 1? That requires cloning the list.
Upvotes: 2