5

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
quartaela
  • 2,579
  • 16
  • 63
  • 99

1 Answers1

2
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.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • Actually, I changed a couple of lines,like `List>> list = new ArrayList(mainCodesMap.entrySet());`, so I have only entries in a list as I wanted. However, what do you mean by "It doesnt work in all contexts". Does it depend on Java version ?. And thanks for your reply anyway – quartaela Jan 19 '14 at 11:20