Mr. Nicky Mr. Nicky - 1 year ago 70
Java Question

Reverse a generic collection in Java

I've got the following task:

"Declare a method, expecting a Collection and reverse it in your method. Return the same collection given, do not return a new collection!.

static <T> void reverse (Collection<T> collection)

Do not try to use Collections.reverse. It works only for a List, and not for collections"

My initial idea was something of the following:

public static <T> void reverse(Collection<T> collection){

int size = collection.size();
Iterator<T> iter = collection.iterator();
Iterator<T> iter2 = collection.iterator();

for (int i = 0; i < size / 2; i++) {

But I keep getting weird exceptions:

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(
at java.util.AbstractList.add(
at ReverseCollection.reverse(
at ReverseCollection.main(

Any idea how this should be done?

Answer Source

What you want to do cannot be done, since many Collection classes (for example HashSet) do not let you control the order.

The problem is that the order of elements in a general Collection is not defined. For example, think of a Set, which does not guarantee the order of the elements. Since there is no ordering, it is hard to define what the reverse order is.