Monday, 21 January 2013

Equalizing Two Object

        Even though two object’s property field values are same, those two objects are not same.

        If we want equalize two objects based on property field values, then we need to override equal and hash code methods.



Sample Program


package com.javalearning.crazy;

public class Student {

      public String rNo;

      public String sName;

      public Student(String rNo, String sName) {

            this.rNo = rNo;

            this.sName = sName;

      }

      @Override

      public boolean equals(Object compareObj) {

            // The argument is not equality == operator to check if the argument is

            // the reference to this object, if yes. return true

            if (this == compareObj)

                  return true;

            // The argument is not null

            if (compareObj == null)

                  return false;

            // Cast the method argument to the correct type.

            // Again, the correct type may not be the same class.

            if (!(compareObj instanceof Student))

                  return false;

            Student compareStudent = (Student) compareObj;

            // Convert the object to a Student

            return this.rNo.equals(compareStudent.rNo);

            // Equal based on the property field value?

      }

      @Override

      public int hashCode() {

            int primeNo = 13;

            return primeNo + this.rNo.hashCode();

      }

      public static void main(String[] args) {

            Student studObj1 = new Student("1001", "Murugan");

            Student studObj2 = new Student("1002", "Murugan");

            boolean areEqual = studObj1.equals(studObj2);

            System.out.println(areEqual);

      }

}

 

Equals Overriding Condition


           If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected impact when your class uses hash-based collections.

Example


           If only equals is overriden, then when you call put method in HashMap, first will hash to some bucket and when you call put method again it will hash to some other bucket. So, although they are equal, as they don't hash to the same bucket (different hashCode) the map can't realize it and both of them stay in the map.

No comments:

Post a Comment