Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I define a HashMap with multiple value types in Java?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading