I'm just preparing for the Oracle Certified Professional Java SE 8 exam and I have some problems with generics and wildcards. I pretty well know that the code I'm submitting doesn't make a lot of sense and would not be written this way in 'real life' but it's an exercise for me.
- First line: ((ArrayList<Exception>)exceptions).add(new Exception());compiles
How can this one compile? exceptions is an ArrayList containing FileNotFoundException objects (or child classes). How can I add an Exception to an ArrayList supposed to hold only elements that are a subclass of FileNotFoundException? Without the cast the line doesn't compile. But even with the cast, exceptions should still be unable to contain superclasses of FileNotFoundException. Am I right or do I misunderstand something?
- Line 2: ((ArrayList<IOException>)exceptions).add(new Exception());doesn't compile
The difference between line 1 and 2 is that I now cast to an IOException, not an Exception. Exception is too 'wide' to be cast to IOException, sure. This should be the reason this line (same for line 5) does not compile. Right?
- Line 3: ((ArrayList<IOException>)exceptions).add(new IOException());
Compiles and I don't really understand why. Basically the same question as for line 1. IOException is superclass to FileNotFoundException, how can I put a member of a superclass in this ArrayList?
- Line 4: ((ArrayList<Exception>)exceptions).add(new FileNotFoundException());
Compiles. Same problem as Line 1.
package javaapplication;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.io.FileNotFoundException;
public static void main(String[] args) {
  List<? extends Throwable> exceptions = new ArrayList<FileNotFoundException>();
  ((ArrayList<Exception>)exceptions).add(new Exception());//1
  ((ArrayList<IOException>)exceptions).add(new Exception());//2,does not compile
  ((ArrayList<IOException>)exceptions).add(new IOException());//3
  ((ArrayList<Exception>)exceptions).add(new FileNotFoundException());//4
  ((ArrayList<FileNotFoundException>)exceptions).add(new
  Exception());//5,does not compile
}
 
     
    