Powered by Blogger.

Definition of The Equals() Method and Program in Java

Definition of The equals Method:-

The method public boolean equals(Object obj) of Object class in the java.lang package compares two objcets for equality. This method returns true, only if the two objects being compared refer to the same object. On the other hand, == operator performs an equivalent comparison. If x==y returns true, that means x and y refer to the same object. We should override the public int hashCode() method of Object class whenever we override the equals method. A simple implementation could use a bit wise XOR on the hash codes of the elements tested for equality.

hashCode() method:-

This method returns a hashcode value as an int for the object. Default implementation for hashcode() should be overridden in order to make searching of data faster. The implementation of hashCode() method for an user-defined object should be calculated based on the properties of the class which we wish to consider.

equals() method:-

This method returns a boolean which specifies whether two objects are equal or not. The default implementation of equals() method given by the Object Class uses the ‘==’ operator to compare two object references, and returns true only if they refer to the same object. But, we can meaningfully re-define this equals() method to have en equality check based on our own criterias.

Consider the following code, which defines two user defined classes Employee and EmployeeId which are supposed to be stored in a Map.

The equals Methods Program:-

 public class TestEquals{
    public int x;
    public int y;

 public TestEquals(int x, int y){
     this.x=x;
     this.y=y;
 }

 public boolean equals(Object obj){
     boolean result = false;
     if((obj!=null)&&(obj instanceof TestEquals)){
     TestEquals t = (TestEquals) obj;
     if((x==t.x)&&(y==t.y)){
     result = true;
    }
 }
 return result;
 }

 public int hashCode(){
      return(xˆy);
 }

 public static void main(String[]args){
     Tes tEquals t1 = new TestEquals(5, 10);
     Tes tEquals t2 = new TestEquals(5, 10);
     if(t1==t2){
          System.out.println(”t1 is identical to t2”);
     }else{
          System.out.println(”t1 is not identical to t2”);
 }
   if(t1.equals(t2)){
         System.out.println(”t1 is equal to t2”);
   }else{
        System.out.println(”t1 is not equal to t2”);
  }
       System.out.println(”Set t2=t1”);
           t2=t1;
           if(t1==t2){
       System.out.println(”t1 is identical to t2”);
   }else{
        System.out.println(”t1 is not identical to t2”) ;
     }
   }
 }

HashCodeTest.java Program:-

public class HashCodeTest {
    public static void main(String[] args) {
        Map<employeeId, Employee>
        employees = new HashMap<employeeId, Employee>();
        employees.put(new EmployeeId("111"), new Employee("Johny"));
        employees.put(new EmployeeId("222"), new Employee("Jeny"));    // Line A
        employees.put(new EmployeeId("333"), new Employee("Jessie"));
        Employee emp = employees.get(new EmployeeId("222"));// Line B
        System.out.println(emp); // Line C
        }
    }
    }
}

Other Program of Employee.java Program:-

public class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }

        public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        Employee emp = (Employee) obj;
        if (this.name == emp.name) {
            return true;
        }
        return false;
    }

        public int hashCode() {
        return name.hashCode();
    }
 }

The equals() method Details:-

The equals() method of java.lang.Object acts the same as the == operator; that is, it tests for object identity rather than object equality. The implicit contract of the equals() method, however, is that it tests for equality rather than identity. Thus most classes will override equals() with a version that does field by field comparisons before deciding whether to return true or false.

To elaborate, an object created by a clone() method (that is a copy of the object) should pass the equals() test if neither the original nor the clone has changed since the clone was created. However the clone will fail to be == to the original object.

For example, here is an equals() method you could use for the Car class. Two cars are equal if and only if their license plates are equal, and that's what this method tests for.

 public boolean equals(Object o) {
 
    if (o instanceof Car) {
      Car c = (Car) o;
      if (this.licensePlate.equals(c.licensePlate)) return true;
    }
    return false;
   
  }

This example is particularly interesting because it demonstrates the impossibility of writing a useful generic equals() method that tests equality for any object. It is not sufficient to simply test for equality of all the fields of two objects. It is entirely possible that some of the fields may not be relevant to the test for equality as in this example where changing the speed of a car does not change the actual car that's referred to.

Be careful to avoid this common mistake when writing equals() methods:

 public boolean equals(Car c) {
 
    if (o instanceof Car) {
      Car c = (Car) o;
      if (this.licensePlate.equals(c.licensePlate)) return true;
    }
    return false;
   
  }

The equals() method must allow tests against any object of any class, not simply against other objects of the same class (Car in this example.)

You do not need to test whether o is null. null is never an instance of any class. null instanceof Object returns false.

1 comment:

  1. Pretty good post. I just came across your site and wanted to say that I’ve really enjoyed reading your posts. In any case I’ll be subscribing to your feed and I hope you will keep a good work!Cheer!

    sap online training
    software online training
    sap sd online training
    hadoop online training
    sap-crm-online-training

    ReplyDelete