看着編程思想第四版,爽的是裏面的程序,當你理解到這個程序的牛逼之處時,就是你拍板叫好的那一刻,終於連追帶趕看到了第十一章持有對象,被這掃描版傷透了眼。寫完這個筆記,眼保健操是個好主意。
【隊和棧特點實驗】
package com.jay.knowledge.queue_study;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* @function: Queue的學習(對列,對,就是隊列) 典型的先進先出的容器(傳送帶似)
* @author:Jay
* @date:2013-12-5
*/
public class Queue001 {
public static void main(String[] args) {
//queue不支持ArrayList,如下會報錯
//Queue<String> queue = new ArrayList<String>();
//queue支持LinkedList
/*
Queue<String> queue = new LinkedList<String>();
queue.add("one");
queue.add("two");
queue.add("three");
queue.add("four");
queue.add("five");
queue.add("six");
Iterator<String> iterator = queue.iterator();
while (iterator.hasNext()) {
String q = (String) iterator.next();
//先進先出
System.out.print(" "+q);
}*/
Queue<String> queue = new LinkedList<String>();
queue.offer("one");
queue.offer("two");
queue.offer("three");
queue.offer("four");
queue.offer("five");
queue.offer("six");
System.out.println("------進隊順序------------");
System.out.println("one two three four five six");
System.out.println("------出隊順序------------");
//,poll刪除並移動指針,peek()查詢
System.out.print(" "+queue.poll());
System.out.print(" "+queue.poll());
System.out.print(" "+queue.poll());
System.out.print(" "+queue.poll());
System.out.print(" "+queue.poll());
System.out.print(" "+queue.poll());
System.out.println();
//比較先進後出的Stack
Stack<String> stack = new Stack<String>();
//進棧
stack.push("one");
stack.push("two");
stack.push("three");
stack.push("four");
stack.push("five");
stack.push("six");
System.out.println("------進棧順序------------");
System.out.println("one two three four five six");
System.out.println("------出棧順序------------");
//出棧pop刪除並移動指針,peek()只拿出最後進棧的值
System.out.print(" "+stack.pop());
System.out.print(" "+stack.pop());
System.out.print(" "+stack.pop());
System.out.print(" "+stack.pop());
System.out.print(" "+stack.pop());
System.out.print(" "+stack.pop());
}
}
------進隊順序------------
one two three four five six
------出隊順序------------
one two three four five six
------進棧順序------------
one two three four five six
------出棧順序------------
six five four three two one
【方法說明】
1.棧(Stack):
①peek():只取出棧頂值,但不會對棧進行操作,如果不斷去做操作,最後的得到的值是相同,此值是最後進去的值。
②push(T):向棧中添加值。
③pop():出棧,並操作棧,取出後進去的值,並刪除,然後移動指針。
2.隊列(Queue)
①peek():只取出隊列中的值,不會對棧進行操作,如果不斷去做操作,最後的得到的值是相同,此值是最先進去的值。
②offer(T):向隊列中添加值。
③poll():出隊列,並操作隊列,取出先進隊列的值,並刪除,然後移動指針。