Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Set collection - override equals method

Tags:

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?

like image 640
Faiyet Avatar asked May 31 '11 12:05

Faiyet


People also ask

Is it possible to override equals method in Java?

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.

Does HashSet have an overloaded equals method?

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.

What are equals () and hashCode () overriding rules?

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.


1 Answers

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();   }  } 
like image 73
Jonas Eicher Avatar answered Mar 30 '23 10:03

Jonas Eicher