Add element to arraylist inside haspmap in java 1.4

268 Views Asked by At

I need to work in java 1.4 which doesn't support generics. This is the code I wrote in java 8

LinkedHashMap<String, ArrayList<String>> m = new LinkedHashMap<>();
ArrayList<String> vals = new ArrayList<String>();
m.put("a", vals);
m.get("a").add(var_name);

After reading jdk 1.4 docs, I managed to get write the below code but how do I add an element to ArrayList inside the map? I don't want to add the values to ArrayList first and then add the ArrayList to map.

LinkedHashMap m = new LinkedHashMap();
ArrayList vals = new ArrayList();
m.put("a", vals);
2

There are 2 best solutions below

1
QBrute On BEST ANSWER

You have to cast beforehand

((ArrayList)m.get("a")).add(var_name);

Of course, if you want to use that value later, you'd have to cast that as well.

7
Rahul Singh On

You can even do this if you are using a higher version of java

 m.put("a", new ArrayList<String>(Arrays.asList("one")));
 m.get("a").add("two");

http://ideone.com/IGnHF4