简体   繁体   中英

Java - a single generic method to reverse ArrayList or List of objects

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;
}

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.

Collections.reverse() reverses any instance of List . So yes, you can use Collections.reverse() on anArrayList , 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);  
  }
}

Below generic method should reverse any type of List or ArrayList

public static <T> List<T> reverseList(List<T> listToReverse){
    List<T> reverseList = new ArrayList<>(listToReverse);
    Collections.reverse(reverseList);
    return reverseList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM