Java Program To Implement A Custom equals() and hashcode() In Java

Chapter: Miscellaneous Last Updated: 07-10-2023 07:09:00 UTC

Program:

            /* ............... START ............... */
                
import java.util.Objects;

class Person {
    private String name;
    private int age;

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

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

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

    public static void main(String[] args) {
        Person person1 = new Person("Alice", 25);
        Person person2 = new Person("Bob", 30);
        Person person3 = new Person("Alice", 25);

        // Testing equals()
        System.out.println("person1.equals(person2): " + person1.equals(person2)); // false
        System.out.println("person1.equals(person3): " + person1.equals(person3)); // true

        // Testing hashCode()
        System.out.println("person1.hashCode(): " + person1.hashCode());
        System.out.println("person3.hashCode(): " + person3.hashCode());
    }
}

                /* ............... END ............... */
        

Output

person1.equals(person2): false
person1.equals(person3): true
person1.hashCode(): 83109938
person3.hashCode(): 83109938

In this output:

person1.equals(person2) returns false because the name and age of person1 and person2 are different.

person1.equals(person3) returns true because the name and age of person1 and person3 are the same.

person1.hashCode() and person3.hashCode() return the same hash code value, which is 83109938, because 
they have the same name and age values, and the hashCode() method generates a consistent hash code for 
objects with the same attributes.

Notes:

  • In Java, the equals() and hashCode() methods are used to compare and hash objects, respectively. When you override these methods, you can define custom behavior for object comparison and hashing.
  • In this example, we have a Person class with two fields: name and age. We override the equals() method to compare two Person objects based on their name and age fields. We also override the hashCode() method to generate a hash code based on these fields.
  • When you create instances of the Person class and compare them using equals(), it will compare the name and age fields. If both fields are the same, the objects are considered equal. Additionally, calling hashCode() on these objects will generate a hash code based on the name and age fields, which is used in data structures like HashMap and HashSet for efficient storage and retrieval.
Similar Programs Chapter Last Updated
Find Unique Elements In List Java Miscellaneous 07-10-2023
Java Program To Find The Intersection Of Two HashSets Miscellaneous 07-10-2023
Java Program To Remove Duplicate Elements From List Miscellaneous 07-10-2023
Java program to parse a date and time string from a log file and store it in a database Miscellaneous 19-09-2023
Java Program To Print All The Dates In A Month That Fall On A Weekend Miscellaneous 19-09-2023
Java Program To Find Number Of Working Days In A Month Miscellaneous 19-09-2023
Java Program To Calculate Age From Year Of Birth Miscellaneous 16-09-2023
How To Check If Two Strings Are Anagrams In Java Miscellaneous 22-08-2023
Java Program To Make A Snake Game Miscellaneous 15-08-2023
Java Program To Find Repeated Characters Of String Miscellaneous 15-08-2023
String To Array In Java Miscellaneous 11-08-2023
Java Program To Convert Date To String Miscellaneous 11-08-2023
Java Program To Convert String To Date Object Miscellaneous 11-08-2023
Java Program To Find Number Of Days In A Month Miscellaneous 11-08-2023
Java Program To Print First And Last Day Of Month Miscellaneous 11-08-2023
Java Program To Find Leap Year Between Two Dates Miscellaneous 11-08-2023
Java Code To Find Difference Between Two Dates In Years Months And Days Miscellaneous 11-08-2023
Java program to calculate age from year of birth Miscellaneous 29-06-2023
Swap Two Numbers Without Using Third Variable In Java Miscellaneous 02-06-2023
Java Program To Find The Average Of An Array Of Numbers Miscellaneous 02-06-2023
How Do You Find The Factorial Of A Number In Java Miscellaneous 02-06-2023
Java Program That Takes Two Numbers As Input And Prints Their Sum Miscellaneous 27-05-2023
How To Get The Length Of An Array In Java Miscellaneous 27-05-2023
Java Add Element To List Example Miscellaneous 19-05-2023
Java Program To Square All Items In List Miscellaneous 17-05-2023
Java Program To Merge Two Lists Miscellaneous 17-05-2023
How To Reverse A List In Java Miscellaneous 17-05-2023
Java Program To Find Unique Elements In An Array Miscellaneous 14-05-2023
Java Program To List All Elements In List Miscellaneous 30-04-2023
Java Program To Create XML File Miscellaneous 23-04-2023

1 2