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".
If I use something like:
Hashtable<String, byte[]>
- all is good. Can someone explain why?
Thanks.
HashMap doesn't handle primitives, just objects. Related SO question, but with int being the value, not the key.
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.
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<Integer, ArrayList<Byte>> table = new Hashtable<Integer, ArrayList<Byte>>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With