sta*_*ker 10 java generics casting
我有两个嵌套泛型的类.有没有办法摆脱
类型不匹配:无法转换Msg<Value<String>>
为Msg<Value<?>>
错误?在最后一次任务中
public class Value<V> {
V val;
public Value(V val) {
this.val = val;
}
@Override
public String toString() {
return "" + val;
}
}
public class Msg<T> {
T holder;
public Msg( T holder) {
this.holder = holder ;
}
public String toString() {
return "" + holder;
}
public static void main(String[] args) {
Msg<Value<String>>strMsg = new Msg(new Value<String>("abc"));
// This is OK
Msg<?>objMsg = strMsg;
// Type mismatch: cannot convert from Msg<Value<String>> to Msg<Value<?>>
Msg<Value<?>>objMsg = strMsg;
}
}
Run Code Online (Sandbox Code Playgroud)
pol*_*nts 18
使用以下内容:
Msg<? extends Value<?>> someMsg = strMsg;
Run Code Online (Sandbox Code Playgroud)
问题是,?
在Msg<Value<?>> objMsg
是不是能够捕获转换.这不是"一Msg
中Value
的某些类型.这是'一Msg
中Value
的任何类型’.
这也解释了为什么随着声明的变化,我也将变量重命名为someMsg
.该Value
不能只是任何Object
.它必须属于某种类型(String
在此示例中).
让我们考虑一个更通用的例子List<List<?>>
.类似于原来的场景中,List<List<?>>
可以不采集,转换List<List<Integer>>
.
List<List<Integer>> lolInt = null;
List<List<?>> lolAnything = lolInt; // DOES NOT COMPILE!!!
// a list of "lists of anything"
List<? extends List<?>> lolSomething = lolInt; // compiles fine!
// a list of "lists of something"
Run Code Online (Sandbox Code Playgroud)
这是另一种看待它的方式:
Integer
到Number
,但不是List<
Integer
>
List<
Number
>
List<Integer>
可以由a捕获转换List<?>
,但a 不是aList<
List<Integer>
>
List<
List<?>
>
List<? extends?
Number
>
List<
Integer
>
List<? extends?
List<?>
>
List<
List<Integer>
>
有些人?
可以捕获的事实和其他人也无法解释以下片段:
List<List<?>> lolAnything = new ArrayList<List<?>>(); // compiles fine!
List<?> listSomething = new ArrayList<?>(); // DOES NOT COMPILE!!!
// cannot instantiate wildcard type with new!
Run Code Online (Sandbox Code Playgroud)
List<List<? extends Number>>
List<Animal> animals = new ArrayList<Dog>()
?<E extends Number>
和之间有什么区别<Number>
? 归档时间: |
|
查看次数: |
3376 次 |
最近记录: |