Here is my array:
int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Let’s say I want to move myArray[3] (it could be any element) and myArray[6] (same with this one) to the front of the array while rearranging the back, how can I do this? Example:
This:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Into this:
{3, 6, 0, 1, 2, 4, 5, 7, 8, 9}
To move index
xto the front, you need to:x0tox - 1up one index, e.g. withSystem.arrayCopy0to be the value you remembered in the first stepFor example:
Note that
System.arraycopyhandles the copying appropriately:Your original example mentioned two elements – while you could potentially do all of this more efficiently knowing both elements in advance, it would be far, far simpler to model this as two
moveToHeadcalls. You need to take care about the ordering – for example, if you want to move index6to the head first, you’ll need to then move index 4 rather than index 3, to take account of the first move.