The hashCode() determines the bucket number, while equals() determines if the one of the objects already inserted in the bucket is equal to the willing to insert object. In this case Human doesn't override hashCode() neither equals(). Which means every object of type Human has a unique hashCode and it is not equal to any other Human object. Therefore the four Human objects will be inserted in the set.
To make Set accepts no duplicates in this example, then override hashCode() and equals() in Human, as for example as following:
public boolean equals(Object h) {
return this.age==((Human)h).age;
}
public int hashCode(){
return 17;
}
|
Oracle Certified Professional Java Programmer
Author:
JavaChamp TeamSenior Java Developer
QuizOver.com
Germany
Access: |