问题
I am trying to run this method to insert a generic value (EltType) into an double sided queue(deque), but I keep getting an outOfBoundsException that I just can't figure out. Would anyone please be able to help me with this ? This is just an extract from the code, but I think it can be pieced together from this!
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;
}
Error :
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)
回答1:
for (int i=0;i<=deque.length;i++) {
should be changed into
for (int i=0;i<deque.length;i++) {
You used a "smaller than or equal", but the last item of an array has (length-1) for index.
回答2:
In addition to the other answers about <=
, you're setting the temp array size to CAPACITY+1, which will always be 11. You probably meant:
tempArray = (EltType[]) new Object[capacity+1];
回答3:
As other posters have mentioned, you have an "off-by-one" error, also called a fencepost error.
Also, you can simplify your isEmpty()
method as follows:
public boolean isEmpty() {
return end == 0;
}
I'm assuming that when end
is zero, then that means there are no elements in the deque. You shouldn't check deque.length
, because that simply tells you how many elements the array can store, not how many are currently in the array.
回答4:
Where are you changing your capacity? It probably shouldn't be a constant. The size is also not being incremented when you add.
回答5:
for (int i=0;i<=deque.length;i++) {
You should use <
, not <=
.
回答6:
B/c you are using <=, you go up to deque.length which is 10, but deque only has 9 indices.
for (int i=0;i<=deque.length;i++) {
tempArray[i+1] = deque[i];
}
Use < instead in the for loop
回答7:
As a side note:
public boolean isEmpty() {
boolean returned;
if (deque.length < 1) {
returned = true;
}else {
returned = false;
}
return returned;
}
Doesn't:
public boolean isEmpty() {
deque.length < 1
}
look simplier?
来源:https://stackoverflow.com/questions/4927026/double-sided-queue-problem