gpt4 book ai didi

Java HashMap 导致 ClassCastException

转载 作者:行者123 更新时间:2023-11-30 06:12:37 25 4
gpt4 key购买 nike

我在 javafx 应用程序的方法之一中使用 HashMap。此 HashMap 导致以下 ClassCastException:

java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to 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");
}
}

最佳答案

迭代 map 的 EntrySet 将生成一系列实现 Map.Entry 接口(interface)的对象。就您而言,似乎您打算迭代 map 的 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49904314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com