How to make Java hashtable Containskey is applicable to array?
•
Java
I'm 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,0};; System.err.println(map.containsKey(temp2));
Not applicable to Containskey (because the print 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));
Work (print "true")
I know it's related to object references, but I can't reach any solution after searching
Can I use hashtable to find keys with array type anyway? I just want to test whether a specific array is used as a key in hashtable
Any click would be great thank you!!!
Solution
You can't use arrays as keys in hashtable / HashMap because they won't override the default implementation of object's equals, which means temp Equals (temp2) if and only if temp = = temp2, this is an incorrect case in your case
You can use set < byte > or list < byte > instead of the key's byte []
For example:
Hashtable<List<Byte>,Byte[]> map = new Hashtable<List<Byte>,Byte[]>(); Byte[] temp = {1,0}; map.put(Arrays.asList(temp),temp); Byte[] temp2 = {1,0};; System.err.println(map.containsKey(Arrays.asList(temp2)));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码