ArrayDeque的源码分析:
ITEYE:Java-Collections Framework学习与总结-ArrayDeque
CSDN:Java多线程(六)之Deque与LinkedBlockingDeque深入分析
这篇文章的1.1部分分析了ArrayDeque的源码
小示例:
package org.lgy.study.collection;
import java.util.ArrayDeque;
/*
javac -d classes "src/org/lgy/study/collection/ArrayDequeTest.java"
java org.lgy.study.collection.ArrayDequeTest
*/
public class ArrayDequeTest{
public static void main(String[] args){
// stack();
doubleQueue();
}
// ArrayDuque作为双端队列使用
public static void doubleQueue(){
// 创建ArrayDeque作为双端队列
ArrayDeque<String> ad = new ArrayDeque<>();
// add、addLast、offer、offerLast都是在队尾添加元素
ad.add("111");
ad.addLast("222");
ad.offer("333");
ad.offerLast("444");
System.out.println(ad + "\n"); // [111, 222, 333, 444]
// addFirst、offerFirst是在队头添加元素
ad.addFirst("555");
ad.offerFirst("666");
System.out.println(ad + "\n"); // [666, 555, 111, 222, 333, 444]
// element、peek、getFirst、peekFirst 获取但不删除队首的元素
System.out.println("ad.element() = " + ad.element()); // ad.element() = 666
System.out.println("ad.peek() = " + ad.peek()); // ad.peek() = 666
System.out.println("ad.getFirst() = " + ad.getFirst()); // ad.getFirst() = 666
System.out.println("ad.peekFirst() = " + ad.peekFirst()); // ad.peekFirst() = 666
System.out.println(ad + "\n"); // [666, 555, 111, 222, 333, 444]
// getLast、peekLast 获取但不删除队尾的元素
System.out.println("ad.getLast() = " + ad.getLast()); // ad.getLast() = 444
System.out.println("ad.peekLast() = " + ad.peekLast()); // ad.peekLast() = 444
System.out.println(ad + "\n"); // [666, 555, 111, 222, 333, 444]
// remove、poll、removeFirst、pollFirst都是删除并返回队首的元素
System.out.println("ad.remove() = " + ad.remove()); // ad.remove() = 666
System.out.println("ad.poll() = " + ad.poll()); // ad.poll() = 555
System.out.println("ad.removeFirst() = " + ad.removeFirst()); // ad.removeFirst() = 111
System.out.println("ad.pollFirst() = " + ad.pollFirst()); // ad.pollFirst() = 222
System.out.println(ad + "\n"); // [333, 444]
// removeLast、pollLast是删除并返回队尾的元素
System.out.println("ad.removeLast() = " + ad.removeLast()); // ad.removeLast() = 444
System.out.println("ad.pollLast() = " + ad.pollLast()); // ad.pollLast() = 333
System.out.println(ad + "\n"); // []
}
// ArrayDeque作为“栈”
public static void stack(){
// 创建ArrayDeque,作为栈
ArrayDeque<String> ad = new ArrayDeque<>();
// 入栈
ad.push("111");
ad.push("222");
ad.push("333");
ad.push("444");
// 栈中元素的个数
System.out.println("size = " + ad.size());
// 出栈前,输出栈中的所有元素
System.out.println("出栈前:" + ad);
// 出栈
int size = ad.size();
for(int i = 0; i < size; i++){
System.out.println(ad.pop());
}
// 出栈后,输出栈中的所有元素
System.out.println("出栈后:" + ad);
/*
结果:
size = 4
出栈前:[444, 333, 222, 111]
444
333
222
111
出栈后:[]
*/
}
}