Hashtable with int array as key in java

I am trying to make a hash table in java where the keys are int [] but they do not work. I made a small 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 calls should return the same result, since both arrays are equal, but they do not fit. Here is the result of running the code:

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

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

+7
source share
3 answers

You can use int [] as a key, but it must be the same array, not just the same content. (This means that he will not do what you want)

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

The only way to do this is to use List <Integer> as a key or wrapper for your int [], for example. 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 an obsolete IMHO class, do not use it unless you need to.

+14
source

You can create strings from arrays before hashing (if the length of the array is not excessively long) in addition to wrapping in List

If you choose the latter, there is a static Arrays method described here From the Java static Arrays class at http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html #toString (int [ ] )

 h1.put(Arrays.toString(test1), s0); 

Now you can hash this, and equivalent arrays will hash to the same thing. However, you cannot recreate the array from the key (if Java does not have some kind of eval now?)

.
.
.
,

For curiosity, here I am, stupidly rolling back until I find the method described above:

 public String intArrayToString(int[] x) { String ans = '['; for(i = 0; i < size(x); i++) ans += '' + i + ','; return ans + ']'; } HashTable<String,String> h1 = new HashTable<String,String> h1; h1.put(intArrayToString(test1), s0); 

If there is some kind of static toString that does this, I apologize. PS - Does Java have a reduction function (and lambdas), a foreach loop or eval (to restore keys to an array, if necessary)? They will make this decision more enjoyable ...

0
source

The root cause is the array test0 and test1 have different hash codes . If 2 keys have different hash codes, they can never be the same.

0
source

All Articles