Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java addAll(collection) vs new ArrayList(collection)

Why do i get different behaviors with:

  1. Collection col2 = new ArrayList(col);

  2. Collection col2 = new ArrayList();
    col2.addAll(col)

I'm working with viewers, and the code is complex, and i'm trying to explain the "root" of the problem. Another interesting fact is the next one...

//IF i use this code i have the correct behavior in my app:
public void updateCollection(Collection<Object> col) {
    this.objectCollection.clear();
    this.objectCollection.addAll(col);
}

//IF i use this code i have unexpected behavior in my app:
public void updateCollection(Collection<Object> col) {
    this.objectCollection=new ArrayList(col);
}
like image 539
marcolopes Avatar asked Nov 21 '10 15:11

marcolopes


1 Answers

This code works:

public void updateCollection(Collection<Object> col) {
    this.objectCollection.clear();
    this.objectCollection.addAll(col);
}

But this introduces problems:

public void updateCollection(Collection<Object> col) {
    this.objectCollection = new ArrayList(col);
}

I suspect that this variation on your first method would introduce identical problems:

public void updateCollection(Collection<Object> col) {
    this.objectCollection = new ArrayList();
    this.objectCollection.clear();
    this.objectCollection.addAll(col);
}

Why? Evidently you have another reference to objectCollection in use somewhere. Somewhere in your code, another object is saying (for instance):

myCopyOfObjectCollection = theOtherObject.objectCollection;

If you're using a getter, that doesn't change the underlying behavior - you are still keeping another reference around.

So if on initial assignment, say, the collection contained {1, 2, 3}, you start out with:

  • this.objectCollection: {1, 2, 3}
  • that.copyOfObjectCollection: {1, 2, 3}

When you assign a new ArrayList to this.objectCollection, and populate it with, say, {4, 5, 6}, you get this:

  • this.objectCollection: {4, 5, 6}
  • that.copyOfObjectCollection: {1, 2, 3}

So that is still pointing to the original ArrayList.

like image 141
Carl Manaster Avatar answered Sep 20 '22 18:09

Carl Manaster