Reputation: 11
What is the difference between:
for (ArrayList<Integer> a : result)
temp.add(new ArrayList<Integer>(a));
and
for (ArrayList<Integer> a : result)
temp.add(a);
?
Upvotes: 1
Views: 36
Reputation: 4609
This is adding a new Arraylist with item of a in temp while iterating result arraylist
for (ArrayList a : result)
temp.add(new ArrayList(a));
This is adding a in temp while iterating result arraylist
for (ArrayList a : result)
temp.add(a);
Upvotes: 0
Reputation: 61148
Lets start with a very simple example:
final List<String> a = new ArrayList<>(Arrays.asList("a", "b", "c"));
System.out.println(a);
Output:
[a, b, c]
Now, lets copy using =
final List<String> b = a;
b.add("d");
System.out.println(b);
System.out.println(a);
System.out.println(a == b);
Output:
[a, b, c, d]
[a, b, c, d]
true
Okay, now lets copy using new
:
final List<String> c = new ArrayList<>(b);
c.add("e");
System.out.println(c);
System.out.println(b);
System.out.println(a);
System.out.println(c == b);
Output:
[a, b, c, d, e]
[a, b, c, d]
[a, b, c, d]
false
Okay, so when we copy using =
we copy the reference to the same List
. When we copy using the copy constructor we actually create an entirely separate List
that contains the same elements.
So a
and b
are references to some same list, they will always return the same result, and any action on a
will affect b
- think of them as aliases for some other entity.
c
is a physical copy of a
(and b
for that matter) where we have constructed a new
entity and copied the contents of a
into it.
So, to answer your question; your first method copies the references and your second method copies the contents.
Upvotes: 1
Reputation: 17577
for (ArrayList a : result) temp.add(new ArrayList(a));
Will add a new ArrayList
to temp
that contains the elements of a
.
See: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29
Adding or deleting stuff in a
, won't change anything for the list that was added to temp
.
for (ArrayList a : result) temp.add(a);
Will add a
to temp
. Due to the same reference, changes of a
affect the list that was added to temp
.
Upvotes: 1
Reputation: 703
new ArrayList(a)
actually copies the Arraylist that you already have, see the javadoc of the constructor
So when you have
ArrayList A = new Arraylist();
//fill the arraylist
ArrayList B = new ArrayList(a);
A
and B
will actually contain the same elements, but A == B
will return false
Upvotes: 1