Java Vector: clear vs removeAllElements method
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 mem开发者_如何学Pythonory) whereas clear() releases memory. Depending on the application, either may be desirable.
I would appreciate some input. Thanks.
Per the JavaDoc about the .removeAllElements() method.
"This method is identical in functionality to the clear method (which is part of the List interface)."
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.
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.
As in JavaDoc for Vector.removeAllElements():
Removes all components from this vector and sets its size to zero. This method is identical in functionality to the clear() method
So they are identical. clear()
is better because of compliance with the newer Java Collections interface.
精彩评论