Saturday, August 28, 2010

Generics and ArrayList

Courtesy of Sun Web Learning Center


1. import java.util.*;
2. class SubGen {
3.   public static void main(String [] args) {
4.     // insert code here
5.   }
6. }
7. class Alpha { }
8. class Beta extends Alpha { }
9. class Gamma extends Beta { }

And the four code fragments:
s1.    ArrayList<? extends Alpha> list1 = new ArrayList<Gamma>();
s2.    ArrayList<Alpha> list2 = new ArrayList<? extends Alpha>();
s3.    ArrayList<? extends Alpha> list3 = new ArrayList<? extends Beta>();
s4.    ArrayList<? extends Beta> list4 = new ArrayList<Gamma>();  ArrayList<? extends Alpha> list5 = list4;

Which, inserted independently at line 4, allow the code to compile?

A Only s1
B Only s3
C Only s1 and s3
D Only s1 and s4
E Only s1, s3, and s4
F All of the codes will compile.

D is correct. Options s1 and s4 use valid syntax. Options s2 and s3 will generate the following compiler error, "required: class or interface without bounds"

No comments:

Post a Comment