My SSCE:
public class ComparableItem implements Comparable<ComparableItem> {
private final int itemNo;
public ComparableItem(final int itemNo) {
this.itemNo = itemNo;
}
@Override
public int compareTo(ComparableItem o) {
if (this.itemNo < o.itemNo) {
return -1;
} else if (this.itemNo > o.itemNo) {
return 1;
}
return 0;
}
}
Here’s a test that demonstrates the problem. The code breaks after the PQ is created. The lines above are to prove that the natural ordering defined by compareTo(..) works as expected.
Printing the elements of the PQ they are: 14,9,15,5,6,3 versus the expected 15,14,9,6,5,3. Could someone explain to me why this is the case?
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class CompTest{
@Test
public void aTest() {
Integer[] order = {9, 3, 14, 15, 6, 5};
List<ComparableItem> items = new ArrayList<ComparableItem>(order.length);
for (int i = 0; i < order.length; i++) {
items.add(new ComparableItem(order[i]));
}
List<ComparableItem> greater = new ArrayList<ComparableItem>();
testCompare(items, items.get(3), greater, true);
testCompare(items, items.get(2), greater, true);
testCompare(items, items.get(0), greater, true);
testCompare(items, items.get(4), greater, true);
testCompare(items, items.get(5), greater, true);
testCompare(items, items.get(1), greater, true);
final PriorityQueue<ComparableItem> itemsQueue = new PriorityQueue<ComparableItem>(items);
greater = new ArrayList<ComparableItem>();
for (ComparableItem c : itemsQueue) {
testCompare(itemsQueue, c, greater, false);
}
}
public static void testCompare(final Collection<ComparableItem> items, final ComparableItem item, final List<ComparableItem> greater, boolean bigger) {
final int exp = (bigger)? -1:1;
for (ComparableItem c : items) {
final int expected = c.equals(item) ? 0 : greater.contains(c) ? exp : exp*-1;
assertEquals(expected, item.compareTo(c));
assertEquals(expected * -1, c.compareTo(item));
}
greater.add(item);
}
}
new PriorityQueue<ComparableItem>(items);
Creates a PriorityQueue containing the
elements in the specified collection.
If the specified collection is an
instance of a SortedSet or is another
PriorityQueue, this priority queue
will be ordered according to the same
ordering. Otherwise, this priority
queue will be ordered according to the
natural ordering of its elements.
I think that the problem is not in the queue, but in the way that you are testing it. In particular, the javadoc for
PriorityQueue.iterator()states:And the class javadoc says this: