How do I implement equals() and hashCode() method using java.util.Objects?

This example will show you how to implement the equals() and hashCode() object using java.util.Objects class. The Objects class provides a set of utility methods to work with object such as comparing two objects for equality and calculating the hashcode. Other methods include object null check methods, object to string method, etc.

To demonstrate equals() and hash() methods we’ll create a simple POJO called Student with a couple of properties such as id, name and dateOfBirth.

package org.kodejava.example.util;

import java.time.LocalDate;
import java.util.Objects;

public class Student {
    private Long id;
    private String name;
    private LocalDate dateOfBirth;

    public Student() {
    }

    public Student(Long id, String name, LocalDate dateOfBirth) {
        this.id = id;
        this.name = name;
        this.dateOfBirth = dateOfBirth;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student that = (Student) o;
        return Objects.equals(this.id, that.id)
                && Objects.equals(this.name, that.name)
                && Objects.equals(this.dateOfBirth, that.dateOfBirth);
    }

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

Using the Objects.equals() and Objects.hash() methods in the Student class makes the implementation of the equals() method and the hashCode() method concise, easy to read and to understand. The Objects utility class will operate in a null-safe way which means that it will check for a null fields of the object.

The code snippet below will demonstrate the use of Student class. Which will compare objects using the equals() method and print out the calculated hashcode of the object.

package org.kodejava.example.util;

import java.time.LocalDate;
import java.time.Month;

public class EqualsHashCodeExample {
    public static void main(String[] args) {
        Student student1 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1));
        Student student2 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1));
        Student student3 = new Student(2L, "Bob", LocalDate.of(1992, Month.DECEMBER, 21));

        System.out.println("student1.equals(student2) = " + student1.equals(student2));
        System.out.println("student1.equals(student3) = " + student1.equals(student3));
        System.out.println("student1.hashCode() = " + student1.hashCode());
        System.out.println("student2.hashCode() = " + student2.hashCode());
        System.out.println("student3.hashCode() = " + student3.hashCode());
    }
}



And here are the result of the code snippet above:

student1.equals(student2) = true
student1.equals(student3) = false
student1.hashCode() = 1967967937
student2.hashCode() = 1967967937
student3.hashCode() = 6188033

Another approach for implementing the equals() and hashCode() method is using the Apache Commons Lang library. And example of it can be seen here: How to implement the hashCode and equals method using Apache Commons?.

How to implement the hashCode and equals method using Apache Commons?

This code snippet show you how to use HashCodeBuilder and EqualsBuilder class from the Apache  Commons Lang library to implement the hashCode() and equals() method of an object. To use both of these classes we just need to create instance of these class and append the properties that we will use the calculate the hashcode and to test for equality.

Implementing the hashCode() method first by creating the hashCode() method. Add the @Override annotation to make sure that we’ve override the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re gonna use to calculate the hashcode. The final result of the actual hashcode can be obtained by calling the toHashCode() from the instance of HashCodeBuilder.

/**
 * Implement the hashCode method using HashCodeBuilder.
 */
@Override
public int hashCode() {
    return new HashCodeBuilder().append(id).append(name).toHashCode();
}

We do the same to create the equals() method. First create the method, it takes a single argument type of java.lang.Object. Add the @Override annotation to make sure we override the correct method. On the first line you can check to see if the passed object is an instance of the same object, we use the instanceof operator. We then compare the values stored in both object using the EqualsBuilder class. To get the equality result you must remember to call the isEquals() method.

/**
 * Implement the equals method using the EqualsBuilder.
 */
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof DummyUser)) {
        return false;
    }
    DummyUser that = (DummyUser) obj;
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class DummyUser {
    private Long id;
    private String name;

    /**
     * Constructor to create an instance of this class.
     */
    public DummyUser() {
    }

    public static void main(String[] args) {
        DummyUser user1 = new DummyUser();
        user1.setId(10L);
        user1.setName("Carol");

        DummyUser user2 = new DummyUser();
        user2.setId(10L);
        user2.setName("Carol");

        System.out.println("user1.hashCode() = " + user1.hashCode());
        System.out.println("user2.hashCode() = " + user2.hashCode());

        System.out.println("user1.equals(user2) = " + user1.equals(user2));
    }

    //
    // Getters & Setters
    //
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Implement the hashCode method using HashCodeBuilder.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(id).append(name).toHashCode();
    }

    /**
     * Implement the equals method using the EqualsBuilder.
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DummyUser)) {
            return false;
        }
        DummyUser that = (DummyUser) obj;
        return new EqualsBuilder().append(this.id, that.id)
                .append(this.name, that.name).isEquals();
    }
}

The result of our code are:

user1.hashCode() = 64902380
user2.hashCode() = 64902380
user1.equals(user2) = true

How do I implement equals method using Commons Lang?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import java.io.Serializable;

public class BookEqualsExample implements Serializable {
    private Long id;
    private String title;
    private String author;

    //~ Implements getters and setters here.

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof BookEqualsExample)) {
            return false;
        }

        BookEqualsExample that = (BookEqualsExample) o;
        return new EqualsBuilder()
                .append(this.id, that.id)
                .append(this.title, that.title)
                .append(this.author, that.author)
                .isEquals();

        // You can also use reflection of the EqualsBuilder class.
        // return EqualsBuilder.reflectionEquals(this, that);
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(id)
                .append(title)
                .append(author)
                .toHashCode();

        // Or even use the simplest method using reflection
        // below.
        // return HashCodeBuilder.reflectionHashCode(this);
    }
}

How do I compare if two arrays are equal?

Using Arrays.equals() methods we can compare if two arrays are equal. Two arrays are considered to be equal if their length, each element in both arrays are equal and in the same order to one another.

package org.kodejava.example.util;

import java.util.Arrays;

public class CompareArrayExample {
    public static void main(String[] args) {
        String[] abc = {"Kode", "Java", "Dot", "Org"};
        String[] xyz = {"Kode", "Java", "Dot", "Org"};
        String[] java = {"Java", "Dot", "Com"};

        System.out.println(Arrays.equals(abc, xyz));
        System.out.println(Arrays.equals(abc, java));
    }
}

The Arrays.equals() can be used to compare array of any primitive data type and array of Object. If you run this example you will have a result as follow:

true
false

How do I check string for equality?

To compare string for their content equality we must use the String.equals() method. This method ensures that it will compare the content of both string instead of the object reference of the both string. This method returns true if both string in comparison have the same content.

Do not, never, use the == operator to compare string for its content. The == operator check for object reference equality, it returns true only if both objects point to the same reference. This operator returns false if the object doesn’t point to the same references.

package org.kodejava.example.lang;

public class StringEquals {
    public static void main(String[] args) {
        String s1 = "Hello World";
        String s2 = new String("Hello World");

        // This is good!
        if (s1.equals(s2)) {
            System.out.println("1. Both strings are equals.");
        } else {
            System.out.println("1. Both strings are not equals.");
        }

        // This is bad!
        if (s1 == s2) {
            System.out.println("2. Both strings are equals.");
        } else {
            System.out.println("2. Both strings are not equals.");
        }
    }
}

In the example above we deliberately create an instance of s2 string using the new operator to make sure that we have a different object reference. When you run the program it will give you the following result:

1. Both strings are equals.
2. Both strings are not equals.