Arraylist swap elements

qvd picture qvd · Apr 12, 2013 · Viewed 147.8k times · Source

How do I swap the the first and last elements of an ArrayList? I know how to swap the elements of an array: setting a temporary value to store the first element, letting the first element equal the last element, then letting the last element equal the stored first element.

int a = values[0];
int n = values.length;
values[0] = values[n-1];
values[n-1] = a;

So for an ArrayList<String> would it be like this?

String a = words.get(0);
int n = words.size();
words.get(0) = words.get(n-1);
words.get(n-1) = a

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Apr 12, 2013

You can use Collections.swap(List<?> list, int i, int j);