How can I set Hashtable value to be array?

时间:2015-08-07 01:58:18

标签: java data-structures hashtable

Is it possible to create in Java a Hashtable where key is integer and values is an array of integer. I tried below code, and it doesn't work. Does anyone know how to make such data-structure?

int[] a = {0, 0, 0};
// does not work!!!!
Hashtable<int, int[]> entry = new Hashtable<NodeT, a>;

2 个答案:

答案 0 :(得分:3)

Several things:

1) Please don't use Hashtable, instead use HashMap. Hashtable is the old, synchronized version and people don't use it anymore.

Please refer to this excellent answer when to use Hashtable.

2) Please code against an interface unless you have good reason not to (so your entry should be of type Map instead). This allows you to change the underlying implementation to a different kind of map easily.

3) Please read the official Java tutorial it explains how to use the map interface and basically it should be more or less like this:

Map<Integer, int[]> entry = new HashMap<>();

Or if you are using Java older than 7 Map<Integer, int[]> entry = new HashMap<Integer, int[]>(); since the diamond operator was introduced in Java7. Also notice that on both sides you need the same values inside <>. Why would you write <NodeT, a> on the right hand side? I gather a was a try to initialize it with a but I don't understand the NodeT.

You have to use Integer instead of int as generics in Java do not accept primitive types. int[] works fine since this is an object in Java.

After that you need to put your entries into the map.

答案 1 :(得分:2)

  1. Don't use Hashtable. Use HashMap. HashMap is more performant and Hashtable has been basically deprecated since Java 2.
  2. You can't use int as a key, it has to be an Object, which in this case is the autoboxed Integer, so use:

    Map<Integer, int[]> = new HashMap<>();