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

时间:2015-11-04 10:09:11

标签: java hashtable

很抱歉提出这个问题,但我是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));

不适用于.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));

有效(打印结果为“True”)

我知道它与对象引用有关,但在搜索后无法找到任何解决方案......

无论如何我可以使用Hashtable查找具有Array类型的键吗?我只想测试一个特定的数组是否在Hashtable中作为键...

任何点击都会很棒。谢谢!!!

1 个答案:

答案 0 :(得分:6)

您不能将数组用作HashTable/HashMap中的键,因为它们不会覆盖Object equals的默认实现,表示temp.equals(temp2)当且仅当temp==temp2时,在您的情况下不正确。

您可以使用Set<Byte>List<Byte>代替byte[]作为密钥。

例如:

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)));
相关问题