集册 Java实例教程 使用固定大小的数组实现堆栈。

使用固定大小的数组实现堆栈。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

403
使用固定大小的数组实现堆栈。

import static java.lang.System.out;

/** from 时代Java公众号**/

public class FixedCapacityStack<Item> {


    private Item[] data;

    private int N;


    @SuppressWarnings("unchecked")

    public FixedCapacityStack(int capacity) {

        data = (Item[]) new Object[capacity]; //work around

    }


    public boolean isEmpty() {

        return N == 0;

    }/**来 自 NowJava.com**/

  

    public void push(Item item) {

        data[N++] = item;

    }

    

    public Item pop() {

      Item item = data[--N];

        data[N] = null;

        return item;

    }

    

    public static void main(String[] args) {

        FixedCapacityStack<Integer> numbers = new FixedCapacityStack<Integer>(5);

        numbers.push(22);

        numbers.pu
展开阅读全文