0

I am trying to write an insert function where I give the object I want to add and the index I want to add it at. For some reason it adds the object where I want but changes the number it is replacing to null.

This is homework.

Even a simple hint would help!

public void insert(Integer obj, Integer index) {

 if( index > array.length){
            throw new IllegalArgumentException("The index you entered was out of bounds.");
        }

 for(Integer i = numItems; i > index; i--){
            array[i] = array[i-1];
        }

        array[index] = obj;
        numItems++;         
    }
}

Here is what I am inserting

iv.insert(44, 2);
iv.insert(33, 0);
iv.insert(22, 1);
iv.insert(11, 3);
iv.insert(2 , 2);

Here are my results

33
22
2
null
11
gvlasov
  • 18,638
  • 21
  • 74
  • 110
  • Where does those results come from? And could you explain what you are trying to do? array[index] = obj would do what you described. Also you will get IndexOutOfBoundsException if your index is same as array.length. – FINDarkside Feb 05 '15 at 20:21
  • As a side note, I'd recommend reading this: http://stackoverflow.com/questions/564/what-is-the-difference-between-an-int-and-an-integer-in-java-and-c . You shouldn't be using `Integer` here. – gvlasov Feb 05 '15 at 20:23
  • Why do you use `Integer` instead of `int` – Fallenreaper Feb 05 '15 at 20:23

1 Answers1

0

Each time you insert you are shifting your positions up by one.

So the first one, numItems < 2:

iv.insert(44, 2);
null, null, 44
numItems = 1

Second, same effect again:

iv.insert(33, 0);
33, null, 44
numItems = 2

Third. Now numItems > i so values get shifted before insertion:

iv.insert(22, 1);
33, 22, null, 44
numItems = 3

Fourth, 44 gets added at the end because i == 3 == numItems so no effect:

iv.insert(11, 3);
33, 22, null, 44
numItems = 4

Fifth. 4 > 2, so once more values after 2 get pulled along before insertion:

iv.insert(2 , 2);
33, 22, 2, null, 44
numItems = 5

Not sure what it is exactly you're trying to do, but if you're trying to write an algorithm that shifts up values before overwriting, you should do something like:

for(int j = array.length - 1; array[i] != null && j > i; j--){
    array[j] = array[j-1];
}

But I think for this kind of thing you would be better off with LinkedList in real life.

robert
  • 4,612
  • 2
  • 29
  • 39