简体   繁体   中英

Work with values through Hashmap object

i've got a HashMap:

Map<String, Object> ObjectMap = new HashMap<String, Object>();

I put a value to this map:

this.ObjectMap.put("text",new ArrayList<Object>());

Now map stores an object (ArrayList) with key "text". And now i want to put a value to that ArrayList. I can do it this way:

@SuppressWarnings("unchecked")
List<Object> s= (List<Object>) ObjectMap.get("text"); s.add(new Ex("n"))

Can i do this better way and bypass annotation and parameters?

If you need to read the configuration file you can use Stringified value in the list:

Map<String, List<String>> map = new HashMap<>();
map.put("key", new ArrayList<String>());
List<String> list = map.get("key");
list.add("config");

Dont make value as an Object type its not recomended and causes confusion.

Map < String, List < String >> ObjectMap = new HashMap < String, List < String >> ();
this.ArrayObjectMap.put("text", new ArrayList < String > ());
ObjectMap.get("text").add("n");

The issue here is your use of Object as a type of a collection. The warning you are suppressing is there to let you know that this is generally not a good idea as it prevents Java's type system from preventing lots of subtle bugs.

The first thing to ask yourself is what objects you are putting into the collection and how will they be used when they are taken out. In most cases you will find that there is an interface you can define that all members can implement to explicitly declare what objects going into the collection must be able to do.

My recommendation is to look for that interface and then declare your map as Map<String, MyInterface> .

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