rzenks rzenks - 6 months ago 22
Java Question

Couldn't cast class with List

I'm having a cast error while trying a method.
I couldn't figure out the actual problem here.

(List) member --> this line is generating cast error as class couldnt cast to List.

How can I update this issue?

java.lang.ClassCastException: com.test.Member cannot be cast to java.util.List
at com.test.impl.Main.splitMembersByState


protected Map< String, List< Member>> splitMembersByState(List< Member> validMembers) {
// TODO

Map< String, List< Member>> membersSplitByState = new HashMap<String, List<Member>>();
List<Member> tempList = validMembers;

for (Member member : validMembers) {
membersSplitByState.put(member.getState(), (List<Member>) member);

}

return membersSplitByState;
}


Thank you.

Answer

membersSplitByState is String -> List and your trying to put a member in it (member).

Here, you want to put your member in a list of member, not directly in the map. Something like that:

    Map< String, List< Member>> membersSplitByState = new HashMap<String, List<Member>>();
    List<Member> tempList = validMembers;

    for (Member member : validMembers) {
        List<Member> membersWithState;
        if (membersSplitByState.containsKey(member.getState()) {
           membersWithState = membersSplitByState.get(member.getState());
        } else {
           membersWithState = new ArrayList<Member>();
           membersSplitByState.put(member.getState(), membersWithState);
        }
        membersWithState.add(member);
    }
    return membersSplitByState;
Comments