Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable with int array as key in java

I'm trying to make a hashtable in java where the keys are int[], but it dosen't work. I have made a little test program to show my problem:

public class test{
        public static void main(String[] args){
                int[] test0 = {1,1};
                int[] test1 = {1,1};
                Hashtable<int[], String> ht = new Hashtable<int[], String>();
                String s0 = "foo";

                ht.put(test0, s0);

                System.out.println("the result from ht.get(test1)");
                System.out.println(ht.get(test1));
                System.out.println("the result from ht.get(test0)");
                System.out.println(ht.get(test0));
        }
}

My intention is that both ht.get calles should return the same result, since the two arrays are equal, but they dont. Here is the result from running the code:

the result from ht.get(test1)
null
the result from ht.get(test0)
foo

Am I missing something here or is it just impossible to use int[] as keys in a hastable?

like image 493
Niels Hansen Avatar asked Jan 08 '11 09:01

Niels Hansen


People also ask

Can I use array as key in HashMap Java?

Arrays in Java use object identity to determine equality. If we create HashMap with byte array as the key, we'll be able to retrieve a value only using exactly the same array object.

Can we store array as key in HashMap?

You directly cannot give the new array as the key, as its reference is not present in the map.

What can be used as the key in a Hashtable?

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.

Can you hash an array in Java?

hashCode(Object[]) method returns a hash code based on the contents of the specified array. If the array contains other arrays as elements, the hash code is based on their identities rather than their contents. For any two arrays a and b such that Arrays.


1 Answers

You can use int[] as the key, but it has to be the same array, not just have the same content. (Which means it won't do what you want)

Arrays are not equals() or have the same hashCode() based on their content on if they are the same array.

The only way you can do this is to use a List<Integer> as a key or a wrapper for your int[] e.g. TIntArrayList.

try the following.

List<Integer> test0 = Arrays.asList(1,1);
List<Integer> test1 = Arrays.asList(1,1);
Map<List<Integer>, String> ht = new HashMap<List<Integer>, String>();

BTW: Hashtable is a legacy class IMHO, don't use it unless you have to.

like image 151
Peter Lawrey Avatar answered Sep 27 '22 19:09

Peter Lawrey