How can I move an element of an ArrayList to the last element?

1

I wonder if there is any method to perform the operation, without being manually concatenated. Example of what you intended:

[1,2,3,4] - > [1,3,4,2]

    
asked by anonymous 14.04.2017 / 11:31

1 answer

2

Yes, you have to change the elements.

public static <E> void swap(List<E> list, int idx1, int idx2){
    E aux = list.get(idx1);
    list.set(idx1, list.get(idx2));
    list.set(idx2, aux);
}

To change the 2 with the 4 you would write

swap(list, 1, list.size() - 1);
    
14.04.2017 / 12:26