如果hashtable中的key是一个类对象,containsKey如何工作?

如果hashtable中的key是一个类对象,containsKey如何工作?,第1张

如果hashtable中的key是一个类对象,containsKey如何工作?

在具有类似散列的数据结构中将实例用作键的所有类,都 必须 正确实现

equals
and
hashCode
方法。Brian Goetz
从前有一篇很棒的文章。

如果不知道的结构

Curr
Prev
以及
Next
和详细的例子是困难的,但假设它们不为空,并有合理的
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;}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5164872.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-18
下一篇2022-11-18

发表评论

登录后才能评论

评论列表(0条)

    保存