Spring 更高版本的 HashMap 的 LinkedCaseInsensitive 映射问题

LinkedCaseInsensitive map casting issue with HashMaps with Spring higher version

LinkedCaseInsensitiveMap 是 Spring 框架的一部分并扩展了 LinkedHashMap

层次结构是这样的:

java.lang.Object

java.util.AbstractMap

java.util.HashMap

java.util.LinkedHashMap

org.springframework.util.LinkedCaseInsensitiveMap

有关信息,请参阅:https://docs.spring.io/spring/docs/3.2.4.RELEASE_to_4.0.0.M3/Spring%20Framework%203.2.4.RELEASE/org/springframework/util/LinkedCaseInsensitiveMap.html

现在我有了这个代码:

List<HashMap<String, String>> l_lstResult = (List<HashMap<String, String>>)service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails);

                l_lstCityTownList = new ArrayList<String>(l_lstResult.size());

                for (int i = 0; i < l_lstResult.size(); i++) {
                    HashMap<String, String> l_hmColmnData = l_lstResult.get(i);
                    String l_sValue = l_hmColmnData.get(p_sColumnName);
                    l_lstCityTownList.add(l_sValue);
                }

l_lstResult returns 一个 LinkedCaseInsensitiveMap 并且我在行 HashMap l_hmColmnData = l_lstResult.get(i);

java.lang.ClassCastException: org.springframework.util.LinkedCaseInsensitiveMap cannot be cast to java.util.HashMap

问题是我在 Spring 版本 4.3.14.RELEASE 中遇到此错误,而在 3.2.3.RELEASE 中没有错误。 3.2.3.RELEASE 中允许此转换的规范在哪里。

任何建议、示例都会对我有很大帮助。

非常感谢!

从Spring 4.3.6.RELEASE开始,LinkedCaseInsensitiveMap不再继承LinkedHashMap和HashMap,只实现了Map接口。

API reference.

当您将 service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails) 转换为 List<HashMap<String, String>> 时,您只是告诉编译器 信任 您。但是,当涉及到获取列表的第一个元素时,它失败了,因为它 不是 一个 HashMap 而是一个 LinkedCaseInsensitiveMap(不扩展 HashMap)。

这将解决您的问题

List<LinkedCaseInsensitiveMap<String>> l_lstResult = service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails);

l_lstCityTownList = new ArrayList<String>(l_lstResult.size());

for (int i = 0; i < l_lstResult.size(); i++) {
    LinkedCaseInsensitiveMap<String> l_hmColmnData = l_lstResult.get(i);
    String l_sValue = l_hmColmnData.get(p_sColumnName);
    l_lstCityTownList.add(l_sValue);
}