Ramesh KC Ramesh KC - 1 year ago 84
Java Question

Java generic unbounded wildcard

I tried to copy the 0th element of a general list to the end of the list.

public static void copyFirstToEnd2(List<?> items) {
items.add(items.get(0)); //compiler error

Compiler error
arises because I am trying to add to a List whose type involves the
extends wildcard

I wrote the helper method to capture

public class CopyFirstToEnd {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1, 4, 5);

public static void copyFirstToEnd2(List<?> items) {

* write a helper method that capture the wildcard
* @param items
* @return
private static <T> void copyFirstToEndHelper(List<T> items)
T item = items.get(0);


What I am getting is

Answer Source

You are getting UnsupportedOperationException because you didn't carefully read the documentation about Arrays.asList:

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

You need to create a real list from the array, as with:

List<Integer> list = new ArrayList<>(Arrays.asList(array));

If you dig inside source code you will see that Arrays.asList returns an Arrays.ArrayList<E> which extends AbstractList<E> without overriding add(int index, E object) method, whose default implementation is

void add(int index, E element) {
  throw new UnsupportedOperationException();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download