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;
}