PriorityQueue优先级队列

PriorityQueue是什么?

一个基于优先级堆的无界优先级队列。优先级队列的元素按照其自然顺序进行排序,或者根据构造队列时提供的 Comparator 进行排序,具体取决于所使用的构造方法。优先级队列不允许使用 null 元素。依靠自然顺序的优先级队列还不允许插入不可比较的对象(这样做可能导致 ClassCastException

方法:

1).add:插入一个元素,成功:true,失败:ClassCastException - 优先级队列的顺序无法将指定元素与此优先级队列中当前元素进行比较;NullPointerException - 指定元素为 null

    public boolean add(E e) {
        return offer(e);
    }

2).offer:插入一个元素,成功:true,失败:ClassCastException - 优先级队列的顺序无法将指定元素与此优先级队列中当前元素进行比较;NullPointerException - 指定元素为 null

    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }

3).remove:删除一个元素,如果不成功会返回false。

    public boolean remove(Object o) {
        int i = indexOf(o);
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }

4).poll:删除队列头元素,并返回删除的元素

    public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }

5).peek:获取但不移除此队列的头;如果此队列为空,则返回 null

    public E peek() {
        if (size == 0)
            return null;
        return (E) queue[0];
    }

    private int indexOf(Object o) {
        if (o != null) {
            for (int i = 0; i < size; i++)
                if (o.equals(queue[i]))
                    return i;
        }
        return -1;
    }

6).indexOf(Object o):查找对象o的索引;

    private int indexOf(Object o) {
        if (o != null) {
            for (int i = 0; i < size; i++)
                if (o.equals(queue[i]))
                    return i;
        }
        return -1;
    }

7).contain(Object o):判断是否容纳了元素

    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

户枢不蠹,流水不腐

原文地址:https://www.cnblogs.com/yunianzeng/p/13229129.html