Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Java Hashtable.containsKey to work for Array?

Tags:

java

hashtable

Sorry to ask this question but i am 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 (as 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 (the printed result is "True")

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

Is there anyway I can use Hashtable to find key with Array type? I just want to test if a specific array is in Hashtable as a key...

Any hits would be great. Thank!!!

like image 973
Jack Avatar asked Nov 04 '15 10:11

Jack


People also ask

How do 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. equals(a, b), it is also the case that Arrays.

Can we store array as key in HashMap?

In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.

What is Hashtable containsKey?

Hashtable containsKey() Method in Java util. Hashtable. containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table.

How does a Hashtable work internally?

Hashtable is a kind of Hash map but is synchronized. Hash map is non–synchronized, permits one null key & multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, the key/values pairs are stored in Hashtable.


1 Answers

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

You can use a Set<Byte> or List<Byte> instead of a 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)));
like image 60
Eran Avatar answered Oct 01 '22 20:10

Eran