Java Stack<E>类
- Stack类是Vector的一个子类,它实现了一个标准的后进先出的栈。
- 堆栈只定义了默认构造函数,用来创建一个空栈。
Stack()
3. 除了由Vector定义的所有方法,自己也定义了一些方法:
|
方法名 |
描述 |
|
boolean empty(); |
测试此堆栈是否为空 |
|
E push(E item); |
把项压入堆栈顶部。 |
|
E peek(); |
查看堆栈顶部的对象,但不从堆栈中移除它。 |
|
E pop(); |
移除堆栈顶部的对象,并作为此函数的值返回该对象。 |
|
int search(Object o); |
返回对象在堆栈中的位置,以 1 为基数,如果不存在,则返回-1 |
示例:
Stack<Integer> stack=new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
int search = stack.search(1);
System.out.println("1在栈中的位置为:"+search);
int search1 = stack.search(0);
System.out.println("0在栈中的位置为:"+search1);
Integer peek = stack.peek();
System.out.println("peek:"+peek);
Integer pop = stack.pop();
System.out.println("pop:"+pop);
Integer peek1 = stack.peek();
System.out.println("peek1:"+peek1);
boolean empty = stack.isEmpty();
System.out.println("empty:"+empty);
运行结果
1在栈中的位置为:3 0在栈中的位置为:-1 peek:3 pop:3 peek1:2 empty:

浙公网安备 33010602011771号