Hashtable与Java中的整数键 [英] Hashtable with integer key in Java
问题描述
我正在尝试创建一个Hashtable,如下所示:
I'm trying to create a Hashtable as in the following:
Hashtable<int, ArrayList<byte>> block = new Hashtable<int, ArrayList<byte>>();
但我在int和byte上都收到错误,说此标记后预期的尺寸。
but I am getting an error on both int and byte saying "Dimensions expected after this token".
如果我使用类似的东西:
If I use something like:
Hashtable< String,byte []>
- 一切都很好。有人可以解释原因吗?
Hashtable<String, byte[]>
- all is good. Can someone explain why?
谢谢。
推荐答案
在Java的核心集合类只能存储引用类型(扩展java.lang.Object的东西)。你不能存储基元,如 int
和 byte
。请注意,像 byte []
这样的数组不是原始数组,也是引用类型。
In Java's core collection classes you can only store reference types (something that extends a java.lang.Object). You cannot store primitives like int
and byte
. Note that an array like byte[]
is no primitive but also a reference type.
正如@Giuseppe所提到的,您可以这样定义:
As @Giuseppe mentioned, you can define it like this:
Hashtable<Integer, ArrayList<Byte>> table = new Hashtable<Integer, ArrayList<Byte>>();
然后将原始 int
放入它作为键:
and then put primitive int
's in it as keys:
table.put(4, ...);
因为自Java 1.5起,自动装箱会自动将原始 int
更改为整数
(包装)幕后。
because since Java 1.5, autoboxing will automatically change the primitive int
into an Integer
(a wrapper) behind the scenes.
如果你需要更高的速度(并且测量了包装器集合类是问题! )您可以使用可以在其集合中存储基元的第三方库。这种库的一个例子是 Trove 和柯尔特。
If you need more speed (and measured the wrapper collection classes are the problem!) you could use a 3rd party library that can store primitives in their collections. An example of such libraries are Trove and Colt.
这篇关于Hashtable与Java中的整数键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!