Java.util.Stack类的peek()方法

时间:2021-02-21 19:10:10

java.util.Stack这个类不难,但需要注意其中的peek()方法: 查看栈顶对象而不移除它

 

import java.util.Date;
import java.util.Stack;


public class StackDemo {

  
    public static void main(String[] args) {
 Stack stack=new Stack();
 stack.push("0");
 stack.push(new Integer(1));
 stack.push(2.0);
 stack.push(new Date());
 
 System.out.println("stack.size()==>"+stack.size());
 System.out.println(stack);
 
 System.out.println("stack.pop()==>"+stack.pop());
 System.out.println("stack.peek()==>"+stack.peek());//peek()方法 查看栈顶对象而不移除它
 System.out.println("stack.pop()==>"+stack.pop());
    }

}

 


运行结果:

stack.size()==>4
[0, 1, 2.0, Tue Jul 21 22:50:40 CST 2009]
stack.pop()==>Tue Jul 21 22:50:40 CST 2009
stack.peek()==>2.0
stack.pop()==>2.0