创建固定大小的堆栈 [英] Creating a fixed-size Stack

查看:137
本文介绍了创建固定大小的堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中创建一个Stack,但要修改大小。例如,创建一个新的Stack,将大小设置为10,然后当我将项目推送到堆栈时它会填满,当它填充到10时,堆栈中的最后一个项目被推下(删除)。我想使用Stack,因为它使用LIFO并且非常符合我的需求。

I want to create a Stack in Java, but fix the size. For example, create a new Stack, set the size to 10, then as I push items to the stack it fills up and when it fills up to ten, the last item in the stack is pushed off (removed). I want to use Stack because it uses LIFO and fits my needs very well.

但是Stack从Vector继承的setSize()方法似乎并没有实际限制Stack的大小。我想我错过了一些关于Stacks如何工作的东西,或者Stacks并不意味着受到限制所以这是不可能的。请教育我!

But the setSize() method that Stack inherits from Vector doesn't seem to actually limit the size of the Stack. I think I am missing something about how Stacks work, or maybe Stacks weren't meant to be constrained so it is impossible. Please educate me!

推荐答案

你可以像这样创建一个非常简单的堆栈:

You can create a very simple stack like this:

public class FixedStack<T>
{
    private T[] stack;
    private int size;
    private int top;

    public FixedStack<T>(int size)
    {
        this.stack = (T[]) new Object[size];
        this.top = -1;
        this.size = size;
    }

    public void push(T obj)
    {
        if (top >= size)
            throw new IndexOutOfBoundsException("Stack size = " + size);
        stack[++top] = obj;
    }

    public T pop()
    {
        if (top < 0) throw new IndexOutOfBoundsException();
        T obj = stack[top--];
        stack[top + 1] = null;
        return obj;
    }

    public int size()
    {
        return size;
    }

    public int elements()
    {
        return top + 1;
    }
}

这篇关于创建固定大小的堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆