【发布时间】:2019-12-03 20:50:03
【问题描述】:
我在泛型类型参数的分配能力上有点挣扎。
我的类型定义如下所示:
public static interface CellValue<T> {
T getValue();
Class<?> getType();
}
public static class DoubleCell implements CellValue<Double> {
Double value;
public DoubleCell(Double value) {
super();
this.value = value;
}
@Override
public Double getValue() {
return value;
}
@Override
public Class<?> getType() {
return Double.class;
}
}
public static class FormulaCell implements CellValue<String> {
String value;
public FormulaCell(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public Class<?> getType() {
return String.class;
}
}
现在,为什么以下声明有效(对我来说,这是预期的行为,但我可能误解了它为什么有效)
Map<String, ? extends CellValue<?>> m = new HashMap<String, FormulaCell>();
Map<String, ? extends CellValue<?>> m2 = new HashMap<String, DoubleCell>();
..而以下没有?
Map<Integer, Map<String, ? extends CellValue<?>>> n = new HashMap<Integer, Map<String, FormulaCell>>();
Map<Integer, Map<String, ? extends CellValue<?>>> n2 = new HashMap<Integer, Map<String, DoubleCell>>();
【问题讨论】:
-
this 会有帮助吗?
-
谢谢!这很有帮助。我会尽量避免使用嵌套通配符。
标签: java generics type-parameter generic-collections