tags:

views:

61

answers:

3

I created an object HashSet, and the value is an object (Triple) which is my own class. But I get a strange thing, when there are two equal objects on my HashSet, is it possible? Here is my overriding method for the equals in the class Triple

 @Override
 public boolean equals(Object other){
 if (other == null) return false;
 if (other == this) return true;
 if (this.getClass() != other.getClass()) return false;
 Triple otherTriple = (Triple)other;

 if(otherTriple.getSubject().equals(getSubject()) &&
   otherTriple.getPredicate().equals(getPredicate()) &&
   otherTriple.getObject().equals(getObject()))
  return true;
 return false;

}

+1  A: 

I am having trouble understanding your question but hashCode() and equals() sematics are important only when you are planning to use an object as the key. And you cant have two objects evaluating to same hash in a Map...one will override the other

Pangea
Any two keys, keyA and keyB, can have the same hash without "overriding" each other, otherwise the whole concept of a hash table wouldn't work. Only when `keyA.equals(keyB)` will the last one added override the previous one.
Stephen P
sorry, it's a hashSet, not a hashMap, I just realized it...
zfm
+3  A: 

You didn't override equals and hashCode in your class properly. Here's how to write it and test it :

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

duffymo
I strongly suggest using Equals and HashCode builder functionality provided by the editor like eclipse
Pangea
Or IntelliJ, a superior IDE.
duffymo
sorry, it's a hashSet, not a hashMap, I just realized it...
zfm
Irrelevant......
duffymo
+4  A: 

You need to be sure to implement hashCode() as well, and when two Triples are equal, their hashCodes must also be equal. If you don't do that, you will get strange behavior.

Eric Bowman - abstracto -
sorry, it's a hashSet, not a hashMap, I just realized it...
zfm
@user491748: doesn't make a difference.
Michael Borgwardt
so the value can be equals? okey I see... thank you
zfm