Java-反转ArrayList或对象列表的单一通用方法 [英] Java - a single generic method to reverse ArrayList or List of objects
问题描述
我已经看到有一种非常方便的方法来反转 ArrayList
在这里使用 Collections.reverse()
方法,但是我需要对几种类型的原始对象(例如至少 ArrayList
和 List
的自定义对象。所以 Collections
不能为扩展使用单个方法挽救生命。
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.
到目前为止,我设法使stg工作(请参见下面的代码),但是我必须写两次:一次用于ArrayList,一次用于List。我将它们命名为相同的名称,因此用法非常方便,但是某些..优化将更加方便:-)。
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;
}
推荐答案
集合。反向
使用 List<?>
。 ArrayList
实现 List
-您可以在 ArrayList
或任何 List
实现。除非我误解了这个问题,否则您的工作似乎完全没有必要。
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.
这篇关于Java-反转ArrayList或对象列表的单一通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!