编程语言
首页 > 编程语言> > 源码分析之Queue(一)Queue 与 Deque

源码分析之Queue(一)Queue 与 Deque

作者:互联网

Queue源码解析

  Queue是Java集合框架中的一员,继承于Collection接口。与List、Set相同的是,Queue也实现了一种数据结构,这就是队列。队列是计算机中的一种数据结构,保存在其中的数据具有“先进先出(FIFO,First In First Out)”的特性。

public interface Queue<E> extends Collection<E> {
    /**
     * Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions
     * 将元素插入队列*/
    boolean add(E e);

    /**
     * Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
     * 将元素插入队列,与add相比,在容量受限时应使用这个*/
    boolean offer(E e);

    /**
     * Retrieves and removes the head of this queue.  This method differs from {@link #poll poll} only in that it throws an exception if this queue is empty.
     * 将队首的元素删除,当队列为空时,则抛出异常
*/
    E remove();

    /**
     * Retrieves and removes the head of this queue,or returns {@code null} if this queue is empty.
     * 将对首的元素删除,当队列为空时,则返回null
     * @return the head of this queue, or {@code null} if this queue is empty
     */
    E poll();

    /**
     * Retrieves, but does not remove, the head of this queue.  This method differs from {@link #peek peek} only in that it throws an exception if this queue is empty.
* 获取队首元素但不移除,当队列为空时,则抛出异常 * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ E element(); /** * Retrieves, but does not remove, the head of this queue,or returns {@code null} if this queue is empty.
   * 获取队首元素但不移除,当队列为空时,则返回Null * @return the head of this queue, or {@code null} if this queue is empty */ E peek(); }

Deque源码解析 

  Deque全称为double ended queue,即双向队列,它允许在两侧插入或删除元素,同时也建议我们不要向其中插入null值。除此之外,其余特性则和父级Queue类似。Deque中定义的方法主要分为四部分,第一部分就如Deque定义所言,提供两侧插入或删除的方法。第二部分是继承自Queue的实现。第三部分表示如果要基于此实现一个Stack,需要实现的方法。最后一部分是继承自Collection的方法。

public interface Deque<E> extends Queue<E> {
  //针对两侧操作

   //在队首添加元素
   void addFirst(E e);
   //在队首添加元素
   boolean offerFirst(E e);
   //在队尾添加元素
   void addLast(E e);
   boolean offerLast(E e);
   //删除队首元素
   E removeFirst();
   E pollFirst();
   //删除队尾元素
   E removeLast();
   E pollLast();

   //获取队首元素
   E getFirst();
   E peekFirst();

   //获取队尾元素
   E getLast();
   E peekLast();

   //删除第一个事件,大多数指的是删除第一个和 o equals的元素
   boolean removeFirstOccurrence(Object o);
   //删除最后一个事件,大多数指的是删除最后一个和 o equals的元素
   boolean removeLastOccurrence(Object o);

 //实现Stack  Stack仅在一侧支持插入删除操作等操作,遵循LIFO原则。
   //与addFirst()等价
   void push(E e);

   //与removeFirst()等价
   E pop();
}

标签:Deque,删除,队首,元素,queue,Queue,源码,empty
来源: https://www.cnblogs.com/ryjJava/p/14324257.html