无法使用泛型转换为不特定的嵌套类型 [英] Can't cast to to unspecific nested type with generics
问题描述
我有两个带有嵌套泛型的类.有没有办法摆脱
I have two classes with nested generics. Is there a way to get rid of the
类型不匹配:无法从 Msg
转换为 Msg
错误?在上次作业中
Type mismatch: cannot convert from Msg<Value<String>>
to Msg<Value<?>>
error ?
In the last assignment
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;
}
}
推荐答案
使用以下内容:
Msg<? extends Value<?>> someMsg = strMsg;
问题是Msg
不 能够捕获转换.它不是some类型的?
objMsgValue
的Msg
.它是Value
的Msg
任何类型的代码>".
The problem is that the ?
in Msg<Value<?>> objMsg
is NOT capable of capture conversion. It's not "a Msg
of Value
of some type. It's "a Msg
of Value
of ANY type".
这也解释了为什么随着声明的更改,我还将变量重命名为 someMsg
.Value
不能只是任何 Object
.它必须属于 some 类型(在本例中为 String
).
This also explains why along with the declaration change, I've also renamed the variable to someMsg
. The Value
can't just be any Object
. It must belong to some type (String
in this example).
让我们考虑一个更通用的 List
示例.与原始场景类似,>
List
可以NOT捕获转换List
.>
Let's consider a more generic example of a List<List<?>>
. Analogously to the original scenario, a List<List<?>>
can NOT capture-convert a 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"
这是另一种看待它的方式:
Here's another way to look at it:
- Java 泛型是类型不变的
- 有一个从
Integer
到Number
的转换strong>,但是List<
Integer
>
不是列表<
数字
>
- 类似地,
List
可以通过List>
,但是一个List<
List
>
不是List<
List>
>
- Java generics is type invariant
- There's a conversion from
Integer
toNumber
, but aList<
Integer
>
is not aList<
Number
>
- Similarly, a
List<Integer>
can be capture-converted by aList<?>
, but aList<
List<Integer>
>
is not aList<
List<?>
>
- 同样,
List
List>
>
可以捕获转换一个List<
List
>
- Similarly, a
List<? extends
List<?>
>
can capture-convert aList<
List<Integer>
>
某些
?
可以捕获而其他人不能捕获的事实也解释了以下代码段:The fact that some
?
can capture and others can't also explains the following snippet:List<List<?>> lolAnything = new ArrayList<List<?>>(); // compiles fine! List<?> listSomething = new ArrayList<?>(); // DOES NOT COMPILE!!! // cannot instantiate wildcard type with new!
相关问题
- Similarly, a
- 类似地,