Java中带有整数键的哈希表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3674912/
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
Hashtable with integer key in Java
提问by Simon Rigby
I'm trying to create a Hashtable as in the following:
我正在尝试创建一个哈希表,如下所示:
Hashtable<int, ArrayList<byte>> block = new Hashtable<int, ArrayList<byte>>();
but I am getting an error on both int and byte saying "Dimensions expected after this token".
但是我在 int 和 byte 上都收到错误消息,提示“此令牌后预期的尺寸”。
If I use something like:
如果我使用类似的东西:
Hashtable<String, byte[]>
- all is good. Can someone explain why?
Hashtable<String, byte[]>
- 一切都很好。有人可以解释为什么吗?
Thanks.
谢谢。
采纳答案by Bart Kiers
In Java's core collection classes you can only store reference types (something that extends a java.lang.Object). You cannotstore primitives like int
and byte
. Note that an array like byte[]
is no primitive but also a reference type.
在 Java 的核心集合类中,您只能存储引用类型(扩展 java.lang.Object 的东西)。您不能存储像int
和这样的原语byte
。请注意,像这样的数组byte[]
不是原始类型,而是引用类型。
As @Giuseppe mentioned, you can define it like this:
正如@Giuseppe 提到的,你可以这样定义它:
Hashtable<Integer, ArrayList<Byte>> table = new Hashtable<Integer, ArrayList<Byte>>();
and then put primitive int
's in it as keys:
然后将原语int
作为键放入其中:
table.put(4, ...);
because since Java 1.5, autoboxingwill automatically change the primitive int
into an Integer
(a wrapper) behind the scenes.
因为从 Java 1.5 开始,自动装箱会在幕后自动将原语更改int
为Integer
(包装器)。
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 Troveand Colt.
如果您需要更高的速度(并且测量包装器集合类是问题!),您可以使用可以在其集合中存储原语的第 3 方库。此类库的一个示例是Trove和Colt。
回答by Karl Johansson
Java generics can't be instantiated with primitive types. Try using the wrapper classes instead:
Java 泛型不能用原始类型实例化。尝试改用包装类:
Hashtable<Integer, ArrayList<Byte>> block = new Hashtable<Integer, ArrayList<Byte>>();
回答by Yon
You can use Integer instead of int and if you're using java 1.5+ the boxing/unboxing feature will make your life easy when working with it.
您可以使用 Integer 而不是 int,如果您使用的是 java 1.5+,装箱/拆箱功能将使您在使用它时变得轻松。
Hashtable<Integer,byte[]> block = new Hashtable<Integer,byte[]>();