I'm doing some exercises on generic programming; is there a way to take a class that implements List and return a reversed version of that same class? It seems this should be feasible as this, at least taking the term at face value, is "generic programming" writ large.
Maybe by performing an in-place reversal? I also considered Collections.reverse(), but it's a void method.
Here is my attempt and demo:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Arrays;
public class ReverseDemo {
public static <T> List<T> reverse(List<T> list) {
List<T> reversed = new ArrayList<T>();
for (int i = list.size() - 1; i >= 0; i--) {
reversed.add(list.get(i));
}
return reversed;
}
public static void main(String[] args) {
LinkedList<Integer> linkedInt = new LinkedList<Integer>();
ArrayList<Double> arrayDouble = new ArrayList<Double>();
for (int k = 0; k < 10; k++) {
double doubleNum = 10*Math.random();
int intNum = (int) (10*Math.random());
linkedInt.add(intNum);
arrayDouble.add(doubleNum);
}
// LinkedList<Integer> demo
System.out.println(Arrays.toString(linkedInt.toArray()));
System.out.println(Arrays.toString(reverse(linkedInt).toArray()));
System.out.println(reverse(linkedInt) instanceof LinkedList<?>); // false
// ArrayList<Double> demo
System.out.println(Arrays.toString(arrayDouble.toArray()));
System.out.println(Arrays.toString(reverse(arrayDouble).toArray()));
System.out.println(reverse(arrayDouble) instanceof ArrayList<?>); // true
}
}
Incidentally this is my first post here, does anyone know the best way to post code directly from Eclipse while preserving the spacing and indentation therefrom? I've used the four-spaces method specified here, but it's a bit inconsistent.
The Guava library has a nice, non-destructive solution to the problem. See Lists.reverse(List).
They define a suite of ReverseList
classes that wrap the input List
. From there, it's just a matter of translating all of calls (although "just" might be understating things a bit).
If you want to preserve the original list, you can try using:
originalList.getClass().newInstance()
That is not a 100% correct solution as it may throw if the original class does not have a default constructor. However, most collections have default constructors that create empty instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With