Java Reference
In-Depth Information
not compile because FileNotFoundException is not a parent class of IOException . The
compiler error looks like the following output:
WildcardDemo.java:8: incompatible types
found : java.util.ArrayList<java.io.FileNotFoundException>
required: java.util.ArrayList<? super java.io.IOException>
ArrayList<? super IOException> alist3 =
new ArrayList<FileNotFoundException>();
Let's look at an example of a method that declares a lower-bound generic. The
following showExceptions method prints a List of objects whose type is List<? super
IOException> :
public static void showExceptions(List<? super IOException> list) {
for(Object e : list) {
System.out.println(e.toString());
}
}
The following statements create an ArrayList<Exception> , a valid argument for
showExceptions . Study the code and determine if it compiles and what the output is:
30. ArrayList<? super IOException> exceptions =
new ArrayList<Exception>();
31. IOException e1 = new IOException(“Problem 1”);
32. IOException e2 = new IOException(“Problem 2”);
33. FileNotFoundException e3 = new FileNotFoundException(“Problem 3”);
34. exceptions.add(e1);
35. exceptions.add(e2);
36. exceptions.add(e3);
37. showExceptions(exceptions);
The reference exceptions on line 30 is of type ArrayList<? super IOException> and
the object it refers to is an ArrayList<Exception> . Therefore, line 30 is valid because
Exception is the parent of IOException . Lines 31-36 add three Exception objects
to the ArrayList . Line 37 passes exceptions to showExceptions . The argument of
showExceptions is List<? super IOException> , so passing in an ArrayList<? super
IOException> is also valid. The code compiles and runs fi ne, and the output is
java.io.IOException: Problem 1
java.io.IOException: Problem 2
java.io.FileNotFoundException: Problem 3
Search WWH ::




Custom Search