Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.equals() for user defined class in Java

Please see the below code

class TestToString 
{
  public static void main(String args[]) 
  {
    CheckToString cs = new CheckToString (2);
    CheckToString c = new CheckToString (2);
    if( cs.equals(c))
       System.out.println(" Both objects are equal");
    else
       System.out.println(" Unequal objects ");
  }
}

class CheckToString 
{
   int i;
   CheckToString () 
   {
      i=10;
   }
   CheckToString (int a) 
   {
     this.i=a;
   }
}

Output: Unequal objects

But I was expecting the output will be

Both objects are equal

I understood that both the objects have different refferences,

System.out.println(cs); //com.sample.personal.checkToString@19821f
System.out.println(c); //com.sample.personal.checkToString@addbf1

but I was asking, why do they have different referrences? whereas in the below case, the objects have same memory locations.

Integer a = new Integer(2);
Integer b = new Integer(2);
System.out.println(a);           //2
System.out.println(b);           //2

I am comparing the object of user-defined class with the object of pre-defined class. It seems the object of user-defined class behaves same as the object of Integer Class having value beyond -128 to 127. Why are the referrences different for both the cases? (same for Integer class having value within -128 to 127 and different for user-defined class)

like image 774
Jyoti Ranjan Avatar asked Nov 26 '25 15:11

Jyoti Ranjan


1 Answers

The default implementation of equals checks references. You are creating 2 different object, that don't refer the same thing in memory.

A decent implementation of equals would be something like:

public boolean equals(Object o) {
  if (!(o instanceof CheckToString)) {
    return false;
  }
  CheckToString other = (CheckToString) o;
  return i == other.i;
}

When overridding equals, you need to override hashCode, too.

Whenever you say new CheckToString(), you are creating a new object in memory, so a totally different reference than another new CheckToString(). It doesn't matter what is inside the object definition.

The stuff you mention about Integer is true, but it applies to Integer, not to a custom object that you have created.

like image 104
Dan D. Avatar answered Nov 29 '25 05:11

Dan D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!