Is there any way to override the the equals
method used by a Set
datatype? I wrote a custom equals
method for a class called Fee
As Jeff Foster said:
The Set.equals() method is only used to compare two sets for equality.
You can use a Set
to get rid of the duplicate entries, but beware: HashSet
doesn't use the equals()
methods of its containing objects to determine equality.
A HashSet
carries an internal HashMap
with
entries and uses equals() as well as the equals method of the HashCode to determine equality.
One way to solve the issue is to override hashCode()
in the Class that you put in the Set, so that it represents your equals()
criteria
For Example:
class Fee {
String name;
public boolean equals(Object o) {
return (o instanceof Fee) && ((Fee)o.getName()).equals(this.getName());
}
public int hashCode() {
return name.hashCode();
}
}