Stack summary

The relationship between Stack and Collection

  • public class Stack extends Vector
  • Stack inherits from Vector, and the underlying implementation is an array.

Stack method

  • Java has only one constructor without parameters.
  • Excluding methods inherited from Vector, Stack has five other methods, including:
    • boolean, empty (), test whether the stack is empty.
    • E, peek (), view the object at the top of the stack, but do not remove it from the stack.
    • E. pop (), remove the object at the top of the stack, and return the object as the value of this function.
    • E, push (E item), push the item onto the top of the stack.
    • int, search (Object o), return the position of the object on the stack, the index of the top element of the stack is 1. If the object does not exist on the stack, -1 is returned.

Stack application examples

package com.tsui.demo;

import java.util.Stack;

/**
 * 测试Stack
 */
public class TestStack {
	
	public static void main(String[] args) {
		
		Stack<Integer> stack = new Stack<Integer>();
		
		//测试堆栈是否为空
		System.out.println(stack.empty());//true
		
		//把项压入堆栈顶部
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		
		
		//查看堆栈顶部的对象,但不从堆栈中移除它
		System.out.println(stack.peek());//5
		
		//移除堆栈顶部的对象,并作为此函数的值返回该对象
		System.out.println(stack.pop());//5
		System.out.println(stack.pop());//4
		
		//判断指定元素是否在栈中,如果在返回1,不在返回-1。
		System.out.println(stack.search(2));//2
		System.out.println(stack.search(6));//-1
	}
}
Published 12 original articles · praised 0 · visits 89

Guess you like

Origin blog.csdn.net/charlotte_tsui/article/details/103686703