问题描述
Java API 中是否有与 Vector
或 ArrayList
类等价的可扩展数组类,可以与基元(int、char、double 等)一起使用?
Is there an expandable array class in the Java API equivalent to the Vector
or ArrayList
class that can be used with primitives (int, char, double, etc)?
我需要一个快速、可扩展的整数数组,为了将它们与 Vector
或 一起使用,必须将它们包装在
.我的 google-fu 让我失望了.Integer
类中似乎很浪费数组列表
I need a quick, expandable array for integers and it seems wasteful to have to wrap them in the Integer
class in order to use them with Vector
or ArrayList
. My google-fu is failing me.
推荐答案
不幸的是没有这样的类,至少在 Java API 中是这样.有 Java 原始集合 3rd 方产品.
There is unfortunately no such class, at least in the Java API. There is the Primitive Collections for Java 3rd-party product.
将自动装箱与现有集合类(特别是 List
实现)一起使用是非常危险的.例如:
It's pretty dangerous to use auto-boxing together with existing collection classes (in particular List
implementations). For example:
List<Integer> l = new ArrayList<Integer>();
l.add(4);
l.remove(4); //will throw ArrayIndexOutOfBoundsException
l.remove(new Integer(4)); //what you probably intended!
而且它也是神秘的NullPointerExceptions
访问的常见来源(可能通过Map
):
And it is also a common source of mysterious NullPointerExceptions
accessing (perhaps via a Map
):
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Hello", 5);
int i = m.get("Helo Misspelt"); //will throw a NullPointerException
这篇关于基元的 Java 向量或 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!