简体   繁体   English

PriorityQueue.poll();

[英]PriorityQueue.poll();

Does anyone have any suggestions as to what the best way to modify an object's compareTo function so that when the parent priority queue's "poll()" function is called the lowest non-negative value is returned, as opposed to the lowest value in general? 有没有人对修改对象的compareTo函数的最佳方法有什么建议,以便在调用父优先级队列的“poll()”函数时返回最低的非负值,而不是一般的最低值?

Say, we have a Number class that stores any number, negative or non-negative, but I don't want the data from an object of that class returned if it's negative. 比方说,我们有一个Number类存储任何数字,负数或非负数,但我不希望返回该类对象的数据,如果它是负数。

Wrap your Queue inside a wrapper object, and never add negative values. 将您的队列包装在包装器对象中,并且永远不会添加负值。 Then you can use your queue as normal, knowing the lowest value will be non-negative. 然后你可以正常使用你的队列,知道最低值将是非负的。

Here's a rough draft. 这是草稿。 I didn't compile it or anything, but it's an idea. 我没有编译它或任何东西,但这是一个想法。 Here's an example of that. 这是一个例子。

import java.util.*;
class PositiveQueue<E extends Number> extends PriorityQueue<Number> {

    public boolean offer(E e) {
        if(isNegative(e)) return false;
        return super.offer(e);
    }

    private static boolean isNegative(Number n) {
        // add logic here
        return n.intValue() < 0;
    }

    public static void main(String[] args) {

        PositiveQueue<Short> q = new PositiveQueue<Short>();
        q.offer((short)4);
        q.offer((short)7);
        q.offer((short)2);
        q.offer((short)-5);
        q.offer((short)5);

        while(q.peek() != null) System.out.println(q.poll());
    }

}

C:\Documents and Settings\glowcoder\My Documents>javac PositiveQueue.java

C:\Documents and Settings\glowcoder\My Documents>java PositiveQueue
2
4
5
7

Ok, so let's sort things out a little: 好的,让我们稍微解决一下:

  1. You want to put negative numbers into your queue? 想把负数放入你的队列?
  2. You do not want those numbers to be returned at all when de-queueing elements? 排队元素时,您希望返回这些数字吗?
  3. What else do you want to do with those numbers which are in the queue but will never leave the queue again? 你想与那些在队列中,但永远不会再离开队列号码做什么?

A queue in Java can only hold objects, by the way, so you can use null instead of some other magic value. 顺便说一句,Java中的队列只能保存对象,因此您可以使用null而不是其他一些魔术值。

I assume you need to allow duplicate values in your implementation. 我假设您需要在实现中允许重复值。 If not, though, have a look at implementations of SortedSet . 但是,如果没有,请查看SortedSet实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM