If key in hashtable is a class object, how does containsKey work?

谁说我不能喝 提交于 2019-11-29 11:40:19

All classes that have instances used as keys in a hash-like data structure must correctly implement the equals and hashCode methods. Brian Goetz has a great article on this from a while back.

Without knowing the structure of Curr, Prev and Next and exact example is difficult, but assuming they are not null and have sensible hashCode implementations, you could do something like this:

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;
}

The easiest way is to use Eclipse's generate hashCode() and equals(). You can select which members should be taken into account for the hashCode and equals calculation, so in case you have some transient members (you don't) you can only use those which are relevant.

And similiarly (and recursively) for Curr, Prev and Next...

From java documentation:

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!