Reputation: 93
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
Reputation: 140309
Think about what happens in that loop for, say, r == 0
:
arrayVetor[0]
is copied to arrayVetor[1]
arrayVetor[1]
is copied to arrayVetor[2]
arrayVetor[2]
is copied to arrayVetor[3]
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:
arrayVetor[8]
to arrayVetor[9]
arrayVetor[7]
to arrayVetor[8]
arrayVetor[6]
to arrayVetor[7]
arrayVetor[0]
to arrayVetor[1]
And then assigning the new value to arrayVetor[0]
.
Upvotes: 1