javaarraylisthashmapjava1.4

Add element to arraylist inside haspmap in java 1.4


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

Solution

  • 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.