Mr. Nicky Mr. Nicky - 4 months ago 30
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++) {
collection.add(iter.next());
iter2.remove();
}
}


But I keep getting weird exceptions:

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ReverseCollection.reverse(ReverseCollection.java:16)
at ReverseCollection.main(ReverseCollection.java:25)


Any idea how this should be done?

Answer

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.