有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java排队/退队或报价/投票

这似乎是一个非常基本的问题,但我已经被困了几个小时

我们何时使用方法排队/退队&;我们什么时候使用报价/投票

我想用void enqueue(int x, int p)int dequeue()方法创建一个整数的PQ,如何声明这样的队列

谢谢


共 (1) 个答案

  1. # 1 楼答案

    我假设“PQ”意味着“优先级队列”。我从未使用过这样的队列(我心目中的队列是一个严格的FIFO结构),但在阅读了文档后,我认为您可以这样做:

    首先,需要创建要存储在队列中的对象的类。假设int内容和int优先级:

    public class MyClass implements Comparable<MyClass> {
        private int x, p;
    
        /*
         * x: Contents
         * p: Priority
         */
        public MyClass(int x, int p) {
            this.x = x;
            this.p = p;
        }
    
        @override
        public int compareTo(MyClass o) {
            return this.p - o.p;
        }
    
        public int getX() {
            return x;
        }
    }
    

    现在,创建优先级队列。如果我正确理解了类文档,它将使用compareTo方法对对象进行排序:

    ....
    PriorityQueue<MyClass> pq = new PriorityQueue<MyClass>();
    ....
    pq.add(new MyClass(x, p));
    ....
    

    检查:http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

    Java队列没有enqueuedequeue方法;这些操作使用以下方法完成:

    • 排队:
      • add(e):如果无法插入对象,则引发异常
      • offer(e):如果无法插入对象,则返回false
    • 退队:
      • remove():如果队列为空,则引发异常
      • poll():如果队列为空,则返回null
    • 看看队列中的第一个对象:
      • element():如果队列为空,则引发异常
      • peek():如果队列为空,则返回null

    现在,最后一点:什么时候使用offeradd

    关于offeradd:这取决于您希望如何处理队列中插入失败的情况:

    The add method, which Queue inherits from Collection, inserts an element unless it would violate the queue's capacity restrictions, in which case it throws IllegalStateException. The offer method, which is intended solely for use on bounded queues, differs from add only in that it indicates failure to insert an element by returning false.

    (见:http://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html

    希望这对你有帮助