![](/img/trans.png)
[英]class java.lang.Long cannot be cast to class java.lang.String error when having a hashmap of mixed types (Long and string)
[英]Weird error Java Hashmap types Long, String
我在Java程序中有一个很奇怪的行为。 我有一个从方法中检索到的Long,Long哈希表,但是当我尝试从该方法中获取信息时,此哈希表是一个String,没有任何错误或警告的String。在我的代码下面:
List<HashMap<Long, Long>> getAggregateResult(String idCheptel, Integer limit) {
StringBuilder hql = new StringBuilder();
hql.append("select new map(t.prod.id, count(t.prod.id))");
... //rest of implem.
return entityManager.createQuery(hql.toString()).setMaxResults(limit).getResultList();
}
函数调用
... //in other method try to retrieve the information
for (HashMap<Long, Long> map : getAggregateResultVetProduct(idCheptel, limit)) {
System.out.println(">>>>>>>" + map.get(0L)); //always null
//the map is asked in Long, but in debugger it's a String, String
for (Map.Entry<Long, Long> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey()); //here key are 0
System.out.println("Value: " + entry.getValue());
}
}
如果有人可以给我一些信息,为什么会有这种行为。 谢谢。
编辑
这里有一些信息:我正在使用Intellij。 在被问到调试器的屏幕截图下方。
有关泛型的信息会在编译过程中删除。 因此,在运行时,您的方法仅返回HashMap
。 因此,有趣的问题是.getResultList()
方法的返回值的实际类型是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.