How do you use equals and hashCode with a simple code example?

In Java, the `equals()` method is used to compare two objects for equality. The `hashCode()` method is used in conjunction with `equals()` to provide a hash code value for the object. It is important to override both methods when creating a class so that it can be used correctly in collections such as HashMap or HashSet.

Here's a simple example demonstrating the usage of `equals()` and `hashCode()` in a custom Java class:

public 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 && name.equals(person.name); } @Override public int hashCode() { return Objects.hash(name, age); } // Getters and Setters } public static void main(String[] args) { Person person1 = new Person("John", 30); Person person2 = new Person("John", 30); System.out.println(person1.equals(person2)); // true System.out.println(person1.hashCode() == person2.hashCode()); // true }

Java equals hashCode Object comparison Java Collections