javaandroidarraysreversegeneric-programming

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

Solution

  • 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.