【问题标题】:How do I make Java Hashtable.containsKey to work for Array?如何使 Java Hashtable.containsKey 为 Array 工作?
【发布时间】:2016-02-04 18:40:57
【问题描述】:

很抱歉问这个问题,但我是 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(因为打印结果为“假”)

Hashtable<Integer,Integer> mapint = new Hashtable<Integer, Integer>();
int i = 5;
mapint.put(i, i);
int j = 5;
System.err.println(mapint.containsKey(j));

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

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

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

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

【问题讨论】:

  • 对于您的具体问题,您可以使用ByteBuffermap.put(ByteBuffer.wrap(temp), temp); 包装数组。

标签: java hashtable


【解决方案1】:

您不能将数组用作HashTable/HashMap 中的键,因为它们不会覆盖Objectequals 的默认实现,这意味着temp.equals(temp2) 当且仅当temp==temp2,即在你的情况下是不正确的。

您可以使用Set&lt;Byte&gt;List&lt;Byte&gt; 代替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)));

【讨论】:

  • 感谢您的评论!在这种情况下,我需要使用替代方法,我能想到的一种天真的方法是将数组转换为字符串,但这似乎很愚蠢……有没有办法解决这个问题?
  • @Jack 看我的例子。顺便说一句,如果键和值相同,为什么要使用 HashTable?您可以改用HashSet
  • 非常感谢您的解决方案。我工作!我将研究使用 Set 或 List...
  • 抱歉造成混淆,实际上 Key 和 Value 是不一样的,它们只是这个例子的快速测试:-)
  • 再次感谢您的解决方案!
猜你喜欢
  • 2013-02-01
  • 2016-06-25
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 2011-02-20
  • 2011-02-07
  • 2012-04-22
  • 1970-01-01
相关资源
最近更新 更多