我的理解是,我不需要使用任何方法來對PriorityQueue
進行排序,但僅向其中添加項目並獲取項目會使它們按自然順序排列。我的比較器沒有正確排序此PriorityQueue?
隊列
public class JobSetQueue extends PriorityBlockingQueue<JobSet> {
public JobSetQueue() {
super(1, new JobSetComparator());
}
}
比較
我已經通過調試走到驗證的getValue()方法,下面是最高優先級,正確的值返回預期值返回比較器期望的值。我錯了嗎? 有什麼我需要做的,爲了讓編輯器影響PriorityQueue命令?
public class JobSetComparator implements Comparator<JobSet> {
@Override
public int compare(JobSet o1, JobSet o2) {
return Integer.compare(o1.getHighestPriority().getValue(), o2.getHighestPriority().getValue());
}
}
優先
public class Priority {
public static final Priority TOP = new Priority("TOP", 1000);
public static final Priority PRIORITY_REMAN = new Priority("PRIORITY_REMAN", 750);
public static final Priority PRIORITY = new Priority("PRIORITY", 500);
public static final Priority STANDARD_REMAN = new Priority("STANDARD_REMAN", 250);
public static final Priority STANDARD = new Priority("STANDARD", 100);
private final String name;
private final int value;
protected Priority(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String toString() {
return getName();
}
}
我的測試:
所有的@Before
public void setUp() {
queue = new JobSetQueue();
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.STANDARD), 1)));
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.PRIORITY_REMAN), 1)));
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.PRIORITY), 1)));
}
@Test
public void testTop() {
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.TOP), 1)));
Assert.assertEquals("Queue priority,", Priority.TOP, queue.poll().getJobUnitList().get(0).getProduct().getPriority());
}
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29 –
謝謝,我正在研究Java 6的javadoc。我的錯誤 – vptheron
編號compareTo(a,b)本質上應該返回ab。在任何情況下,以相同順序調用另一個compare()方法都是相同的參數不能是錯誤的。 – EJP