Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeSet and equals function

There is a Java bean object which has implemented equals function based on certain criteria (Criteria A). I have a requirement to identify unique objects based on another criteria (Criteria B). Since the equals function uses criteria A, I can not use HashSet. So I thought of using TreeSet with my custom Comparator which is based on criteria B. My question is, Is it allowed to do like this? Any issues with this approach?

Thank you.

like image 351
Sujee Avatar asked Sep 07 '10 03:09

Sujee


People also ask

How does the TreeSet test if two elements are equal?

"a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal".

What is equals () used for?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

What is difference between equals () and compare to ()?

The 2 main differences are that: equals will take any Object as a parameter, but compareTo will only take Strings. equals only tells you whether they're equal or not, but compareTo gives information on how the Strings compare lexicographically.

What is difference between == and equals () show with example?

The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.


1 Answers

Here is some guide from Oracle Java:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

I think in terms of technical, no, you don't have any problems. But, in terms of coding, readability and maintainability, you have to be careful, because other people can misuse or misunderstand what you are doing

like image 166
vodkhang Avatar answered Nov 07 '22 03:11

vodkhang