Reverse a generic collection in Java
<p>I've got the following task:</p>

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

<pre><code>static &lt;T&gt; void  reverse (Collection&lt;T&gt; collection)
</code></pre>

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

<p>My initial idea was something of the following:</p>

<pre><code>public static &lt;T&gt; void reverse(Collection&lt;T&gt; collection){

    int size = collection.size();
    Iterator&lt;T&gt; iter = collection.iterator();
    Iterator&lt;T&gt; iter2 = collection.iterator();

    for (int i = 0; i &lt; size / 2; i++) {
        collection.add(iter.next());
        iter2.remove();
    }
}
</code></pre>

<p>But I keep getting weird exceptions:</p>

<pre><code>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)
</code></pre>

<p>Any idea how this should be done?</p>