开发者

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 th开发者_如何学Ce 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


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.


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.


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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜