Sam
Sam

Reputation: 93

Shift elements to right in a array to add a new element in java

Im trying to shift some elements of the array to get space for a new element in the index chosen, but my array is cloning the element after the index till the end of the array

public void insertAtRank(int r, Object o) {
    for(int i = r+1 ; i < arrayVetor.length; i++ ){
        arrayVetor[i] = arrayVetor[i-1];
    }
    this.arrayVetor[r] = o;
}
arrayVetor.insertAtRank(0, "1");
arrayVetor.insertAtRank(1, "2");
arrayVetor.insertAtRank(2, "3");
arrayVetor.insertAtRank(3, "4");
arrayVetor.insertAtRank(2, "5");

the output: [1, 2, 5, 3, 3, 3, 3, 3, 3, 3]

what i want: [1, 2, 5, 3, 4, null, null, null, null, null]

Upvotes: 0

Views: 107

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

Think about what happens in that loop for, say, r == 0:

  • The element at arrayVetor[0] is copied to arrayVetor[1]
  • The element at arrayVetor[1] is copied to arrayVetor[2]
  • The element at arrayVetor[2] is copied to arrayVetor[3]
  • ...
  • The element at arrayVetor[8] is copied to arrayVetor[9].

So you end up copying (well, assigning) the value at arrayVetor[0] to all elements in the array.

What you actually want to be doing is:

  • Copying the element at arrayVetor[8] to arrayVetor[9]
  • Copying the element at arrayVetor[7] to arrayVetor[8]
  • Copying the element at arrayVetor[6] to arrayVetor[7]
  • ...
  • Copying the element at arrayVetor[0] to arrayVetor[1]

And then assigning the new value to arrayVetor[0].

Upvotes: 1

Related Questions