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!!!
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.
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.
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.
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.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With