views:

40

answers:

1

Hi,

I'm trying order pairs of integers ascendantly where a pair is considered less than another pair if both its entries are strictly less than those of the other pair, and larger than the other pair if both its entries are strictly larger than those of the other pair. All other cases are considered incomparable.

They way I want to solve this is by defining a Comparator that implements the above, but will throw an exception for incomparable cases, and provide that to a PriorityQueue. Of course, while inserting a pair the priority queue does several comparisons while bubbling the new entry up to its correct position in the heap, and many of these will be comparable. But it may happen during the bubbling process that a pair is encountered with which this new pair is incomparable, and an exception will be thrown. If this happens, what will be the state of the PriorityQueue? Will the pair I was trying to insert sit in the heap at the last position it was in before the exception was thrown? If I use the PriorityQueue's remove(Object o) method, will the PriorityQueue be restored to a consistent state?

Thanks

+1  A: 

If you look at the PriorityQueue source code, when adding/offering new elements the .compare() method is called without any try/catch (this is in siftUpUsingComparator())- which makes sense, as it's not the PriorityQueue's responsibility to prevent you from putting incomparable elements in the queue. So any RuntimeException thrown by your Comparator will bubble up to your calling code.

The larger question here is why are you attempting to sort items which are, by your definition, "incomparable"? This doesn't make much sense. If the items are of the same type but are neither greater than or lesser than another item, your Comparator should return them as equal. The semantics of Comparator are such that "equal" doesn't mean "has the same value" but rather "has the same order the element being compared to" - in other words, you return equal (0) when you want the two items to be ordered next to each other in the sort.

matt b
What I'm really trying to do is to get the longest sequence of pairs that is strictly growing. By throwing an exception I am trying to cancel those pairs that don't fit this sequence.BTW: I gave it a shot, and ended up with a null element in my heap.
nieldw
perhaps PriorityQueue isn't the best data structure for what you want to do then?
matt b