tags:

views:

155

answers:

3

Hello all,

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.

+8  A: 

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.

Bart Kiers
Ah .. many thanks.
Simon Rigby
You can use the wrapper object to build your Hastable: Hashtable<Integer, ArrayList<Byte>>() . The auto(un)boxing feature of java will make the difference almost unnoticeable. It is however quite slow, since it boxes and unboxes integers for every access. For further reference please read http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html .
Giuseppe Cardone
@Giuseppe, good point: added it to my answer.
Bart Kiers
Note also that you (almost) never want to use an array as a key type for a Map, as all arrays only support object-identity as a basis for equality. They're fine as a payload though.
Donal Fellows
@Donal, agreed. But no one is/was talking about the key being an array, right? Or did I misread something...
Bart Kiers
@Bart: You'd be surprised what people (mis-)read into random things they find on the net. :-(
Donal Fellows
Thanks very much .. that's sorted it.
Simon Rigby
A: 

Java generics can't be instantiated with primitive types. Try using the wrapper classes instead:

Hashtable<Integer, ArrayList<Byte>> block = new Hashtable<Integer, ArrayList<Byte>>();
Karl Johansson
A: 

You can use Integer instead of int and if you're using java 1.5+ the boxing/unboxing feature will make your life easy when working with it.

Hashtable<Integer,byte[]> block = new Hashtable<Integer,byte[]>();
Yon