Throws exception | Returns special value | |
Insert | add(e) | offer(e) |
Remove | remove() | poll() |
Examine | element() | peek() |
packagecom.ipmotor.sm.db;
importjava.util.LinkedList;
importjava.util.Queue;
importjava.util.Stack;
/**
*测试jdk中的栈和队列
*@authorscott
*
*/
publicclassTestQueueAndStack{
/**
*测试队列
*<pre>
*队列特点,先进先出,后进后出,火车过山洞例子
*</pre>
*/
staticvoidtestQueue(){
Queue<String>queue=newLinkedList<String>();
//添加几个元素
queue.offer("a");
queue.offer("b");
queue.offer("c");
queue.offer("d");
queue.offer("e");
queue.add("1");
queue.add("2");
queue.add("3");
queue.add("4");
queue.add("5");
System.out.println("队列中的元素是:"+queue);
//弹出元素
queue.poll();
System.out.println("队列中的元素是:"+queue);
//查看队列中首个元素,并不移除
Stringpeek=queue.peek();
System.out.println("查看队列中首个元素,并不移除:"+peek);
System.out.println("队列中的元素是:"+queue);
}
/**
*测试栈
*<pre>
*先进后出,后进先出,水桶倒水
*</pre>
*/
staticvoidtestStack(){
Stack<String>stack=newStack<String>();
//添加几个元素
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");
stack.add("1");
stack.add("2");
stack.add("3");
stack.add("4");
stack.add("5");
System.out.println("栈中的元素是:"+stack);
//弹出元素
stack.pop();
System.out.println("栈中的元素是:"+stack);
//查看栈中首个元素,并不移除
Stringpeek=stack.peek();
System.out.println("查看栈中首个元素,并不移除:"+peek);
System.out.println("栈中的元素是:"+stack);
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
testQueue();
System.out.println("-------栈--------");
testStack();
}
}
队列中的元素是:[a, b, c, d, e, 1, 2, 3, 4, 5]
队列中的元素是:[b, c, d, e, 1, 2, 3, 4, 5]
查看队列中首个元素,并不移除:b
队列中的元素是:[b, c, d, e, 1, 2, 3, 4, 5]
-------栈--------
栈中的元素是:[a, b, c, d, e, 1, 2, 3, 4, 5]
栈中的元素是:[a, b, c, d, e, 1, 2, 3, 4]
查看栈中首个元素,并不移除:4
栈中的元素是:[a, b, c, d, e, 1, 2, 3, 4]