java集合类——Stack类

查看java的API文档,Stack继承Vector类。 
栈的特点是后进先出。 
API中Stack自身的方法不多,基本跟栈的特点有关。 

Java代码  收藏代码
  1. import java.util.Stack;  
  2.   
  3.   
  4. public class StackTest {  
  5.   
  6.     public static void main(String[] args) {  
  7.         Stack<String> stack = new Stack<String>();  
  8.         System.out.println("now the stack is " + isEmpty(stack));  
  9.         stack.push("1");  
  10.         stack.push("2");  
  11.         stack.push("3");  
  12.         stack.push("4");  
  13.         stack.push("5");  
  14.         System.out.println("now the stack is " + isEmpty(stack));  
  15.         System.out.println(stack.peek());  
  16.         System.out.println(stack.pop());  
  17.         System.out.println(stack.pop());  
  18.         System.out.println(stack.search("2"));  
  19.     }  
  20.     public static String isEmpty(Stack<String> stack) {  
  21.         return stack.empty() ? "empty" : "not empty";  
  22.     }  
  23. }  



输出为: 

Java代码  收藏代码
    1. now the stack is not empty  
    2. 5  
    3. 5  
    4. 4  
    5. 2  
posted @ 2016-12-09 12:45  天涯海角路  阅读(107)  评论(0)    收藏  举报