Generics and Subtyping
List<string> ls = new ArrayList<string>(); //1
List<Object> lo = ls; //2 This is not allowed
lo.add(new Object()); // 3
String s = ls.get(0); // 4: attempts to assign an Object to a String!
Wildcards
Becaue the subtyping is not allowed for generics, you cannot pass Collection<String> into the method below.
void printCollection(Collection<Object> c) {
for (Object e : c) {
System.out.println(e);
}}
So what is the supertype of all kinds of collections? It’s written Collection<?> (pronounced “collection of unknown”)
void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}}
Collection<?> c = new ArrayList<String>(); // This is allowed
c.add(new Object()); // compile time error
c.add(new String()); // compile time error
Since we don’t know what the element type of c stands for, we cannot add objects to it.
Bounded Wildcards
public void drawAll(List<? extends Shape> shapes) { ... }
Now drawAll() will accept lists of any subclass of Shape, so we can now call it on a List<Circle> if we want. (Circle is a subclass of Shape)
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // correct
}}
Object[] oa = new Object[100];
Collection<Object> co = new ArrayList<Object>();
fromArrayToCollection(oa, co);// T inferred to be Object
No comments:
Post a Comment