Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeSet Comperator

I used a TreeSet with a self written Comparator. Now when I'm adding elements to the TreeSet and the Comparator's compare methods returns 0, it seems like the TreeSet contains only one of the Object with equal ranking.

I didn't see that this behaviour is documented in the javadocs. Maybe I miss something. Can you confirm this behaviour?

I edited the Comparator. Now it never returns 0 and the TreeSet contains all the Objects with equal ranking.

Is that the way it has to be, if I want to have multiple Objects with equal ranking?


1 Answers

That's the way it has to be, as a set is defined as including equal objects only once.

When your Comparator returns 0, two objects are considered equal, therefore only one (probably the first) of all equal objects is included in the set.

like image 190
mrueg Avatar answered Oct 31 '25 20:10

mrueg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!