My current HashMap has the following structure, which is working fine for me.
Map<String, List<MyClass>> data = new HashMap<String, List<MyClass>>() {{
put("correct", new ArrayList<MyClass>());
put("incorrect", new ArrayList<MyClass>());
}}
Nevertheless I want to add a string to the same HashMap. I already tried the following, but it leads to an error when I want to add new elements to the ArrayList’s.
Map<String, Object> data = new HashMap<String, Object>() {{
put("correct", new ArrayList<MyClass>());
put("incorrect", new ArrayList<MyClass>());
put("filestring", new String());
}}
The error:
class java.util.ArrayList cannot be cast to class java.util.Set (java.util.ArrayList and java.util.Set are in module java.base of loader 'bootstrap')
The way I try to add new elements to the ArrayList’s:
((Set<List<MyClass>>) data.get("correct")).add((List<MyClass>) new MyClass());
Does anybody know how I can achieve the above? I highly appreciate any kind of help, cheers!
>Solution :
What you store for the key "correct" is new ArrayList<MyClass>()
:
put("correct", new ArrayList<MyClass>());
But on reading it back you try to cast it into a (Set<List<MyClass>>)
which will not work.
In a similar way later on you try the cast (List<MyClass>) new MyClass()
which will also fail.
To add a new element you need to write
((List<MyClass>) data.get("correct")).add(new MyClass());