LinkedCaseInsensitive map casting issue with HashM

2019-08-22 07:55发布

问题:

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