For contains should we override both hashcode and equals for hashset in java [duplicate]
Possible Duplicate:
Overriding equals and hashCode in Java
For contains should we override both hashcode and equals for hashset in java?
import java.lang.Math;
import java.util.HashSet;
class Hello{
public String name= "";
Hello(String name){
this.name = name;
}
public static void main(String args[]){
Hello h1 = new Hello("first");
Hello h2 = new Hello("second");
Hello h3 = new Hello("third");
Hello h4 = new Hello("fourth");
Hello h5 = new Hello("fourth");
HashSet hs = new HashSet();
hs.add(h1);
hs.add(h2);
hs.add(h3);
hs.add(h4);
hs.add(h5);
hs.add(h5);
hs.add(null);
System.out.println("elements in hashset"+hs);
// System.out.println("elements in hashset"+hs.contains());
System.out.println("elements in hashset"+hs.contains(new Hello("fourth")));
}
/*public boolean equals(Object obj){
System.out.println(name+"==========="+((Hello)obj).name);
if(name.equals(((Hello)obj).name))
return true;
else
return false;
}*/
public int hashCode(){
return name.hashCode();
}
}
I don't see any detail about the question, but yes, you should override hashCode() and equals() to properly compare objects for collections.
If you override either hashCode
or equals
, you must override them both. It says that in the Javadocs for java.lang.Object
, and it's definitely true.
Yes your Hello class is just wrapping a String but you MUST overwrite hashCode and equals in Hello.
Yes.
Because HashSet.contains
uses containsKey
that uses getEntry
. It tries to find the key-value pair in the hash and both methods are needed (one for choosing the bucket, other for looking in the internal bucket list).
You need to override equals if you expect two different Objects to be considered equal. If you use a hash collection, you need to override hashCode() to work the same way.
System.out.println("elements in hashset"+hs.contains(h4); // displays true.
By the way, if all your Hello
objects shall be regarded as different (e.g. one new Hello("first")
should be regarded as different to the next new Hello("first")
, you don't have to override equals
or hashCode
at all, as the default implementations already work fine for this case.
精彩评论