Lets say I have the array:
int[] taco = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
How can I move an element based its index to the front? Example:
Move element taco[5] to the front should produce this:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
// becomes
{5, 0, 1, 2, 3, 4, 6, 7, 8, 9}
EDIT:
Does it make a difference if the ints are instead objects?
intvariabletaco[0], in this case)It does not make any difference if it’s an array of
intvalues, or objects. The algorithm is the same. Since an array ofObjectreferences would literally be an array of 32-bit or 64-bit memory references, you’re effectively still copying integers around.Here is code that would do it – there are several ways to do this, but this is the basic idea:
0, then nothing winds up being moved.You could also take a look at the source code of
arraycopyif you’re curious, via the OpenJDK project.