Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable with integer key in Java

Tags:

java

hashtable

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.

like image 596
Simon Rigby Avatar asked Sep 09 '10 08:09

Simon Rigby


People also ask

Can we use integer as key in HashMap?

HashMap doesn't handle primitives, just objects. Related SO question, but with int being the value, not the key.

Can we get key from value in Hashtable?

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.

How do you add a key value pair to a Hashtable in Java?

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.

What is Hashtable in Java with example?

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.


1 Answers

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.

like image 118
Bart Kiers Avatar answered Oct 29 '22 12:10

Bart Kiers