Percy

双面排队问题

java

我正在尝试运行此方法,以将通用值(EltType)插入到双面队列(双端队列)中,但是我一直收到无法确定的outOfBoundsException。有人能帮我这个忙吗?这只是代码的一部分,但我认为可以将其拼凑起来!

  private final int CAPACITY = 10;
  private int capacity;
  private int end;
  private EltType deque[];  

  public ArrayBasedDeque() {
    this.capacity = CAPACITY;
    deque = (EltType[]) (new Object[capacity]);  
  }

    public void insertFirst(EltType first) {
        if(!isEmpty()) {
        EltType[] tempArray;
        tempArray = (EltType[]) new Object[CAPACITY+1];
        for (int i=0;i<=deque.length;i++) {
          tempArray[i+1] = deque[i]; 
        }
        deque = tempArray; 
        }
       deque[0] = first;
      }

  public boolean isEmpty() {
    boolean returned;
    if (deque.length < 1) {
     returned = true; 
    }else {
     returned = false; 
    }
    return returned;
  }

错误:

java.lang.ArrayIndexOutOfBoundsException: 10
    at ArrayBasedDeque.insertFirst(ArrayBasedDeque.java:48)
    at TestABD.main(TestABD.java:5)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)

阅读 405

收藏
2020-12-07

共1个答案

一尘不染

for (int i=0;i<=deque.length;i++) {

应该变成

for (int i=0;i<deque.length;i++) {

您使用了“小于或等于”,但是数组的最后一项的索引为(length-1)。

2020-12-07