yossi
yossi

Reputation: 13315

Java clearing a list by creating a new instance

I was looking through Java code, and I came across this code:

list = new ArrayList();
uselist(list);

if (condition)
   list = new ArrayList();

What's the use of this, as opposed to simply using the clear() method of ArrayLists.

is using the new command to clear a list is ok and is it faster than clearing a list ?

i am using java version 1.6

Upvotes: 1

Views: 2132

Answers (5)

Anders Forsgren
Anders Forsgren

Reputation: 11101

Do note that clearing and re-instantiating a list is not the same thing!

Consider this example:

a = new ArrayList();
a.add("Hello")
b = a;
a = new ArrayList();   // a is now empty while b contains hello!

Versus

a = new ArrayList();
a.add("Hello")
b = a;
a.clear();            // Both a and b are now empty.

If the side-effects (shared references) are not an issue, then it is just two ways of clearing a list. It should probably not be a performance issue unless this is called millions of times.

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1500893

No, they don't do the same thing. The method clear() clears an existing list - anything which still has a reference to the list and looks at it later will see that it's empty.

The approach with the new keyword, changes the value of the list variable but does nothing to the existing ArrayList object - so if anything else has a reference to the same object, they won't see any changes.

Upvotes: 9

user425367
user425367

Reputation:

The difference can be fatal and hard to see. For example hibernate will flip out of you use list = new ArrayList(); and then try to update the list in the db but it works just fine with clear() as hibernate then can see the connection.

clear() // operates on your old object 

list = new ArrayList(); // list will be a new object the old will be GCed

Upvotes: 0

Simone Gianni
Simone Gianni

Reputation: 11662

Wether it is the same or not it depends on what uselist(...) does internally with the list.

For example, suppose you have the following code in uselist :

public void uselist(List l) {
    this.mylist = l;
}

In that case, your code will create a new list and not touch this.mylist . If instead you call .clear() on it, you are clearing that same list.

Upvotes: 2

Thomas
Thomas

Reputation: 88707

If the list is used elsewhere calling clear() might cause side effects. However, if that is not the case, I'd say that creating a new list instead of clearing the old one might be faster (however, probably for huge lists only, since ArrayList's clear() just iterates over the elements and set's them as null), but most likely it's just a matter of programming style.

Upvotes: 3

Related Questions