简体   繁体   中英

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:

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!

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM