Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

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

When we put a class Object (that has say three data members) in a hashtable, how can I prevent putting another entry into the hash table whose key has the same three data members ? Cos I am guessing this will be a new object. So hashtable.containsKey() will return false even when there is a key (this class object) that has the very same data members as the one that is waiting to be inserted.

More clearly: I have a class like

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

I have a hashtable structure like:

Hashtable<Triplet, Integer> table = new Hashtable<Triplet, Integer>();

When I do:

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

will this insert a duplicate even if the table contains a triplet that already has the same data members ? That is: triplet_to_be_inserted.curr, triplet_to_be_inserted.next and triplet_to_be_inserted.prev If yes, how to prevent this ?

Also, for any entry to be inserted, will containsKey() ever return true at all ? How to work around this problem ?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...