gpt4 book ai didi

java - 双面队列问题

转载 作者:行者123 更新时间:2023-12-01 16:39:57 25 4
gpt4 key购买 nike

我正在尝试运行此方法以将通用值(EltType)插入双面队列(deque)中,但我不断收到我无法弄清楚的 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)

最佳答案

除了关于 <= 的其他答案,您将临时数组大小设置为 CAPACITY+1,它始终为 11。您的意思可能是:

tempArray = (EltType[]) new Object[capacity+1];

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com