after searched for a while I still couldn’t find any answer to my question, even there’s couple of Generics related topic, so here you go:
ArrayList<? super IOException> list = new ArrayList<Exception>();
list.add(new FileNotFoundException("this is ok."));
list.add(new IOException("This is ok"));
list.add(new ClassCastException("compile err"));//why compile err?
list.add(new Exception("compile err"));//why compile err?
Why last two line doesn’t compile? Especially the last line. I’ve been doing quite a bit test on this topic but still couldn’t catch the logic.
Thanks.
ArrayList<? super IOException>could be any of the following (since there is a wild card):The code needs to work with all four possibilities.
But if it is an
ArrayList<IOException>, you cannot put in aClassCastExceptionor anException, hence the compile errors.No, FileNotFoundException is fine, because it extends IOException and you can put it in all of the four types of lists.
Note that for historical reasons, arrays do not get the same strict type checking, you can compile the following (and then get an array store exception at runtime):