hornetbzz
hornetbzz

Reputation: 9357

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

Upvotes: 0

Views: 6461

Answers (3)

Anoop Pednekar
Anoop Pednekar

Reputation: 9

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

Upvotes: 0

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

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

Upvotes: 4

Paul Bellora
Paul Bellora

Reputation: 55223

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.

Upvotes: 8

Related Questions