Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a method that returns a map defined as:

public Map<String, ?> getData();

The actual implementation of this method is not clear to me, but, when I try to do:

obj.getData().put("key","value")

I get following compile time error message:

The method put(String, capture#9-of ?) in the type Map is not applicable for the arguments (String, String)

What is the problem? Is String not of type anything?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
274 views
Welcome To Ask or Share your Answers For Others

1 Answer

The return type of

Map<String, ?>

is the same as

Map<String, ? extends Object>

The means that the concrete type returned could be a Map<String, AnyClass>. You can't put a String into an AnyClass, hence the error.

A good general principle is to not use wildcards in method return types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...