Wildcard in Generics doesn't work
Looking at the following code, why doesn't the second invocation of dump get compiled? And how can I fix it without removing the wildcard?
import java.util.ArrayList;
import 开发者_开发问答java.util.List;
class Column<A, T extends Object> {
}
public class Generics {
static void main(String[] args) {
Integer i = 5;
// this works
List<Column<Integer, ?>> columns1 = new ArrayList<Column<Integer, ?>>();
dump(columns1, i);
// this doesn't
List<Column<Integer, String>> columns2 = new ArrayList<Column<Integer, String>>();
dump(columns2, i);
}
static <A, T> void dump(Iterable<Column<A, ?>> columns, A value) {
for (Column<A,?> col: columns) {
System.out.println(col);
}
}
}
The JDK's compiler gives
Generics.java:18: <A,T>dump(java.lang.Iterable<Column<A,?>>,A) in Generics cannot be applied to (java.util.List<Column<java.lang.Integer,java.lang.String>>,java.lang.Integer)
dump(columns2, i);
^
1 error
Since columns
in dump()
acts as a producer of objects, you need to declare it with extends
(the general rule is "producer - extends
, consumer - super
"):
static <A, T> void dump(Iterable<? extends Column<A, ?>> columns, A value) {
for (Column<A,?> col: columns) {
System.out.println(col);
}
}
精彩评论