2

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.

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

            if (j == array.length - 1) { 
                break;
            } 
        }
        array[i] = s;
Gregg1989
  • 675
  • 6
  • 14
  • 24

3 Answers3

3

Try this

public void insert(int i, String s) {

    String[] newArr = new String[array.length + 1];
    for (int j = 0; j < array.length; j++) { 
        if(j < i){
           newArr[j] = array[j];
        } else if(j == i){ // '==' insted of '='
           newArr[j] = s;
        } else {
           newArr[j+1] = array[i];
        }
    }

    array = newArr;
}
Dimitar Pavlov
  • 300
  • 3
  • 10
  • this will be a big performance loss as on each insert a new array is being allocated. A better option would be to use ArrayList and not reinvent the wheel. – Narendra Pathai Nov 13 '13 at 14:37
  • Yes I know but "P.S. I don't want to use the built-in ArrayList library, which automatically does it for you. " – Dimitar Pavlov Nov 13 '13 at 14:41
1

Well, arrays are not dynamic, so if you have an array that has size 3 you cannot add anything to it unless you create a new array that has size of oldArray.length+1 and then populate it with new data.

Lucas
  • 3,181
  • 4
  • 26
  • 45
0
public static int[] addAtIndex(int[] a, int index, int value) {
 int[] newArr = new int[a.length + 1];
 int temp;
 for (int j = 0; j < a.length + 1; j++) {
  if (j < index) {
   newArr[j] = a[j];
  } else if (j == index) {
   //copy value at index to temp so that value added at specific index can be shifted right
   temp = a[j];
   newArr[j] = value;
   newArr[j + 1] = temp;
  } else {
   newArr[j] = a[index];
   index++;
  }
 }
 return newArr;
}