- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractList<E>
-
- java.util.Vector<E>
-
- java.util.Stack<E>
- Stack类的继承关系如上,其直接继承自Vector,Vector可以作为一个集合使用。Stack在其上完成了“后进先出”的功能。
- Stack实现的接口如下:
- Serializable, Cloneable, Iterable<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类的使用
最新推荐文章于 2022-10-06 19:01:11 发布