据我了解,我不需要使用任何方法来对PriorityQueue进行排序,而只需向其中添加项目并获取项目即可使它们保持自然顺序。

队列

public class JobSetQueue extends PriorityBlockingQueue<JobSet> {
    public JobSetQueue() {
        super(1, new JobSetComparator());
    }
}


比较器

我已逐步调试通过,以验证下面的getValue()方法是否为最高优先级返回了期望值,并且返回了Comparator期望的正确值。我错了吗?为了使编译器影响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());
}

最佳答案

首先,我没有在Javadoc中看到Integer.compare,而是看到compareTo。

第二,我认为您的比较器落后了。您希望最高优先级优先于较小优先级:

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


如果01的优先级更高(例如,如果o1小于队列中要在其前面的02),则在此您将返回负数。

关于java - 我的比较器未正确排序此PriorityQueue?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16658282/

10-12 16:01