简体   繁体   English

如何使Java Hashtable.containsKey适用于Array?

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

Sorry to ask this question but i am new to Java. 很抱歉提出这个问题,但我是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") 不适用于.containsKey(因为打印结果为“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") 工作(打印结果为“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? 反正我是否可以使用Hashtable查找具有Array类型的键? I just want to test if a specific array is in Hashtable as a key... 我只是想测试一个特定的数组是否在Hashtable中作为键...

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. 你不能在HashTable/HashMap使用数组作为键,因为它们不会覆盖Objectequals的默认实现,这意味着temp.equals(temp2)当且仅当temp==temp2 ,这不是真的在你的情况下。

You can use a Set<Byte> or List<Byte> instead of a byte[] for your key. 对于键,可以使用Set<Byte>List<Byte>而不是byte[]

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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM