l
Why override equals()
and hashCode()
?
equals()
: Determines whether two objects are considered equal. When you add an object to aSet
, the set uses this method to check if an object already exists in the set.hashCode()
: Provides a hash code that is used for efficient lookups in hash-based collections likeHashSet
. If you overrideequals()
, you should also overridehashCode()
to maintain the general contract between these methods.
1 ) import java.util.HashSet;
import java.util.Set;
class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Override equals() to compare name and age for equality
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
// Override hashCode() to generate a consistent hash code based on name and age
@Override
public int hashCode() {
return 31 * name.hashCode() + Integer.hashCode(age);
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
// Create a Set of Person objects
Set<Person> people = new HashSet<>();
// Add some custom objects to the Set
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Alice", 30)); // Duplicate (same name and age)
people.add(new Person("Charlie", 35));
// Output the set to see unique objects
for (Person person : people) {
System.out.println(person);
}
}
}
2 )
import java.util.Set;
import java.util.TreeSet;
import java.util.Comparator;
class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
// Comparator to sort by name in ascending order
Comparator<Person> nameComparator = (p1, p2) -> p1.getName().compareTo(p2.getName());
// Create a TreeSet with a custom comparator (sorting by name)
Set<Person> people = new TreeSet<>(nameComparator);
// Add some custom objects to the Set
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// Output the set to see ordered elements
for (Person person : people) {
System.out.println(person);
}
}
}
No comments:
Post a Comment