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
. Now I have a LnkedList
of Fee
and I want to ensure that there are no duplicated entries. Thus I am considering using a Set
insted of a LinkedList
, but the criteria for deciding if two fees are equal resides in the overriden equals
method in the Fee
class.
If using a LinkedList
, I will have to iterate over every list item and call the overriden equals
method in the Fee
class with the remaining entries as a parameter. Just reading this alone sounds like too much processing and will add to computational complexity.
Can I use Set
with an overridden equals
method? Should I?
You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.
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.
Case 1: Overriding both equals(Object) and hashCode() method Whenever it(hashcode) is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
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 <Integer(HashCode), Object>
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With