and this one doesn't compile (cannot find symbol
symbol : method add(java.lang.Throwable)
location: interface java.util.List<capture#493 of ? super java.lang.Exception>
list.add(new Throwable());):
Can somebody help me to understand what is going on here?
To be more exact, compiler error appears on the 2nd line...
harshvardhan ojha wrote:Exception is Throwable not otherwise. [Exception extends Throwable]. So it looks fine to me.
What do you mean harshvardhan? I know that Exception is subclass of Throwable. But I do not understand why that compiler error apeared on the 2nd line.
It doesn't compile because <? super Exception> is saying you have a List that takes an Exception type or any sub class of Exception but you are then adding a Throwable object to it and Throwable is a super type of Exception not a sub type of it.
Tony Docherty wrote:It doesn't compile because <? super Exception> is saying you have a List that takes an Exception type or any sub class of Exception but you are then adding a Throwable object to it and Throwable is a super type of Exception not a sub type of it.
Hi Tony,
that is not true. 'super' means sperclass is expected. You are talking about the case if 'extends' keyword would be used.
Yes, but the effect of that in a wild card can be slightly counter-intuitive.
A List<? super Exception> will reference a List of Exception or any class it extends. So It could be a List<Exception>, a List<Throwable> or a List<Object>.
Now, the compiler will stop you adding things to the List that it doesn't know are safe. So what can you safely put in all those collections? You can't add a Throwable, because that can't be added to a List<Exception>. The only things that can be safely added to all of them are instances of Exception or subclasses of Exception.