0
public static void wildCard2(List<? super Base> lst){
    for (int i=0; i<2; i++){
        System.out.println(lst.get(i));
    }
    lst.add(new Base());

}

As shown in the code above, I have a class called Base. Can anyone explain why this fails at RunTime and throws UnsupportedOperationException ?

phoenix
  • 3,069
  • 3
  • 22
  • 29

2 Answers2

1

The add(E e) method defined on the List<E> interface is specified as an optional operation.

If you're getting an UnsupportedOperationException at runtime, this means that the List implementation that you're using does not support this operation.

It might be an unmodifiable type created by calling Collections.unmodifiableList(), an instance of a Guava ImmutableList, or something else entirely. Check the runtime type to find out:

System.out.println(lst.getClass().getName());
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

You cannot .add() from such a List, you can create a copy of the list to a known-modifiable implementation like ArrayList.

Abdelhak
  • 8,299
  • 4
  • 22
  • 36