Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with declaration of Map<String,Class<? extends Serializable>>

Java provides me by <? extends class> a way of filtering the java classes that you can use to build in this case the new HashMap, for example:

I can do that:

Map<String,? extends Serializable> map1 = new HashMap<String,String>();

It is correct, because String implements Serializable, so the compiler let me do that.

But when i try to do it:

Map<String,GenericClass<? extends Serializable>> map2 = new HashMap<String, GenericClass<String>>();

Being the GenericClass as it:

public class GenericClass<T>
{
.
.
.
}

The compiler throw an error saying:

Type mismatch: cannot convert from HashMap<String,GenericClass<String>> to Map<String,GenericClass<? extends Serializable>>

I would like to know, what is happen?

Maybe the compiler cannot detect the extends class being part of a generic type.

like image 461
Ivan Avatar asked Oct 21 '22 05:10

Ivan


1 Answers

You would need to use the following:

Map<String, ? extends GenericClass<? extends Serializable>> map2 =
        new HashMap<String, GenericClass<String>>();

Nested wildcards are much different from top-level wildcards - only the latter perform wildcard capture. As a result, HashMap<String, GenericClass<String>> is considered inconvertible to Map<String, GenericClass<? extends Serializable>>, because GenericClass<? extends Serializable> is a concrete type argument (and because generics aren't covariant).

See this post for further information on nested wildcards: Multiple wildcards on a generic methods makes Java compiler (and me!) very confused

like image 116
Paul Bellora Avatar answered Oct 27 '22 09:10

Paul Bellora