I have two classes with nested generics. Is there a way to get rid of the
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;
}
}
Use the following:
The problem is that the
?inMsg<Value<?>> objMsgis NOT capable of capture conversion. It’s not “aMsgofValueof some type. It’s “aMsgofValueof ANY type”.This also explains why along with the declaration change, I’ve also renamed the variable to
someMsg. TheValuecan’t just be anyObject. It must belong to some type (Stringin this example).A more generic example
Let’s consider a more generic example of a
List<List<?>>. Analogously to the original scenario, aList<List<?>>can NOT capture-convert aList<List<Integer>>.Here’s another way to look at it:
IntegertoNumber, but aList<Integer>is not aList<Number>List<Integer>can be capture-converted by aList<?>, but aList<List<Integer>>is not aList<List<?>>List<? extendsNumber>can capture-convert aList<Integer>List<? extendsList<?>>can capture-convert aList<List<Integer>>The fact that some
?can capture and others can’t also explains the following snippet:Related questions
List<List<? extends Number>>List<Animal> animals = new ArrayList<Dog>()?<E extends Number>and<Number>?See also