Updated with Object equality. (#30911)
* updated with Object equality. Usage of .equals() and .hashCode() methods of Java Object. * Fix spacing * Added code formatting
This commit is contained in:
@ -90,5 +90,58 @@ System.out.println(s1.equals(s2)); //false
|
||||
System.out.println(s1.equalsIgnoreCase(s2)); //true
|
||||
```
|
||||
|
||||
## Object Equality
|
||||
|
||||
The java `Object` class provides two methods for comparing objects which are `equals(Object obj)` and `hashcode()`.
|
||||
|
||||
As discussed above, the `equals(Object obj)` method indicates if the object passed in argument is equal to the current instance. The default implementation of this method interprets that two objects are equal if and only if the memory address of the objects are same.
|
||||
|
||||
The `hashCode()` method returns an integer that represents the memory location of the object and this will be unique for each and every new instance.
|
||||
|
||||
However, the default implementation of the methods will have limitations as we cannot compare the custom objects on our own attributes.
|
||||
|
||||
Consider the following example for the limitation.
|
||||
|
||||
``` java
|
||||
public static void main (String[]args) {
|
||||
Employee emp1 = new Employee(1,"foo");
|
||||
Employee emp2 = new Employee(1,"foo");
|
||||
System.out.println(emp1.equals(emp2)); //output :- false
|
||||
}
|
||||
```
|
||||
The example prints `false` because both the employee objects (though they have same attribute `id` which is `1`) are stored in different memory locations. Hence, they are not considered to be equal.
|
||||
|
||||
The above limitation can be resolved by overriding the `equals()` method of the `Employee` object.
|
||||
|
||||
``` java
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
// If the object is null return false.
|
||||
if (obj == null) return false;
|
||||
|
||||
// If the object is not an instance of Employee object return false.
|
||||
if (!(obj instanceof Employee))
|
||||
return false;
|
||||
|
||||
// If the objects are stored in same memory address return true.
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
// If the objects have same employee Id return true.
|
||||
return this.getId() == ((Employee) obj).getId();
|
||||
}
|
||||
```
|
||||
|
||||
Now, the following example will print `true` as we are comparing the objects on the `id` attribute of the `Employee` object.
|
||||
|
||||
``` java
|
||||
public static void main (String[]args) {
|
||||
Employee emp1 = new Employee(1,"foo");
|
||||
Employee emp2 = new Employee(1,"foo");
|
||||
System.out.println(emp1.equals(emp2)); //output : true
|
||||
}
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
- [Oracle Java Docs : Equality Operators](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21)
|
||||
|
Reference in New Issue
Block a user