jarosik
jarosik

Reputation: 4564

Hashcode Equals Contract failed but HashMap works

I have found following question for OCPJP:

class Student{
 public Student(int r) {
         rollNo = r;
 }
 int rollNo;
  public int hashCode(){
          return rollNo;
  }

}

class Test {
 public  static void main(String[] args){
         HashSet<Student> students = new HashSet<>();
         students.add(new Student(5));
         Student s10 = new Student(10);
         students.add(s10);
         System.out.println(students.contains(new Student(10)));
         System.out.println(students.contains(s10));
  }

} the output is: false true

you can even sucesfully remove s10 from a set. How come this works if equals is not overriden?

Upvotes: 0

Views: 92

Answers (2)

rghome
rghome

Reputation: 8819

The default equals method is equivalent to ==, so it will return true for s10.equals(s10) and the default hash method will always return the same value for s10.

So by default, a HashSet will work as long as you are adding, checking and deleting the same physical object.

This is not usually useful, as you will have often lost the reference to the original key and will be constructing a new one (but if you are using constant keys, it would work, as long as you are in the same classloader).

Upvotes: 1

wilkesybear
wilkesybear

Reputation: 528

If you don't override equals, then it will essentially check if the two objects being compared are the same in memory. Since you are actually checking s10 against itself, then the standard equals evaluates to true since it's the same object.

Here's the doc on contains that explains this: "Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e))."

And, for Object.equals: "The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true)."

Upvotes: 1

Related Questions