Java Vector:clear 与 removeAllElements 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5446383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Vector: clear vs removeAllElements method
提问by Paul
I'm new to Java.
我是 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.
哪个对 Vectors 更有效——clear() 或 removeAllElements()。我猜 removeAllElements 因为它保持容量不变(不释放内存)而 clear() 释放内存。根据应用,两者都可能是可取的。
I would appreciate some input. Thanks.
我会很感激一些输入。谢谢。
回答by Suroot
回答by Daniel
Vectorwas in Java 1.1, and since Java 1.4 the new Collection APIhas appeared, defining a general Listinterface with the function clear().
Vector是在 Java 1.1 中,从 Java 1.4开始出现了新的Collection API,它定义了一个带有函数 clear()的通用List接口。
Use clear(), because it is the modern API. Both functions are equivalent.
使用 clear(),因为它是现代 API。这两个功能是等价的。
Btw. consider using ArrayListinstead of Vector. ArrayList is not synchronized, and so its faster if you don't access the List from different Threads simultanously.
顺便提一句。考虑使用ArrayList而不是 Vector。ArrayList 不是同步的,因此如果您不同时从不同的线程访问 List,它会更快。
回答by Bombe
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.
当您担心效率时(并且您很可能出于错误的原因),根本不要使用Vector
,而是使用List
实现(例如ArrayList
)。如果您使用Vector
它是因为它的内部同步(我对此表示怀疑),请改用 a synchronizedList
。
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.
此外,Vector.clear()
只是调用Vector.removeAllElements()
所以没有功能差异,使用Vector.clear()
. 话虽如此,如果您必须使用Vector
, 调用,Vector.clear()
因为它遵循更现代的Collection
界面并陈述更清晰的意图。
回答by pajton
As in JavaDoc for Vector.removeAllElements():
就像在Vector.removeAllElements() 的JavaDoc 中一样:
Removes all components from this vector and sets its size to zero. This method is identical in functionality to the clear() method
从此向量中删除所有组件并将其大小设置为零。此方法在功能上与 clear() 方法相同
So they are identical. clear()
is better because of compliance with the newer Java Collections interface.
所以它们是相同的。clear()
更好,因为符合较新的 Java Collections 接口。