我正在尝试运行此方法以将通用值(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)

最佳答案

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


应该变成

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


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

关于java - 双面排队问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4927026/

10-10 03:47