队列:先进先出,应用于抢购等等。
add 添加元素
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素,只查看元素 如果队列为空,则返回nul
public class Queue {
public static void main(String[] args){
java.util.Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
System.out.println(queue);
queue.poll();
System.out.println("poll()方法");
System.out.println(queue);
Integer i = queue.peek();
System.out.println("peek()方法");
System.out.println(i);
}
}
输出结果为:
[1, 2, 3, 4, 5]
poll()方法
[2, 3, 4, 5]
peek()方法
2
堆栈:先进后出
add 添加元素
push 添加元素
pop 删除最上方的元素,也就是最后一个添加的元素
peek 查找最上方的元素,也就是最后一个添加的元素
public class Stack {
public static void main(String[] args){
java.util.Stack<Integer> stack = new java.util.Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack);
stack.pop();
System.out.println("pop()方法");
System.out.println(stack);
Integer i = stack.peek();
System.out.println("peek()方法");
System.out.println(i);
}
}
其他参考资料:
http://blog.youkuaiyun.com/u011240877/article/details/52860924
http://www.cnblogs.com/end/archive/2012/10/25/2738493.html