1

I am using a HashMap in one of the methods in my javafx application. This HashMap is causing the following 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");
    }
}
1
  • Replace movieMap.entrySet().iterator(); with movieMap.values().iterator(); Commented Apr 18, 2018 at 16:23

1 Answer 1

1

Iterating over a map's EntrySet will produce a series of objects implementing the Map.Entry interface. In your case, it seems as though you meant to iterate over the values() of the map:

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.