I have a simple class
public class A { int val; public A(int val) {this.val = val;} }
I store instances of A in java.util.TreeSet as:
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 instances of A with the same val values cannot coexist in the TreeSet .
I need a TreeSet because I want:
- Quick insert
- Quick delete
- Quick item request with minimal
val
Since equality is completely dependent on the return value 0 from compare() and how we implement it, is there a hack way that allows instances with the same val value to coexist in the TreeSet ?
My workaround is to return a stable non-zero value if val are equal, but it turns out 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();
Or do I just need to switch to a different data structure? (if there is some kind of replacement better than the RB tree)
And, Oh Geez, I know, modeling a mathematical set of abstractions is cool, and everyone here loves it.
Conclusion : Use the priority queue .
source share