问题
I have seen that there is a very convenient way to reverse ArrayList like here using Collections.reverse() method, but I need to achieve such a reverse operation for several types of primitive objects, like at least ArrayList and List of my custom objects. So Collections can't save my life for an extended usage of a single method.
So far I managed to get stg working (See code below) but I have to write it twice: once for ArrayList and once for List. I named them both the same so usage is very convenient, but some .. optimization would be even more convenient :-).
How to commonalize these 2 methods into a single (real) generic one ?
Thx
/**
* Generic Reverse Method for ARRAYLIST using Iterator
* @param ArrayList<Obj_item> notReversed
* @return ArrayList<Obj_item> reversed
*/
@SuppressWarnings("unchecked")
public static <Obj_item> ArrayList<Obj_item> GenReverseArrayByIterator(ArrayList<Obj_item> mylist) {
// ^^^^^^^^^^^^^^^^^^ how to make this generic ?
// Instanciate
ArrayList<Obj_item> tmp = new ArrayList<Obj_item>();
ArrayList<Obj_item> reversed = new ArrayList<Obj_item>();
// Copy original list
tmp = mylist;
// Generate an iterator, starting right after the last element.
@SuppressWarnings("rawtypes")
ListIterator myIterator = tmp.listIterator(tmp.size());
// Iterate in reverse direction
while (myIterator .hasPrevious()) {
reversed.add((Obj_item) myIterator.previous());
}
return reversed;
}
回答1:
Collections.reverse takes a List<?>. ArrayList implements List - you can use that method on an ArrayList or any List implementation. What you're doing seems entirely unnecessary, unless I misunderstood the question.
回答2:
Collections.reverse() reverses any instance of List. so yes, you can use Collections.reverse() on an ArrayList, or any instance of List.
but anyway, here's how'd you write it by hand if you wanted,
static void reverse(List<?> list) {
for (int i = 0, l = list.size() / 2, j = list.size() - 1; i < l; i++, j--) {
Object tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
}
来源:https://stackoverflow.com/questions/12397267/java-a-single-generic-method-to-reverse-arraylist-or-list-of-objects