首页 > 其他 > 详细

Stack类的使用

时间:2015-08-13 15:54:14      阅读:150      评论:0      收藏:0      [点我收藏+]
  • java.lang.Object
  • Stack类的继承关系如上,其直接继承自Vector,Vector可以作为一个集合使用。Stack在其上完成了“后进先出”的功能。
  • Stack实现的接口如下:
  • SerializableCloneableIterable<E>, Collection<E>, List<E>, RandomAccess
  • Stack的主要方法有:
  • boolean empty()
    Tests if this stack is empty.测试栈是否为空
    E peek()
    Looks at the object at the top of this stack without removing it from the stack.返回栈顶元素,但并不在栈中删除
    E pop()
    Removes the object at the top of this stack and returns that object as the value of this function.返回栈顶元素,在栈中删除
    E push(E item)
    Pushes an item onto the top of this stack.“压入”元素进栈
    int search(Object o)
    Returns the 1-based position where an object is on this stack.查找元素,返回元素在栈中第一次出现的位置,位置从1算起(非0)
    package yuchen.com;
    
    import java.util.Stack;
    
    public class StackTest {
    
    	public static void main(String[] args){
    		
    		//新建一个栈对象
    		Stack<Integer> s=new Stack<Integer>();
    		
    		//向栈中压入 1 2 3 4 5 6
    		s.push(1);
    		s.push(2);
    		s.push(3);
    		s.push(4);
    		s.push(5);
    		s.push(6);
    		
    		
    		//在栈中搜素元素5,因为元素5是在最后倒数第二次压入的,所以其位置为2
    		//****注意,这里的位置是从1算起的******
    		System.out.println("元素5的位置:"+s.search(5));
    		
    		//从栈中依次取出元素
    		while(!(s.isEmpty())){
    			int intStack = s.pop();
    			System.out.print(intStack+" ");
    		}
    	}
    }
    
    输出结果:
  • 元素5的位置:2
    6 5 4 3 2 1 

  • PS:Stack中也有add(E e)这个方法,其也能向Stack对象中添加元素,与push(E e)类似,究竟他们有什么区别呢?
  • 1、为了程序的可读性更强,使用push方法更能让人明白,针对的是Stack的操作
  • 2、add是继承自List<E>接口的方法,返回值为boolean;push返回的是添加元素的对象E 
    所以,在Stack中添加元素,就是用push吧!

版权声明:本文为博主原创文章,未经博主允许不得转载。

Stack类的使用

原文:http://blog.csdn.net/wuyzhen_csdn/article/details/47612097

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!