如题,用Collections.addAll()方法给Stack和LinkedList添加元素,添加进去的顺序是不同的。
下面的代码说明了这个结果:
package com.lwc.Stack;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Stack;
public class StackTest {
public static void main(String[] agrs) {
Stack<String> stk = new Stack<String>();
Collections.addAll(stk, "one","two","three","four","five","six");
System.out.println(stk);
System.out.println(stk.peek());
LinkedList<String> lkt = new LinkedList<String>();
Collections.addAll(lkt, "one","two","three","four","five","six");
System.out.println(lkt);
System.out.println(lkt.peek());
}
}
运行结果:
[one, two, three, four, five, six]
six
[one, two, three, four, five, six]
one
Stack和LinkedList都有peek()方法,都是用于返回第一个元素。
结果说明,如果用Collections.addAll()给LinkedList添加元素,则按顺序往后面添加。而Stack刚好相反,每个后添加的元素会被添加到先添加元素的前面。这也正是栈的目的。