我有一个像这样的简单豆:
class Account {
private String username;
private String password;
private Map<String, String> extras;
String getUsername() {
return username;
}
void setUsername(String username) {
this.username = username;
}
String getPassword() {
return password;
}
void setPassword(String password) {
this.password = password;
}
Map<String, String> getExtras() {
return extras;
}
void setExtras(Map<String,String> attr) {
this.extras=attr;
}
}
现在我要通过以下方式设置extra
:
Account tmpAccount=new Account();
tmpAccount.setExtras(new HashMap<String, String>().put("x","y"));
但是我收到了这个错误:
setExtras(Map<String,String> in Account cannot be applied to Object.
为什么?
答案 0 :(得分:3)
如果我理解你的问题,问题是你无法链接HashMap put,
Map<String, String> map = new HashMap<>();
tmpAccount.setExtras(map.put("x","y"));
V put(K键,V值)
它返回V
,而不是Map
。 setExtras(map);
需要Map
(不是String
)。
答案 1 :(得分:2)
new HashMap<String, String>().put("x","y")
此语句返回String
实例
void setExtras(Map<String,String> attr)
请参阅put(K, V)
API文档以供参考
答案 2 :(得分:0)
Account tmpAccount=new Account();
tmpAccount.setExtras(new HashMap<String, String>().put("x","y"));
不起作用。使用如下
Account tmpAccount=new Account();
Map<String, String> myExtras = new HashMap<String, String>();
myExtras.put("x","y");
tmpAccount.setExtras(myExtras);
原因,HashMap的put方法签名如下
public V put(K key,V value)
,它返回的值是
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can
also indicate that the map previously associated null with key.)
所以,当你这样做时
tmpAccount.setExtras(new HashMap<String, String>().put("x","y"));
您将setExtras设置为null,因为它需要HashMap
答案 3 :(得分:0)
.put()返回与key关联的先前值,如果没有key的映射,则返回null。你应该这样做:
Account tmpAccount=new Account();
Map<String, String> values = new HashMap<String, String>();
values.put("x","y");
tmpAccount.setExtras(values);
答案 4 :(得分:0)
我刚刚找到了另一个解决方案,转向Map:
tmpAccount.setExtras(Map<String, String>)new HashMap<String, String>().put("x","y"));
它运作正常。
答案 5 :(得分:0)
方法put()
返回字符串对象,而方法setExtras(Map m)
期待调用对象Map
,请尝试以下方法:)
Account tmpAccount = new Account();
Map map = new HashMap<String, String>();
map.put("x", "y");
tmpAccount.setExtras(map);