This code defines a custom Person
class with a name and an age, and implements the equals()
and hashCode()
methods to ensure that HashSet
considers two Person
objects equal if they have the same name and age.
The code creates a HashSet
of Person
objects and adds three elements to it. It then tries to add a fourth element with the same name and age as the first element, but since it’s a duplicate, it’s not added to the HashSet
. The code then prints out the contents of the HashSet
, checks if a Person
object with a certain name and age is present in the HashSet
, removes a Person
object from the HashSet
, and prints out the contents of the HashSet
again.
import java.util.HashSet;
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;
}
// Implementing equals() and hashCode() methods
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class AdvancedHashSetExample {
public static void main(String[] args) {
HashSet<Person> set = new HashSet<>();
// Adding elements to the HashSet
set.add(new Person("Alice", 25));
set.add(new Person("Bob", 30));
set.add(new Person("Charlie", 35));
set.add(new Person("Alice", 25)); // This will not be added to the HashSet because it is a duplicate
// Printing the HashSet
System.out.println(set);
// Checking if an element is present in the HashSet
Person alice = new Person("Alice", 25);
if (set.contains(alice)) {
System.out.println("The HashSet contains " + alice);
} else {
System.out.println("The HashSet does not contain " + alice);
}
// Removing an element from the HashSet
set.remove(new Person("Bob", 30));
// Printing the HashSet after removing an element
System.out.println(set);
}
}