Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #19 Reverse a list

Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.

import java.util.List;
static <T> void reverse(List<T> x){
	int n = x.size();
	for(int i=0;i<n/2;i++){
		T tmp = x.get(i);
		x.set(i, x.get(n-i-1));
		x.set(n-i-1, tmp);
	}
}

This method works for lists of any element type T .

In case of an odd number of elements, the central element doesn't need to be swapped.
import static java.util.Collections.swap;
int i, m = x.size(), n = m-- / 2;
for (i = 0; i < n; ++i) swap(x, i, m - i);
import static java.util.Collections.reverse;
reverse(x);
import java.util.Collections;
Collections.reverse(x);
import java.util.Collections;
Collections.reverse(x);
with Ada.Containers.Vectors;
use Ada.Containers;
X.Reverse_Elements;

New implementation...
< >
programming-idioms.org