Java: moving items in array

前端 未结 6 1664
囚心锁ツ
囚心锁ツ 2020-12-11 12:31

I\'m looking to move things around within an Array.

I want to be able to move the last item within the given Array to a spot while moving those in the current locati

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 13:06

    Another short and quick solution based on System.arraycopy:

    System.arraycopy(array, insert, array, insert+1, array.length-insert-1);
    

    The array content is "pushed to the right" from index "insert".

    Here's some demonstration code:

    int[] array = {1,2,3,4,5};
    int insert = 2;
    int last = array[array.length-1];
    System.arraycopy(array, insert, array, insert+1, array.length-insert-1);
    array[insert] = last;
    for (int value:array) System.out.println(value);
    

提交回复
热议问题