java中栈Stack类操作

时间:2022-04-08 17:41:57
/**
* Stack类
* 栈:桶型或箱型数据类型,后进先出,相对堆Heap为二叉树类型,可以快速定位并操作
* Stack<E>,支持泛型
* public class Stack<E> extends Vector<E>
* Stack的方法调用的Vector的方法,被synchronized修饰,为线程安全(Vector也是)
* Stack methods:
* push : 把项压入堆栈顶部 ,并作为此函数的值返回该对象
* pop : 移除堆栈顶部的对象,并作为此函数的值返回该对象
* peek : 查看堆栈顶部的对象,,并作为此函数的值返回该对象,但不从堆栈中移除它
* empty : 测试堆栈是否为空
* search : 返回对象在堆栈中的位置,以 1 为基数
* */

操作代码为下:

package ca.map;

import java.util.Stack;

public class StackX {
public static void main(String[] args) {
stackMethod();
}
//stack operate
public static void stackMethod(){
//定义一个Integer泛型的Stack
Stack<Integer> stack = new Stack<Integer>();
System.out.println("新建栈stack是否为空 : "+(stack.empty() ? "空" : stack.size()));
//push : 把项压入堆栈顶部,返回值泛型指定的类型
//此处将1到5压入栈中
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("将1到5按顺序压入栈中后为:"+stack);
//empty : 测试堆栈是否为空,size() == 0,返回值boolean
System.out.println("值为1~5的栈中stack是否为空 : "+(stack.empty() ? "空" : stack.size()));
//search : 返回对象在堆栈中的位置,以 1 为基数,参数:search(Object o) ,返回值int
int oStack = stack.search(3);
System.out.println("查找栈stack中对象3的位置elementId为 : "+oStack);
//peek : 查看堆栈顶部的对象,但不从堆栈中移除它,返回值泛型指定的类型
int topElement =stack.peek();
System.out.println("查看stack的栈顶元素为 : "+topElement);
System.out.println("peek操作stack后为 : "+stack);
//pop : 移除堆栈顶部的对象,并作为此函数的值返回该对象,返回值泛型指定的类型
int oRemove = stack.pop();
System.out.println("移除stack栈顶的元素为 : "+oRemove);
System.out.println("pop操作移除stack栈顶元素后为 : "+stack);
}
}

输出为:

新建栈stack是否为空 : 空
将1到5按顺序压入栈中后为:[1, 2, 3, 4, 5]
值为1~5的栈中stack是否为空 : 5
查找栈stack中对象3的位置elementId为 : 3
查看stack的栈顶元素为 : 5
peek操作stack后为 : [1, 2, 3, 4, 5]
移除stack栈顶的元素为 : 5
pop操作移除stack栈顶元素后为 : [1, 2, 3, 4]

Stack的toString()方法继承自Vector的toString()方法;

Vector的toString()方法super.toString()继承自AbstractList继承自AbstractCollection的toString()方法:

代码为:

    public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";

StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}

若集合为空,返回  []

若集合不为空则 [  加上迭代元素 加上 , 最后集合无元素加上 ] eg:[1, 2, 3, 4]