Comparing Two Objects in Java: Using equals() and hashcode()

Java is an object-oriented programming language that allows developers to create complex and robust applications. One of the essential concepts in Java is object comparison. In this article, we will discuss how to compare two objects in Java.

What is object comparison?

Object comparison is the process of checking whether two objects are equal or not. In Java, objects are created from classes, and each object has its own set of data and behavior. Comparing two objects is not as simple as comparing two primitive data types such as integers or booleans. It requires a deeper understanding of the structure of objects and how they are stored in memory.

Check out our blog on Prime Number in Java here!

2 Methods to Compare Two Objects in Java 

Using equals() method

The equals() method is the primary method used to compare two objects in Java. By default, the equals() method compares two objects by their memory address. In other words, it checks whether the two objects are in the same instance or not. However, this default behavior is often not what we want. We may want to compare objects based on their internal state, rather than their memory location.

a. Without overriding

To compare two objects based on their internal state, we need to override the equals() method in the class definition. If we do not override the equals() method, then the default behavior will be used, which compares the memory addresses of the two objects. Here is an example of how to use the equals() method without overriding:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        Person person2 = new Person("John", 30);
        System.out.println(person1.equals(person2)); // Output: false
    }
}

In the above example, we have two instances of the Person class. Both objects have the same name and age values. However, the output of the equals() method is false because the default implementation of equals() compares the memory addresses of the two objects, which are different.

Output:

false

Check out our blog on Fascinating Number in Java, Here!

b. With overriding

To compare two objects based on their internal state, we need to override the equals() method in the class definition. Here is an example of how to override the equals() method:

import java.util.*;
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        Person person2 = new Person("John", 30);
        System.out.println(person1.equals(person2)); 
    }
}

Output:

true

In the above example, we have two instances of the Person class. Both objects have the same name and age values. We have also overridden the equals() method in the Person class, which compares the name and age fields of the two objects. The output of the equals() method is true because both objects have the same name and age values.

Using hashcode() and equals() method

The hashcode() and equals() methods work together to compare two objects in Java. The hashcode() method returns an integer value that represents the hash code of an object. The hash code of an object is used to determine its position in a hash table, which is used for fast lookups.

The equals() method is used to check whether two objects are equal or not. If two objects are equal, then their hash codes must also be equal. Therefore, when we override the equals() method, we must also override the hashcode() method.

Here is an example of how to use the hashcode() and equals() methods:

import java.util.*;
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        Person person2 = new Person("John", 30);
        System.out.println(person1.equals(person2)); // Output: true
        System.out.println(person1.hashCode() == person2.hashCode()); // Output: true
    }
}

In the above example, we have two instances of the Person class. Both objects have the same name and age values. We have overridden both the equals() and hashcode() methods in the Person class. The output of the equals() method is true because both objects have the same name and age values. The output of the hashcode() method is also true because both objects have the same hash code.

Output:

true
true

In Java, comparing two objects is not as simple as comparing two primitive data types. It requires a deeper understanding of the structure of objects and how they are stored in memory. The equals() method is the primary method used to compare two objects in Java. When we override the equals() method, we must also override the hashcode() method to ensure that two equal objects have the same hash code. By using the equals() and hashcode() methods, we can compare two objects based on their internal state, rather than their memory location.

Get Complete Python Interview Questions and Answers, here!

7 Tips for writing effective equals() and compareTo() methods:

  1. Replace the equivalent and hashCode methods: Java requires that the equals() and hashCode() methods be overridden in order to compare objects. 
  2. Verify for null: Before comparing objects, always check for null values to prevent NullPointerException. utilise the instanceof operator Before casting an object, use the instanceof operator to determine its type.
  3. To make sure the objects are equal, compare all the fields that are pertinent to the state of each object. 
  4. For primitive types, use the == operator: When comparing the values of primitive types like int, use the == operator.
  5. Implement the Comparable interface: The compareTo() method can be used to compare objects when the Comparable interface is implemented. 
  6. Observe the agreement: Make sure the equals() method complies with the contract of equivalence, which mandates that if two objects are equal, then their hash codes must also be equal.

Common mistakes to avoid when comparing objects:

Here is the mention of some common mistakes which you can avoid while comparing two objects in Java:

  1. Reference comparison: When comparing two objects, the == operator only determines whether they refer to the same memory-based object, not whether their values are equal. 
  2. Not performing a null check NullPointerExceptions can occur if the check for null values is not done. 
  3. Comparing irrelevant fields can result in false positives and negatives when comparing objects because they are not relevant to the state of the object.
  4. Breaking the contract: When comparing objects, breaking the agreement on equivalence can result in unexpected behavior. 
  5. Not using the instanceof operator: When casting an object to the correct type, not using the instanceof operator may cause a ClassCastException. 

You can effectively compare objects in Java by adhering to these best practices and avoiding common mistakes, and you can make sure that your code works as intended by doing so.


We hope that our blog post on “Compare Two Objects in Java” will effectively guide and inform you about your Java-related queries.To keep enhancing your coding skills, do check out Newtum’s website and explore our online coding courses covering Java,html, PHP, and more.

About The Author

Leave a Reply