当我们将一个类对象(具有三个数据成员)放入哈希表中时,如何防止将另一个条目放入哈希表中,其键具有相同的三个数据成员?因为我猜这将是一个新对象。因此 hashtable.containsKey() 将返回 false 即使存在一个键(此类对象)与等待插入的键具有完全相同的数据成员。
更清楚: 我有一个类
class Triplet {
private Curr curr;
private Prev prev;
private Next next;
}
我的哈希表结构如下:
Hashtable<Triplet, Integer> table = new Hashtable<Triplet, Integer>();
当我这样做时:
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? 如何解决这个问题?
谢谢。
最佳答案
在类散列数据结构中将实例用作键的所有类必须正确实现equals
和hashCode
方法。 Brian Goetz 有 a great article on this不久前。
不知道 Curr
、Prev
和 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;
}
关于java - 如果哈希表中的键是类对象,那么 containsKey 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6485186/