Saturday, May 28, 2016

Tricky equals() in Java

Behavior of equal() in Java with different Objects

Integer class

Integer i2 = new Integer(100);
Integer i3 = 100;
System.out.println(i2.equals(i3));

public boolean equals(Object paramObject) {
            if (paramObject instanceof Integer)
                  return (this.value == ((Integer) paramObject).intValue());
            return false;
      }

All wrapper classes overriding equals() and thus checking actual value instead of addresses.

String class

 public boolean equals(Object paramObject) {
              if (this == paramObject)
                     return true;
              if (paramObject instanceof String) {
                     String str = (String) paramObject;
                     int i = this.value.length;
                     if (i == str.value.length) {
                           char[] arrayOfChar1 = this.value;
                           char[] arrayOfChar2 = str.value;
                           for (int j = 0; i-- != 0; ++j)
                                  if (arrayOfChar1[j] != arrayOfChar2[j])
                                         return false;
                           return true;
                     }
              }
              return false;
       }

Object Class

public boolean equals(Object paramObject) {
              return (this == paramObject);
       }


public class EqualsMethod {

     public static void main(String[] args) {
           Integer i1 = new Integer(200);
           Integer i2 = 200;
           Integer i3 = new Integer(200);
           System.out.println("--equals() for Integer Object--");
           // Checking address and not values
           System.out.println(i1 == i2);
           // equals() Checks values thus result is true
           System.out.println(i1.equals(i2));
           System.out.println(i1.equals(i3));

           System.out.println("--equals() for Build In Object--");

           Employeee e1 = new Employeee("Paras", "Rohtak");
           Employeee e2 = new Employeee("Paras", "Rohtak");
           System.out.println(e1.equals(e2));
           System.out.println(e1 == e2);
          
           System.out.println("--equals() for String Object--");
           String s1= new String("Paras");
           String s2= new String("Paras");
           String s3="Paras";
           // Check values and not address
           System.out.println(s1.equals(s3));
           System.out.println(s1.equals(s2));
           System.out.println(s1==s2);
     }
}

class Employeee {
     String name;
     String address;

     Employeee(String name, String address) {
           this.name = name;
           this.address = address;
     }
}



Output:
--equals() for Integer Object--
false
true
true
--equals() for Build In Object--
false
false
366712642
--equals() for String Object--
true
true
false


No comments:

Post a Comment