user1062898
user1062898

Reputation: 109

Java - Add Element to an Array

Looked around, couldn't find any similar questions in java..

Basically I need to add a number to an int array in a specific position index

I can only use Arrays, no ArrayLists

Here is what I have so far, and I know why it doesn't work, but I can't figure out how to fix that problem of overwriting, which I don't want it to do.

The task is a non-overwriting insert. e.g. the final result would be

[1 2 1337 3 4 5 6 7 8]

Here is the code snippet:

public void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8};
array = add(array, 2, 1337);
for(int i : array)
    System.out.print(i + " ");
}


public int[] add(int[] myArray, int pos, int n)
{
    for (int i = pos; i<myArray.length-1; i++){
        myArray[i] = myArray[i+1];
    }
    myArray[pos] = n;
    return myArray;
}

Upvotes: 1

Views: 46667

Answers (2)

Bohemian
Bohemian

Reputation: 424983

Your problem is this loop:

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

It is writing i+1 into i - ie it moves element down - you need it to move them up. In order to move up, you need to iterate down (otherwise you overwrite what you just wrote).
Try this:

for (int i = myArray.length - 1; i > pos; i--) {
    myArray[i] = myArray[i - 1];
}

Note that this will make room for the insertion at pos by losing (overwriting) the last element.

Upvotes: 2

Pritom
Pritom

Reputation: 1333

myArray[i+1] = myArray[i];

Maybe this will help you.

Upvotes: 0

Related Questions