如果哈希表中的键是一个类对象,那么containsKey是如何工作的?

当我们在哈希表中放置一个类Object(有三个数据成员)时,如何防止将另一个条目放入其密钥具有相同三个数据成员的哈希表中? 我猜这将是一个新的对象。 因此,即使存在与等待插入的数据成员具有相同数据成员的键(此类对象),hashtable.containsKey()也将返回false。

更清楚:我有一个类似的课程

class Triplet { private Curr curr; private Prev prev; private Next next; } 

我有一个哈希表结构,如:

 Hashtable table = new Hashtable(); 

当我做:

 if(!table.containsKey(triplet_to_inserted)) table.put(triplet, new Integer(0)); 

即使表中包含已具有相同数据成员的三元组,这是否会插入副本? 即:triplet_to_be_inserted.curr,triplet_to_be_inserted.next和triplet_to_be_inserted.prev如果是,如何防止这种情况?

此外,对于要插入的任何条目,containsKey()是否会返回true? 如何解决这个问题?

谢谢。

所有具有在类哈希数据结构中用作键的实例的类必须正确实现equalshashCode方法。 不久前,Brian Goetz就此发表了一篇很棒的文章 。

在不知道CurrPrevNext的结构的情况Next ,确切的示例很难,但假设它们不是null并且具有合理的hashCode实现,那么您可以执行以下操作:

 public boolean equals(Object obj) { if (!(obj instanceof Triplet)) { return false; } else { Triplet that = (Triplet)obj; return this.curr.equals(that.curr) && this.next.equals(that.next) && this.prev.equals(that.prev); } } public int hashCode() { int hash = this.curr.hashCode(); hash = hash * 31 + this.next.hashCode(); hash = hash * 31 + this.prev.hashCode(); return hash; } 

最简单的方法是使用Eclipse的生成hashCode()和equals()。 您可以选择hashCode和equals计算应考虑哪些成员,因此如果您有一些临时成员(您没有),您只能使用相关的成员。

和Curr,Prev和Next类似(并且递归地)…

来自java文档:

要成功存储和检索哈希表中的对象,用作键的对象必须实现hashCode方法和equals方法。