Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Vector: clear vs removeAllElements method

Tags:

java

I'm new to Java.

Which is more efficient for Vectors -- clear() or removeAllElements(). I would guess removeAllElements since it leaves the capacity unchanged (doesn't release memory) whereas clear() releases memory. Depending on the application, either may be desirable.

I would appreciate some input. Thanks.

like image 624
Paul Avatar asked Mar 27 '11 00:03

Paul


3 Answers

Per the JavaDoc about the .removeAllElements() method.

"This method is identical in functionality to the clear method (which is part of the List interface)."

like image 169
Suroot Avatar answered Oct 04 '22 19:10

Suroot


Vector was in Java 1.1, and since Java 1.4 the new Collection API has appeared, defining a general List interface with the function clear().

Use clear(), because it is the modern API. Both functions are equivalent.

Btw. consider using ArrayList instead of Vector. ArrayList is not synchronized, and so its faster if you don't access the List from different Threads simultanously.

like image 20
Daniel Avatar answered Oct 04 '22 19:10

Daniel


When you are worried about efficiency (and there’s quite a chance that you are for the wrong reasons), don’t use Vector at all, but use a List implementation (such as ArrayList) instead. If you are using Vector because of its internal synchronization (and I have my doubts about that), use a synchronizedList instead.

Also, Vector.clear() just calls Vector.removeAllElements() so there is no functional difference, just one more function call when using Vector.clear(). That being said, if you have to use Vector, call Vector.clear() because it adheres to the more modern Collection interface and states a clearer intent.

like image 35
Bombe Avatar answered Oct 04 '22 20:10

Bombe