iamcrypticcoder
iamcrypticcoder

Reputation: 2889

Compilation error with lower-bounded wildcard

Consider the following example:

public static void main(String... args) {
    List<? super IOException> exceptions = new ArrayList<Exception>();
    exceptions.add(new Exception());       // Compile Error
    exceptions.add(new IOException());
    exceptions.add(new FileNotFoundException());
}

I know that lower-bounded wildcard accepts all classes which are super class of the given class in the wildcard (here IOException).

Why does compiler showing compilation error in the above case?

Upvotes: 1

Views: 112

Answers (2)

rgettman
rgettman

Reputation: 178303

When you say

lower-bounded wildcard accepts all classes which are super class of the given class in the wildcard

That refers to the parameterized type, not the types of the objects which may be passed to the methods. You can assign a List<Exception> to that variable, or even a List<Object>.

The compiler cannot assume that exceptions can hold an Exception. The actual type parameter could be as specific as the lower bound, in this case, IOException. It is legal to assign a List<IOException> to exceptions, in which case you should not be able to add an Exception. Therefore, the compiler disallows that statement.

If you would like to add an Exception and retain a lower bound, change the bound to:

List<? super Exception> exceptions = new ArrayList<Exception>();

One may of course dispense with the bound entirely:

List<Exception> exceptions = new ArrayList<>();

Upvotes: 1

k_ssb
k_ssb

Reputation: 6272

The reason your code doesn't compile is that the following is legal:

List<? super IOException> exceptions = new ArrayList<IOException>();

Then, exceptions.add(new Exception()) should be disallowed, because an ArrayList<IOException> cannot hold an Exception.

A solution is to use:

// No compiler errors
List<? super Exception> exceptions = new ArrayList<Exception>();
exceptions.add(new Exception());
exceptions.add(new IOException());
exceptions.add(new FileNotFoundException());

Or even:

// Also no compiler errors
List<Exception> exceptions = new ArrayList<>();
exceptions.add(new Exception());
exceptions.add(new IOException());
exceptions.add(new FileNotFoundException());

Upvotes: 0

Related Questions