What does an OBJECT EQUALS method do internally? How to know the value stored in an Object eg: Object_Comparison?

204 Views Asked by At

I know that .equals methods from the Object class in Java compares the content of the object but what does it do in the below code and why is it FALSE as i put in the comment line? Please let me know.

public class Object_Comparison {

public static void main(String[] args) {        
    Object_Comparison T1 = new Object_Comparison();
    Object_Comparison T2 = new Object_Comparison();
    
    System.out.println("T1-->"+T1);
    System.out.println("T2-->"+T2);
    
    System.out.println("T1-->"+T1.hashCode());
    System.out.println("T2-->"+T2.hashCode());
    
    System.out.println(T1==T2);
    
    System.out.println(T1.equals(T2)); // what does it contain to do and produces the result as false?
}
}

O/p:

T1-->Object_Comparison@1db9742

T2-->Object_Comparison@106d69c

T1-->31168322

T2-->17225372

false

false

2

There are 2 best solutions below

3
GhostCat On

Your code doesn't use strings, and as your class Object_Comparison isn't overriding the base equals() method from java.lang.Object, therefore expected happens.

Your code creates two different object T1 and T2. If you compare the "references" to those objects, they are different (T1 != T2). And as the base implementation for equals() ... simply does the same check, that method returns false as well.

Given your current code, you could as well replace

Object_Comparison T1 = new Object_Comparison();
Object_Comparison T2 = new Object_Comparison();

with

Object t1 = new Object();
Object t2 ...

and get to the exact same results. Because nothing you are showing in your example code does anything different then what you "inherit" from java.lang.Object.

0
Thilo On

I know that .equals methods from the Object class in Java compares the content of the object

Not necessarily, no.

Every class has to implement the logic to "compare the content of the object". There is no built-in generic way in Java that works for all classes.

So while it does compare the contents for things like String or ArrayList<Integer>, that is only because String, ArrayList and Integer have implemented their own versions of the equals method accordingly.

If you do not implement equals in your own class, you will inherit it from the parent class. And if that ends up being Object, then, no, the default implementation provided there does not compare contents: Two objects are only considered equal if they are the same object instance.

And if you do implememt equals, make sure to also implement hashCode(): Why do I need to override the equals and hashCode methods in Java?