By default, when we compare two instances of the same class in Java, it is checked whether both refer to the same object or not.
Therefore, two instances may be completely different regardless of the similarity of the information contained. Take for Example:
public class PersonDetails {
private Integer age;
private String firstName;
private String lastName;
private String nationality;
public PersonDetails(Integer age, String firstName, String lastName, String nationality) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
this.nationality = nationality;
}
}
If we run the main class as follows,
public class Main {
public static void main(String[] args){
PersonDetails first = new PersonDetails(18,"John","Doe","American");
PersonDetails second = new PersonDetails(18,"John","Doe","American");
if(first.equals(second)){
System.out.println("Equal");
}
else {
System.out.println("Not equal");
}
}
}
The output will be: Not equal
And for us to check for equality of values inside the objects, we will need to override the equals method in our class.
public class PersonDetails {
private Integer age;
private String firstName;
private String lastName;
private String nationality;
public PersonDetails(Integer age, String firstName, String lastName, String nationality) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
this.nationality = nationality;
}
//Overriding equals() to compare PersonDetails objects
@Override
public boolean equals(Object o){
//If object is compared to itself then return
if(o == this){
return true;
}
//Check if o is an instance of PersonDetails or not
if(!(o instanceof PersonDetails)){
return false;
}
// typecast o to PersonDetails so that we can compare data
PersonDetails personDetails = (PersonDetails) o;
// Compare the values inside the objects and return accordingly
return Integer.compare(age,personDetails.age) == 0
&& firstName.compareTo(personDetails.firstName) == 0
&& lastName.compareTo(personDetails.lastName) ==0
&& nationality.compareTo(personDetails.nationality) == 0;
}
}
If we run the main class again,
The output will be: Equal
Get source code used in this article from GitHub
Link
Top comments (0)