gpt4 book ai didi

java - Maps.newHashMap 与新 HashMap 返回的 HashMap

转载 作者:IT老高 更新时间:2023-10-28 13:53:19 26 4
gpt4 key购买 nike

我第一次尝试 Guava ,我发现它真的很棒。

我在 Spring jdbc 模板上执行了几个参数化检索查询。 DAO (AbstractDataAccessObject) 中的方法是这样的。这里没问题。

public Map<String,Object> getResultAsMap(String sql, Map<String,Object> parameters) {
try {
return jdbcTemplate.queryForMap(sql, parameters);
} catch (EmptyResultDataAccessException e) {
//Ignore if no data found for this query
logger.error(e.getMessage(), e);

}
return null;
}

问题来了:

当我使用

调用此方法时
getResultAsMap(query, new HashMap<String,Object>(ImmutableMap.of("gciList",gciList)));

效果很好。

但是当我这样做时

getResultAsMap(query, Maps.newHashMap(ImmutableMap.of("gciList",gciList)));

编译器不高兴说

The method getResultAsMap(String, Map<String,Object>) in the type AbstractDataAccessObject is not applicable for the arguments (String, HashMap<String,List<String>>)

我是不是做错了什么?或者是什么原因导致了此投诉?

最佳答案

这是类型推断失败。 Maps.newHashMap是静态参数化方法。它允许您使用

Map<String,Integer> map = Maps.newHashMap()

而不是

Map<String,Integer> map = new HashMap<String,Integer>()

让您不必输入 <String,Integer>两次。在 Java 7 中,菱形运算符允许您使用

Map<String,Integer> map = new HashMap<>()

所以该方法是多余的。

要回答您的问题,只需使用 new HashMap版本,因为类型推断不适用于方法参数。 (您可以使用 Maps.<String,Object>newHashMap() 但这违背了使用该方法的意义)

关于java - Maps.newHashMap 与新 HashMap 返回的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13153609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com