1

This feature is supposed to add an element at the selected index and push all other in the array elements down. So, for instance, say I have the following array:

[0] = zero
[1] = one
[2] = two

if I add another element at index 0 called NEWZERO, the array has to look like this:

[0] = NEWZERO
[1] = zero 
[2] = one 
[3] = two

but currently I'm getting IndexOutOfBounds exception and it doesn't work, although my array is much bigger than just 3 elements.

P.S. I don't want to use the built-in ArrayList library, which automatically does it for you.

public void insert(int i, String s) {

if (array[i] == null) {
    array[i] = s; //Need to add feature that instantly puts the element at the first available spot on the list.
} else { 
    for (int j = i; j < array.length; j++) { //Can't use >= i
        array[j + 1] = array[j]; //THIS IS WHERE I GET THE ERROR.

        if (j == array.length - 1) { 
            break;
        } 
    }
    array[i] = s;
    extendArray(); //If an element is inserted properly, the array becomes array.length + 1

I'm not getting the error because there's no space in my array. Even if I have an array with 20 elements, and I'm working with just 3, I still get the OutOfBounds error. Here's my extend array method for when a user runs out of array space.

public void extendArray() {
    String[] items2 = new String[items.length + 1];
    for (int j = 0; j < items.length; j++) {
        items2[j] = items[j];
    }
    items = items2;
}
4

5 回答 5

3

When you initializes an array, it exists from 0 to length-1 values.

in your code

for (int j = i; j < array.length; j++) { //Can't use >= i
    array[j + 1] = array[j]; //THIS IS WHERE I GET THE ERROR.

you are trying to store values to array[length] that is out of the bounds of the array.

so change the for to

for (int j = i; j < array.length - 1; j++) { //Can't use >= i
    array[j + 1] = array[j]; 
于 2013-11-13T14:58:14.420 回答
1

试试这个修复

    for (int j = i; j < array.length - 1; j++) { //Can't use >= i
        array[j + 1] = array[j]; 
    }

此外,在插入新元素之前扩展数组的大小是有意义的

于 2013-11-13T15:04:52.293 回答
1

When j reaches array.length-1 in the loop, the array[j + 1] is out of bounds.

To fix this, change the stopping condition (and get rid of the break since it's completely unnecessary):

for (int j = i; j < array.length - 1; j++) {
    array[j + 1] = array[j];
}

Finally, you might want to replace the entire loop with a single call to System.arraycopy().

于 2013-11-13T14:58:57.463 回答
1

你已经有一个j循环中的条件,那么为什么你需要第二个呢?只需使用

for (int j = i; j < array.length - 1; j++) { //Can't use >= i
    array[j + 1] = array[j]; 
}
于 2013-11-13T15:02:41.247 回答
1

当 j 将到达末尾时, j+1 将超出界限并导致 arrayIndexoutOfBoundException

解决方案 :

改变for循环如下

for (int j = i; j < array.length - 1; j++) { //Can't use >= i
array[j + 1] = array[j]; 
}
于 2013-11-13T15:00:48.980 回答