Java: moving items in array

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

    Any particular reason you're not using a List instead of String[]? It'll make these type of operations easier. With an ArrayList, all you need is:

    list.add(3, list.remove(list.size() - 1));
    

    Or even shorter if you used a LinkedList:

    list.add(3, list.removeLast());
    

    Here's a more complete example based on yours:

    LinkedList list = new LinkedList();
    list.addAll(Arrays.asList("a", "b", "c", "d", "e"));
    list.add(3, list.removeLast());
    System.out.println(list); // prints "[a, b, c, e, d]"
    

提交回复
热议问题