Home > Blockchain >  What would be the impact of using a TreeSet<Integer> with a comparator that allows duplicates
What would be the impact of using a TreeSet<Integer> with a comparator that allows duplicates

Time:12-05

I need a binary tree with duplicates so I'm trying to use a java's TreeSet and allowing duplicates by passing a comparator that never returns 0.

Example

TreeSet<Integer> binaryTreeWithDuplicates = new TreeSet<Integer>((x, y) -> x>y?1:-1);

Will there be an undesirable side effect of such implementation and usage?
because we are obviously violating the rules in comparator api like the sign rule.

CodePudding user response:

contains would never return true.

You could have arbitrary duplicates in the set, and not be able to identify or remove them. (remove would never work.)

CodePudding user response:

I suggest trying a TreeMultiset instead

CodePudding user response:

Opinion:

Your Set ceases to be a Set, for one thing. Since that's outside the specification, the implementation is not obliged to do anything consistently. Anything could happen.

Note that since you can't say 2 == 2, you're obliged to have 2 > 2 at the same time that 2 < 2. That doesn't seem like it will end happily.

The only way to discover what happens with this sort of abuse is to try it. Maybe it'll all work and allow duplicate entries. But that doesn't guarantee that it will continue to happen with the next bugfix.

If I needed something like this (though I don't understand your use case), I'd either build a special-purpose class, or else try and use something like a set of lists of numbers.

  • Related