I'm just starting to learn to use HashMap and reading the java tutorial, but I'm having trouble.
I'm trying to update the List inside a HashMap but I want to get the List of that key, is there a way to update a specific List of the key instead of having to make...5 different Lists and updating those?
HashMap<String, ArrayList<String>> mMap = new HashMap<String, ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
mMap.put("A", list);
mMap.put("B", list);
mMap.put("C", list);
mMap.put("D", list);
Iterator iter = mMap.entrySet().iterator();
if (mMap.containsKey("A"))
{
Map.Entry mEntry = (Map.Entry) iter.next();
list.add("test");
mMap.put("A",list);
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
else if (mMap.containsKey("B"))
{
Map.Entry mEntry = (Map.Entry) iter.next();
list.add("entry");
mMap.put("B",list);
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
You could use something like:
mMap.get("A").add("test");
mMap.get("B").add("entry");
If you add the same list as a value with different keys, in your case keys A,B,C, and D all point to the same list, and access and update the list through one key the changes will then be visible in all the lists. Each key points to the same list structure.
If you want the lists to be different you need to use different for different keys you need to use a different list.
You could automate the process, say by making your own insert method that clones the given list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With