Hashtable and integer keys in Java
I am trying to create a hashtable as follows:
Hashtable<int,ArrayList<byte>> block = new Hashtable<int,ArrayList<byte>>();
But I will display "the size after this token" on both integers and bytes
If I use something like:
Hash table < string, byte [] > – everything is fine Can anyone explain why
thank you.
Solution
In Java's core collection classes, you can only store reference types (things that extend Java. Lang. object) You cannot store primitives like int and byte Please note that an array like byte [] is not original, but also a reference type
As @ Giuseppe said, you can define it this way:
Hashtable<Integer,ArrayList<Byte>> table = new Hashtable<Integer,ArrayList<Byte>>();
Then put the original int in it as the key:
table.put(4,...);
Since Java 1.5, autoboxing will automatically change the original int to the following integer (wrapper)
If you need more speed (and measuring the wrapper collection class is a problem!), You can use third - party libraries to store primitives in their collections An example of such a library is trove and colt