Ramesh KC Ramesh KC - 1 month ago 13
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
wildcard
.

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

public static void copyFirstToEnd2(List<?> items) {
System.out.println(items);
copyFirstToEndHelper(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);
items.add(item);
}

}


What I am getting is
java.lang.UnsupportedOperationException
.

Answer

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