Deque是一个更精简的元素集合,支持两端元素的插入和删除。 它发音为’双端队列’。 Deque接口提供了插入,删除和检查队列两端元素的方法。 这些方法是:
addFirst()
,offerFirst()
和push()
- 将元素插入双端队列的头部。add()
,addLast()
,offerLast()
和offer()
- 将元素插入双端队列的尾部。element()
,getFirst()
,peek()
和peekFirst()
- 从双端队列的头部检索元素。getLast()
和peekLast()
- 从双端队列的尾部检索元素。remove()
,removeFirst()
,poll()
,pollFirst()
和pop()
- 从双端队列中删除元素。removeLast()
和pollLast()
- 从双端队列的尾部删除元素。
ArrayDeque
和LinkedList
是Collection API中Deque接口的实现。
文件:DequeExample.java -
package com.yiibai.tutorial;
import java.util.Deque;
import java.util.LinkedList;
/**
* @author yiibai
*
*/
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new LinkedList<>();
/*Adding element to deque*/
deque.add("One");
deque.addFirst("Two");
deque.addLast("Three");
deque.offer("Four");
deque.offerFirst("Five");
deque.offerLast("Six");
deque.push("Seven");
System.out.println("Elements in deque: "+deque);
System.out.println();
/*Retrieving elements from deque*/
System.out.println("element() : "+deque.element());
System.out.println("getFirst() : "+deque.getFirst());
System.out.println("getLast() : "+deque.getLast());
System.out.println("peek() : "+deque.peek());
System.out.println("peekFirst() : "+deque.peekFirst());
System.out.println("peekLast() : "+deque.peekLast());
/*Removing elements from deque */
System.out.println();
System.out.println("remove() : "+deque.remove());
System.out.println("Elements in deque after removal : "+deque);
System.out.println("removeFirst() : "+deque.removeFirst());
System.out.println("Elements in deque after removal : "+deque);
System.out.println("removeLast() : "+deque.removeLast());
System.out.println("Elements in deque after removal : "+deque);
System.out.println("poll() : "+deque.poll());
System.out.println("Elements in deque after removal : "+deque);
System.out.println("pollFirst() : "+deque.pollFirst());
System.out.println("Elements in deque after removal : "+deque);
System.out.println("pollLast() : "+deque.pollLast());
System.out.println("Elements in deque after removal : "+deque);
System.out.println("pop() : "+deque.pop());
System.out.println("Elements in deque after removal : "+deque);
}
}
执行上面示例代码,得到以下结果:
Elements in deque: [Seven Five Two One Three Four Six]
element() : Seven
getFirst() : Seven
getLast() : Six
peek() : Seven
peekFirst() : Seven
peekLast() : Six
remove() : Seven
Elements in deque after removal : [Five Two One Three Four Six]
removeFirst() : Five
Elements in deque after removal : [Two One Three Four Six]
removeLast() : Six
Elements in deque after removal : [Two One Three Four]
poll() : Two
Elements in deque after removal : [One Three Four]
pollFirst() : One
Elements in deque after removal : [Three Four]
pollLast() : Four
Elements in deque after removal : [Three]
pop() : Three
Elements in deque after removal : []