Hashtable with integer key in Java

后端 未结 3 715
清歌不尽
清歌不尽 2021-01-02 04:15

I\'m trying to create a Hashtable as in the following:

Hashtable> block = new Hashtable>();         


        
3条回答
  •  被撕碎了的回忆
    2021-01-02 04:35

    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.

    As @Giuseppe mentioned, you can define it like this:

    Hashtable> table = new Hashtable>();
    

    and then put primitive int's in it as keys:

    table.put(4, ...);
    

    because since Java 1.5, autoboxing will automatically change the primitive int into an Integer (a wrapper) behind the scenes.

    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.

提交回复
热议问题