Java中HashSet集合怎么对自定义对象进行去重
One easy way to get rid of duplicated objects in a HashSet in Java is to override both the equals() and hashCode() methods of the custom object. This enables the HashSet to compare the two objects and ensure only one copy is added to the set.
The equals() method is used to compare two objects for equality. It accepts an object as a parameter and returns a boolean value if the two objects are equal. The hashCode() method, on the other hand, returns an integer value that represents the unique identifier for the object.
Here are the steps to follow to implement the equals() and hashCode() methods in a custom object:
1. Identify the unique attributes of the object that will differentiate it from other objects. This could be a combination of one or more attributes. For example, if the custom object is a Person, the unique attributes could be their name and date of birth.
2. Implement the equals() method. This can be done by comparing the unique attributes of the current object with the attributes of the object passed in as a parameter. If all the attributes match, the two objects are equal and the method should return true. Otherwise, the objects are not equal and the method should return false. An example implementation for a Person object could look like this:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person person = (Person) obj;
return Objects.equals(name, person.name) &&
Objects.equals(dateOfBirth, person.dateOfBirth);
}
3. Implement the hashCode() method. This method should return an integer value that represents the unique identifier for the object. This value should be based on the same attributes used in the equals() method. An example implementation for a Person object could look like this:
@Override
public int hashCode() {
return Objects.hash(name, dateOfBirth);
}
Once both methods are implemented, the custom object can be added to a HashSet and duplicates will be automatically removed. For example:
Set<Person> people = new HashSet<>();
people.add(new Person("John", LocalDate.of(1980, 1, 1))); // adds a new person
people.add(new Person("John", LocalDate.of(1980, 1, 1))); // does not add a duplicate person
In conclusion, overriding the equals() and hashCode() methods allows for custom objects to be efficiently added to HashSets and other collections and ensures that duplicates are removed.
