我正在尝试创建一个哈希表,如下所示:
Hashtable<int, ArrayList<byte>> block = new Hashtable<int, ArrayList<byte>>();
但是我在int和byte上都收到一个错误,说“此令牌后应有尺寸”。
如果我使用类似:
Hashtable<String, byte[]>- 一切都很好。有人可以解释为什么吗?
Hashtable<String, byte[]>
谢谢。
在Java的核心集合类中,您只能存储引用类型(扩展java.lang.Object的对象)。您 不能 存储诸如int和的基元byte。请注意,like数组byte[]不是原始数组,而是引用类型。
int
byte
byte[]
如@Giuseppe所述,您可以这样定义它:
Hashtable<Integer, ArrayList<Byte>> table = new Hashtable<Integer, ArrayList<Byte>>();
然后将primitive int的作为键:
table.put(4, ...);
因为从Java 1.5开始,自动装箱将自动将原语更改为幕后int的Integer(包装器)。
Integer
如果您需要更快的速度(并且测量包装器集合类是问题!),则可以使用第3方库,该库可以在其集合中存储基元。Trove和Colt是此类库的示例。