How to make Java Hashtable.containsKey work in Array?

Sorry to ask this question, but I'm new to Java.

Hashtable<byte[],byte[]> map = new Hashtable<byte[],byte[]>(); byte[] temp = {1, -1, 0}; map.put(temp, temp); byte[] temp2 = {1, -1, 0};; System.err.println(map.containsKey(temp2)); 

DOES NOT work with .containsKey (since the printed result is "False")

 Hashtable<Integer,Integer> mapint = new Hashtable<Integer, Integer>(); int i = 5; mapint.put(i, i); int j = 5; System.err.println(mapint.containsKey(j)); 

works (printed result is "True")

I understand that it has something to do with the reference to the object, but could not reach any solution after the search ...

Anyway, can I use a Hashtable to find a key with an array type? I just want to check if a specific array in a Hashtable is as a key ...

Any hits will be great. Thanks!!!

+7
java hashtable
source share
1 answer

You cannot use arrays as keys in a HashTable/HashMap , since they do not override the default implementation of Object equals , which means temp.equals(temp2) if and only if temp==temp2 , which is not true in your case.

You can use Set<Byte> or List<Byte> instead of byte[] for your key.

For example:

 Hashtable<List<Byte>,Byte[]> map = new Hashtable<List<Byte>,Byte[]>(); Byte[] temp = {1, -1, 0}; map.put(Arrays.asList(temp), temp); Byte[] temp2 = {1, -1, 0};; System.err.println(map.containsKey(Arrays.asList(temp2))); 
+6
source share

All Articles