0

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.

1
  • You could write a for loop, that will start at location and moves "to the left" to shift the elements "to the right". And on index 0 it inserts an empty string. Commented Feb 12, 2015 at 0:48

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

You might want to add that OP should use just location (instead of location-1) if location is zero based. But good answer.
0

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.

Comments

0

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.