Can someone explain the following error (from eclipse IDE):
The method 开发者_如何转开发put(String, capture#1-of ?) in the type Map is not applicable for the arguments (String, Object)
Received on line 3 of the code blow:
public class MyTest {
public void populateUserLoggedIn(Map<String, ?> model){
model.put( "test", new Object() );
}
}
?
is not equivalent to Object
for methods that take ?
as a parameter. With a Map<String, ?>
, the signature of put
is put(String, ?)
. You can't pass anything but null
for a ?
parameter.
Consider this:
Map<String, Integer> map = new HashMap<String, Integer>();
myTest.populateUserLoggedIn(map);
Integer foo = map.get("test"); // ClassCastException
Since populateUserLoggedIn
takes a Map<String, ?>
, a map with any type of values can be passed in... so within the method you have no way of knowing what types are or aren't legal as values. Therefore, you cannot add any.
The type of the values of model
is undefined, so the compiler can't guarantee that a value of type Object
will be appropriate.
You should read this paragraph:
As an example of an unbounded wildcard,
List<?>
indicates a list which has an unknown object type. Methods which take such a list as an argument can take any type of list, regardless of parameter type. Reading from the list will return objects of typeObject
, and writing non-null elements to the list is not allowed, since the parameter type is not known.
精彩评论