Sam Kohnson
Sam Kohnson

Reputation: 115

copying an array to the same array

So I have a array with elements [10] that I add from the top of the array so something like this

["","","","","",5,4,3,2,1]

and when I remove a element I wanted to shift up ones below it to take its place

["","","","","",5,3,2,1]

public void moveUP(int location, int Arraysize) {

    System.arraycopy(vehicle, 0, vehicle, 0, location + 1);
}

I tried using the array copy but when I check the debugger the elements are remaining the same.

edit: forgot to mention that location was the element I planned on removing.

Upvotes: 0

Views: 99

Answers (3)

cangoektas
cangoektas

Reputation: 719

I think this is not possible with one call of System.arraycopy. You can shift all elements of an array to the left or to the right with arraycopy (assuming you have enough space) but either way there will be old leftover elements which have only been copied and not set to 0/null. Example:

int[] test = new int[] {0,0,7,7};
System.arraycopy(test, 2, test, 1, 2); // this will shift all elements 
                                       // starting at position 2 to position 1
// but test now looks like this = [0,7,7,7]

So the last 7 is still there. A solution for this could look something like this:

int[] newArr = new int[oldArr.length];
System.arraycopy(oldArr, 0, newArr, 0, posToBeDeleted);
System.arraycopy(oldArr, posToBeDeleted+1, newArr, posToBeDeleted, elemsRemaining);
oldArr = newArr;

Upvotes: 0

Verim
Verim

Reputation: 1125

I think the correct function should look like this:

public void moveUP(int location, int arraysize){
    System.arraycopy(vehicle, 0, vehicle, 1, location-1);
    vehicle[0] = "";
}

This moves every element from 0 to location-1 one place to end, so its after the copy on position 1....location (so the element on position is deleted)

Upvotes: 1

The destPos argument is the fourth one, not fifth one. Your call should probably look like System.arraycopy(vehicle, 0, vehicle, location, Arraysize), assuming you want to shift from 0 to location, and there are Arraysize elements in your array.

Upvotes: 0

Related Questions