I am trying Guava for the first time and I find it really awesome.
I am executing few parameterized retrieve queries on a Spring jdbc template. The method in the DAO (AbstractDataAccessObject) goes like this. No problem here.
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;
}
Here’s the problem :
When I call this method using
getResultAsMap(query, new HashMap<String,Object>(ImmutableMap.of("gciList",gciList)));
it works great.
But when I do this
getResultAsMap(query, Maps.newHashMap(ImmutableMap.of("gciList",gciList)));
the compiler gets upset saying
The method getResultAsMap(String, Map<String,Object>) in the type AbstractDataAccessObject is not applicable for the arguments (String, HashMap<String,List<String>>)
Am I doing something wrong or what could be the reason for this complaint?
This is type inference failing.
Maps.newHashMapis a static parameterized method. It allows you to useinstead of
saving you from having to type
<String,Integer>twice. In Java 7, the diamond operator allows you to useso the method is then redundant.
To answer your question, just use the
new HashMapversion, since type inference doesn’t work for method parameters. (You could useMaps.<String,Object>newHashMap()but that defeats the point of using the method)