Stack类的使用

  • 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吧!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值