2013-05-20 44 views
1

我的理解是,我不需要使用任何方法來對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()); 
} 

回答

0

首先,我沒有看到Integer.compare在Javadoc中,我看到的compareTo。

其次,我認爲你的比較是落後的。你想要的最高優先級來之前一個較小的一個:

@Override 
    public int compare(JobSet o1, JobSet o2) { 
     return o2.getHighestPriority().getValue() - o1.getHighestPriority().getValue()); 
    } 

在這裏你會返回一個負數,如果01的優先級越高(即如果01小於02來之前,在隊列中)。

+0

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29 –

+0

謝謝,我正在研究Java 6的javadoc。我的錯誤 – vptheron

+0

編號compareTo(a,b)本質上應該返回ab。在任何情況下,以相同順序調用另一個compare()方法都是相同的參數不能是錯誤的。 – EJP

3

我懷疑你期望PQ的迭代器按順序迭代。它沒有。看到Javadoc。訂單的PQ只有在清除時才能觀察到。

+0

您正確的說明,由PriorityQueue實現的迭代器接口不會按優先順序進行迭代,但它不相關,因爲quesion中的代碼使用[poll()](http://docs.oracle.com/javase/6/ docs/api/java/util/PriorityQueue.html#poll()),它刪除了隊列的頭部並且會遵守優先級。 – Ryan