Java HashMap导致ClassCastException

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java HashMap导致ClassCastException相关的知识,希望对你有一定的参考价值。

我在我的javafx应用程序中的一个方法中使用了HashMap。这个HashMap导致以下ClassCastException

java.lang.ClassCastException:java.util.HashMap $ Node无法强制转换为java.util.ArrayList

@FXML
private void initialize() {
    Map<Integer, ArrayList<WhatsOn>> movieMap = new HashMap<>();

    String whatsOnString = null;
    movieLabels = new Label[]{movie1, movie2, movie3, movie4, movie5, movie6};
    Label[] screenLabels;
    try {
        //get the list of screenings from the database
        whatsOnString = Harness.sendGet("whatson").toString();
        WhatsOn[] whatsOn = JSON.whatsOnFromJson(whatsOnString);

        //set the text of each label to the title of the movie
        for (int i = 0; i < whatsOn.length; i++) {
            if(!movieMap.containsKey(whatsOn[i].getMovie_ID())){
                movieMap.put(whatsOn[i].getMovie_ID(),new ArrayList<>(Arrays.asList(whatsOn[i])));
            } else {
                ArrayList<WhatsOn> list =  (ArrayList<WhatsOn>)movieMap.get(whatsOn[i].getMovie_ID());
                list.add(whatsOn[i]);
                System.out.println(movieMap.get(whatsOn[i].getMovie_ID()));
            }
        }


        Iterator iterator = movieMap.entrySet().iterator();
        int count = 0;
        while(iterator.hasNext()){
            ArrayList<WhatsOn> list = (ArrayList<WhatsOn>) iterator.next();
            setMovieLabel(count, list.get(0));
            for(WhatsOn whatson: list){
            }
            count++;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Could not recieve data from database");
    }
}
答案

迭代地图的EntrySet将生成一系列实现Map.Entry界面的对象。在你的情况下,似乎你想要迭代地图的values()

Iterator<ArrayList<WhatsOn> iterator = movieMap.values().iterator();
int count = 0;
while(iterator.hasNext()) {
    ArrayList<WhatsOn> list = iterator.next();
    setMovieLabel(count, list.get(0));
    for(WhatsOn whatson: list) {
        // Presumably there's some code missing here too
    }
    count++;
}

以上是关于Java HashMap导致ClassCastException的主要内容,如果未能解决你的问题,请参考以下文章

是啥导致 java.util.HashSet 和 HashMap.keySet() 类的 iterator() 排序稍微不可预测?

HashMap导致死循环问题

使用Class作为HashMap的关键是否会导致不良影响?

深入理解JAVA集合系列三:HashMap的死循环解读

深入理解JAVA集合系列三:HashMap的死循环解读

Java HashMap