The Object Class
Understand how the Object class's equals method works, why it compares memory addresses by default, and why overriding both equals and hashCode is crucial for proper object equality and hash-based collections in Java. Explore examples to see how to implement these methods correctly.
We'll cover the following...
What is the Object class?
What are the methods defined in the Object class?
What is the output of the below snippet?
String obj1 = new String("abc");
String obj2 = new String("abc");
System.out.println(obj1 == obj2);
false
true
The equals() method provided in the Object class uses the identity operator == to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal — that is, if the object references are pointing to the same address in memory. This is the reason the statement new Integer(5) == new Integer(5) will output false because the two integer objects have different memory ...