Hack: Duplicates in java.util.TreeSet?

Viewed 207

I have a simple class

public class A {
    int val;
    public A(int val) {this.val = val;}
}

I store A instances in a java.util.TreeSet like:

SortedSet<A> ss = new TreeSet<A>(new Comparator<A>() {
    @Override
    public int compare(A o1, A o2) {
        return Integer.compare(o1.val, o2.val);
    }
});

Only to find later that A instances with the same val values cannot coexist in TreeSet.

I need TreeSet because I want:

  • Quick Insertion
  • Quick Removal
  • Quick Query of Element with Minimum val

Since the equality completely depends on the return value 0 of compare() and how we implement it, is there a hacking way that allow instances with the same value of val to coexist in TreeSet?

My workaround is to return a stable non-zero value if val are equal, but it proves to be unstable.

SortedSet<ListNode> ss = new TreeSet<ListNode>(new Comparator<ListNode>() {
    @Override
    public int compare(ListNode o1, ListNode o2) {
        if (o1.val != o2.val) return Integer.compare(o1.val, o2.val);
        return o1.hashCode() - o2.hashCode(); // not to return 0
    }
});

Or should I just switch to another data structure? (if there exists some substitute better than R-B Tree)

And, Oh Geez, I know modeling the mathematical set abstraction is cool and everyone here loves it.

Conclusion: use priority queue.

2 Answers
Related