Java: moving items in array

前端 未结 6 1662
囚心锁ツ
囚心锁ツ 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);
    
    0 讨论(0)
  • 2020-12-11 13:07

    you could do like this:

    char arr1[]=new arr1[5]; // arr1 contains a,b,c,d,e in order
    char arr2[]=new arr2[5];
    
    for(int i=0;i<arr1.length;i++) {       // copy contents to arr2
       arr2[i]=arr1[i];
    }
    
    for(int i=0,j=4;i<arr1.length;i++) {
      arr2[i]=arr1[4];
      arr2[i+1]=arr1[4];
      arr2[i+2]=arr1[i+1];
      arr2[i+3]=arr1[i+2];
      arr2[i+4]=arr1[i+3];
    }
    
    for(int i=0;arr2.length;i++) {          // Final result
      System.out.println(arr[i]+" ");
    }
    
    0 讨论(0)
  • 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]

    0 讨论(0)
  • 2020-12-11 13:14

    I know the question is about Arrays - don't wanna start a discussion about performance "versus" issues and "why I'm using pure array" - but for those using List I think this might be useful.

    java.util.Collections.rotate method. Yeah, the name is weird, by check it out a part of the javadoc:

    Note that this method can usefully be applied to sublists to move one or more elements within a list while preserving the order of the remaining elements. For example, the following idiom moves the element at index j forward to position k (which must be greater than or equal to j):

        Collections.rotate(list.subList(j, k+1), -1);
    

    To make this concrete, suppose list comprises [a, b, c, d, e]. To move the element at index 1 (b) forward two positions, perform the following invocation:

        Collections.rotate(l.subList(1, 4), -1);
    

    The resulting list is [a, c, d, b, e].

    To move more than one element forward, increase the absolute value of the rotation distance. To move elements backward, use a positive shift distance.

    public void moveElement(List list, int a, int b) {
        // forward or backward
        int direction = a > b ? 1 : -1;
        // always from minor to major to subList
        int minor = a < b ? a : b;
        int major = b > a ? b : a;
        Collections.rotate(list.subList(minor, major + 1), direction);
    }
    
    0 讨论(0)
  • 2020-12-11 13:15

    First of all, in your code you do

    for (int x = stuff.length-1; x > pos; x--)  
    

    where pos is not even defined, I suggest on changing it to position. second of all, change the "list" to "stuff".

    Modified, working code:

    public static void moveLastup(String[] stuff, int position) 
        {
            String y = stuff[stuff.length-1];
    
            for (int x = stuff.length-1; x > position; x--)  
                stuff[x] = stuff[x-1];
    
            stuff[position] = y;
        }
    
    0 讨论(0)
  • 2020-12-11 13:22

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

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

    Or even shorter if you used a LinkedList<String>:

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

    Here's a more complete example based on yours:

    LinkedList<String> list = new LinkedList<String>();
    list.addAll(Arrays.asList("a", "b", "c", "d", "e"));
    list.add(3, list.removeLast());
    System.out.println(list); // prints "[a, b, c, e, d]"
    
    0 讨论(0)
提交回复
热议问题