相同點:都返回棧頂的值。
不同點:peek 不改變棧的值(不刪除棧頂的值),pop會把棧頂的值刪除。
下面通過代碼展現
/*
* 文 件 名: TestPeekAndPopDiff.java
*/
import java.util.List;
import java.util.Stack;
/**
* @author
* @since
*/
public class TestPeekAndPopDiff {
public static void main(String[] args) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
// 將1,2,3,4,5添加到棧中
for (int i = 1; i < 6; i++) {
stack1.push(i);
stack2.push(i);
}
stack1.peek();
stack2.pop();
System.out.println("peek stack1:");
iteratorThroughRandomAccess(stack1);
System.out.println("pop stack2:");
iteratorThroughRandomAccess(stack2);
}
/**
* 通過快速訪問遍歷Stack
*/
public static void iteratorThroughRandomAccess(List list) {
Integer val = 0;
for (int i = 0; i < list.size(); i++) {
val = (Integer) list.get(i);
System.out.print(val + " ");
}
System.out.println();
}
// 相同點:都返回棧頂的值。
// 不同點:peek 不改變棧的值(不刪除棧頂的值),pop會把棧頂的值刪除。
}
輸出結果:
peek stack1:
1 2 3 4 5
pop stack2:
1 2 3 4