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.
"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".
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
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.
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.
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
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