LinkedCaseInsensitive map casting issue with HashMaps with Spring higher version

≯℡__Kan透↙ 提交于 2020-01-06 07:17:28

问题


The LinkedCaseInsensitiveMap is part of the Spring Framework and extends the LinkedHashMap

The hierarchy goes like this:

java.lang.Object

java.util.AbstractMap

java.util.HashMap

java.util.LinkedHashMap

org.springframework.util.LinkedCaseInsensitiveMap

For information refer : 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

Now I have this code :

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);
                }

The l_lstResult returns a LinkedCaseInsensitiveMap and i get the error in the line HashMap l_hmColmnData = l_lstResult.get(i);

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

The thing is i get this error with Spring version 4.3.14.RELEASE and no error in 3.2.3.RELEASE. Where is the specification in 3.2.3.RELEASE that allows this casting.

Any suggestions,examples would help me a lot .

Thanks a lot !


回答1:


Since Spring 4.3.6.RELEASE, LinkedCaseInsensitiveMap doesn't extend anymore LinkedHashMap and HashMap, but only implements Map interface.

API reference.

When you cast service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails) to List<HashMap<String, String>> you're just telling the compiler to trust you. But then, when it comes to get the first element of the list, it fails because it's not a HashMap but a LinkedCaseInsensitiveMap (not extending HashMap).

This will solve your issue

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);
}


来源:https://stackoverflow.com/questions/54684878/linkedcaseinsensitive-map-casting-issue-with-hashmaps-with-spring-higher-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!