Why does the first line work, but the second one doesn't?
Collection<Class<? extends Throwable>> exs =
new ArrayList<Class<? extends Throwable>>() {{ add(MyOwnException.class); }};
Collection<Class<? extends Throwable>> exs = Arrays.asList(MyOwnException.class);
Core Java bootcamp program with Hands on practiceA generic class is not allowed to extend the Throwable class directly or indirectly. A method is not allowed to catch an instance of a type parameter.
Correct Option: C. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.
super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .
The reason it's an error is that java is inferring the wrong type, but you can make it compile, without casting, by specifying the type in the call to the typed method Arrays.asList()
:
Collection<Class<? extends Throwable>> exs
= Arrays.<Class<? extends Throwable>>asList(Exception.class); // compiles
Without specifying the type, java infers the element type of the collection to be Class<Exception>
, which is not assignable to Collection<Class<? extends Throwable>>
.
Remember with generics that if B
extends A
, List<B>
does not extend List<A>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With