• Java中的容器 I————浅谈Queue和PriorityQueue


    一.Queue的实现

    通过LinkedList类实现Queue接口来完成对Queue的实例类的实现,代码如下:

    Queue<Integer> queue=new LinkedList<>();//linkedList实现了Queue接口,将其向上转型为队列

    二.Queue的方法

    1.offer————加入元素(加入至队尾)

    queue.offer(2);//使用offer将元素插入队尾

    2.remove,poll————返回头结点并删除元素

    区别remove方法在队列为空时将抛出异常,而poll将返回null

    queue.remove();//remove poll 返回头结点并移除 remove在空时抛出异常  但是poll返回null

    3.element,peek ————返回头结点,不删除元素

    区别element方法在队列为空时将抛出异常,而peek 将返回null

    queue.peek();//删除头结点peek/element都是返回队头但是不移除队头,但是peek在没有元素时返回null  element抛出异常

     

    三.PriorityQueue队列(优先级队列)的实现

    注意点:

    在实现了comparator接口的类可以PriorityQueue队列中调用offer方法实现排序

    代码如下:

            PriorityQueue<Integer> pque=new PriorityQueue<>();
            pque.offer(6);//使用offer添加可以保证有序
            pque.offer(0);
            pque.offer(23);
            pque.offer(1);
            System.out.println(pque);//0 1 23 6
            pque.add(3);//使用add方法无法排序
            System.out.println(pque);//无须

      

    (补充)

    一.了解collection和iterator的关系

    首先只有实现了iterator接口的才能使用foreach遍历(数组除外)。

    collection是iterator接口的子接口

    public interface Collection<E> extends Iterable<E> {

    所以collection所有的子接口可以实现foreach遍历。

  • 相关阅读:
    11.MySQL
    10、设计模式
    9
    8
    7
    6
    5
    4
    3
    2
  • 原文地址:https://www.cnblogs.com/SAM-CJM/p/9381116.html
Copyright © 2020-2023  润新知