Java: moving items in array

前端 未结 6 1667
囚心锁ツ
囚心锁ツ 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:12

    Here's a more efficient and concise solution, relying on the natively implemented System.arraycopy:

    public static void moveLastup(String[] arr, int pos) {
        String last = arr[arr.length-1];
    
        // Copy sub-array starting at pos to pos+1
        System.arraycopy(arr, pos, arr, pos + 1, arr.length - pos - 1);
    
        arr[pos] = last;
    }
    

    And some test code:

    public static void main(String[] args) {
        String[] test = { "one", "two", "three", "four", "five" };
    
        // Move "five" to index 2
        moveLastup(test, 2);
    
        // [one, two, five, three, four]
        System.out.println(Arrays.toString(test));
    }
    

    Regarding your edit: You're working with and modifying the original array. If you want to "start over" in each moveLastup you need to work on a copy. This snippet prints what you want:

    String[] list = { "a", "b", "c", "d", "e" };
    
    for (int pos = 0; pos < list.length; pos++) {
        String[] tmpCopy = list.clone();
        moveLastup(tmpCopy, pos);
        showList(tmpCopy);
    }
    

    Output:

    [e, a, b, c, d]
    [a,e, b, c, d]
    [a, b,e, c, d]
    [a, b, c,e, d]
    [a, b, c, d,e]

提交回复
热议问题