基元的 Java 向量或 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1301588/
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 or ArrayList for Primitives
提问by Daniel Bingham
Is there an expandable array class in the Java API equivalent to the Vectoror ArrayListclass that can be used with primitives (int, char, double, etc)?
Java API 中是否有一个可扩展的数组类,相当于可以与基元(int、char、double 等)一起使用的VectororArrayList类?
I need a quick, expandable array for integers and it seems wasteful to have to wrap them in the Integerclass in order to use them with Vectoror ArrayList. My google-fu is failing me.
我需要一个快速、可扩展的整数数组Integer,为了将它们与Vectoror一起使用,必须将它们包装在类中似乎很浪费ArrayList。我的 google-fu 让我失望了。
回答by oxbow_lakes
There is unfortunately no such class, at least in the Java API. There is the Primitive Collections for Java3rd-party product.
不幸的是没有这样的类,至少在 Java API 中是这样。有Java3rd 方产品的Primitive Collections。
It's pretty dangerous to use auto-boxing together with existing collection classes (in particular Listimplementations). For example:
将自动装箱与现有的集合类(特别是List实现)一起使用是非常危险的。例如:
List<Integer> l = new ArrayList<Integer>();
l.add(4);
l.remove(4); //will throw ArrayIndexOutOfBoundsException
l.remove(new Integer(4)); //what you probably intended!
And it is also a common source of mysterious NullPointerExceptionsaccessing (perhaps via a Map):
它也是神秘NullPointerExceptions访问的常见来源(可能通过 a Map):
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Hello", 5);
int i = m.get("Helo Misspelt"); //will throw a NullPointerException
回答by skaffman
http://trove4j.sourceforge.net/
http://trove4j.sourceforge.net/
The Trove library provides high speed regular and primitive collections for Java.
Trove 库为 Java 提供了高速的常规和原始集合。
Note that because Trove uses primitives, the types it defines do not implement the java.util collections interfaces.
请注意,因为 Trove 使用原语,它定义的类型没有实现 java.util 集合接口。
(LGPL license)
(LGPL 许可证)
回答by Thom Smith
Modern Java supports autoboxing of primitives, so you can say
现代 Java 支持原语的自动装箱,所以你可以说
List<Integer> lst = new ArrayList<Integer>;
lst.add(42);
That at least avoids the syntactic vinegar of new Integer(42).
这至少避免了 new Integer(42) 的语法醋。
回答by cherouvim
There is also Primitive Collections for Javabut it's a bit out of date.
还有用于 Java 的 Primitive Collections,但它有点过时了。
回答by Donald Raab
Eclipse Collectionshas primitive ArrayLists for all primitive types, as well as primitive Sets, Bags, Stacks and Maps. There are immutable versions of all of the primitive container types as well.
Eclipse Collections具有所有原始类型的原始 ArrayLists,以及原始 Sets、Bags、Stacks 和 Maps。所有原始容器类型也有不可变版本。
Note: I am a committer for Eclipse Collections.
注意:我是 Eclipse Collections 的提交者。

