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!!!
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)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.