How can I move an element from an Arraylist to the last element ?

Asked

Viewed 393 times

1

I would like to know if there is any method to perform the operation, other than to concatenate manually. Example of what you wanted:

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

1 answer

2


Yes, it is to exchange 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 exchange the 2 with the 4 Voce would write

swap(list, 1, list.size() - 1);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.