Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap$Entry cannot be cast to java.util.LinkedHashMap

I'm wrapped LinkedHashMap<String, LinkedHashMap<Date, Double>> into a List with;

List<LinkedHashMap<String, LinkedHashMap<Date, Double>>> list = new ArrayList(mainCodesMap.entrySet());

which mainCodeMap is type of Map<String, Map<Date, Double>>

the thing is there is no problem with list,however, when I try to get elements of list by index in a for loop like;

for (int i = 0; i < correMatrix.length; i++) {

    LinkedHashMap<String, LinkedHashMap<Date, Double>> entryRow = list.get(i);
    LinkedHashMap<Date, Double> entryRowData = (LinkedHashMap<Date, Double>) entryRow.values();
    ..
    ..
}

jvm throws ClassCastException which says;

java.lang.ClassCastException: java.util.LinkedHashMap$Entry cannot be cast to java.util.LinkedHashMap
like image 692
quartaela Avatar asked Nov 02 '22 06:11

quartaela


1 Answers

List<LinkedHashMap<String, LinkedHashMap<Date, Double>>> list = new ArrayList(mainCodesMap.entrySet());

mainCodesMap.entrySet returns a Set<Map.Entry<...>> (not literally ...). You then create an ArrayList containing these Map.Entrys. Because you are using the raw type ArrayList (instead of ArrayList<something>) the compiler can't catch this problem.

It looks like you actually meant this:

List<LinkedHashMap<String, LinkedHashMap<Date, Double>>> list = new ArrayList<>();
list.add(mainCodesMap)

Note: ArrayList<> means the compiler will automatically fill in the <>. It doesn't work in all contexts.

like image 156
user253751 Avatar answered Nov 04 '22 09:11

user253751