【问题标题】:Beginner Stacks, OutofBoundsException Java初学者堆栈,OutofBoundsException Java
【发布时间】:2014-05-05 11:24:18
【问题描述】:

嘿,我有一个问题,为什么我的程序会抛出 ArrayIndextOutofBounds 异常 我在互联网上到处查看并浏览了代码,但我知道我遗漏了一些东西。 这是我第一个实现堆栈的程序,坦率地说,我并不是 100% 了解我正在做的事情。

我认为问题出在我的 isEmpty 方法上,但无法准确看出我做错了什么。必须有一种更简单的方法来测试堆栈是否为空? 任何帮助将不胜感激。

PS:我的测试堆栈设置正确吗?

这是我的代码:

import java.util.Arrays;

public class ArrayStack<T> implements StackADT<T> { private final static int DEFAULT_CAPACITY = 100;

private int top;
private T[] stack;
private int emptyCount = 0;

//Creates an empty stack using the default capacity.
public ArrayStack()
{
    this(DEFAULT_CAPACITY);
}

//Creates an empty stack using the specified capacity.
@SuppressWarnings("unchecked")
public ArrayStack(int initialCapacity)
{
    top = 0;
    stack = (T[])(new Object[initialCapacity]);
}

/* Adds the specified element to the top of this stack, expanding
the capacity of the array if necessary.*/
public void push(T element)
{
    if (size() == stack.length)
        expandCapacity();

    stack[top] = element;
    top++;
}

/*Creates a new array to store the contents of this stack with
twice the capacity of the old one.*/
private void expandCapacity()
{
    stack = Arrays.copyOf(stack, stack.length * 2);
}

/*Removes the element at the top of this stack and returns a
reference to it.*/
public T pop() throws EmptyCollectionException
{
    if (isEmpty())
        throw new EmptyCollectionException("stack");

    top--;
    T result = stack[top];
    stack[top] = null;

    return result;
}

/*Returns a reference to the element at the top of this stack.
The element is not removed from the stack.*/
public T peek() throws EmptyCollectionException
{
    if (isEmpty())
        throw new EmptyCollectionException("stack");

    return stack[top-1];
}

//Returns true if this stack is empty and false otherwise.
public boolean isEmpty()
{
    for(int i = 0; i < stack.length; i++)
    {
        if (stack[i] == null)
        emptyCount++;
    }
    if(emptyCount != stack.length-1)
        return false;
    else
        return true;

}

//Returns the number of elements in this stack.
public int size()
{
    return stack.length;
}

//Returns a string representation of this stack.
public String toString()
{
    String output = "The element at the top of the stack is: " + peek() + "\n" +
        "It is " + isEmpty() + " that the stack is empty." + "\n" +
            "The number of elements in the stack is: " + size();
    return output;
}
}

还有我的驱动程序/测试文件:

public class StackTest
{
    public static void main(String[] args) throws EmptyCollectionException
    {
        ArrayStack stack = new ArrayStack(5);
        System.out.println(stack);
    }
}

【问题讨论】:

    标签: java arrays generics stack indexoutofboundsexception


    【解决方案1】:

    您的问题是isEmpty() 方法。 top==0时栈为空,与栈元素的内容无关。

    【讨论】:

    • 我已将代码更改为 top == 0 但是,现在我收到不兼容的类型错误,Type T 和 int 不兼容
    【解决方案2】:

    我猜问题出在 peek() 函数而不是 isEmpty() 在 peek() 你使用 stack[top - 1] 这意味着 stack[-1] 另一个问题是 size() 函数……它不返回堆栈中的元素数量,而是返回堆栈的长度。

    【讨论】:

      【解决方案3】:

      问题出在您的 isEmpty() 方法中。尝试做这样的事情

      public boolean isEmpty()
      {
          for (T element : stack)
          {
              if(element != null)
              {
                  return false;
              }
          }
      
          return true;
      }
      

      另一个问题是你的 size 函数,它总是返回数组的长度。

      尝试做这样的事情:

      public int size()
      {
          int count = 0;
          for (T element : stack)
          {
              if(element != null)
                  count++;
          }
      
          return count;
      }
      

      【讨论】:

      • 非常感谢您的帮助,程序现在运行良好!
      • isEmpty() 函数很好,效率不高但仍然有效...问题出在 peek() 函数中
      • peck()函数没有问题。我已经测试过了,它工作正常
      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 2014-11-12
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      相关资源
      最近更新 更多