I have researched this question for ages and cannot get it right!
I have a populated hashmap and an identically formatted hashmap ( Map<Integer, ArrayList<String>>
) that I have been working on (it has key value/s equal to other keys in the populated hashmap such as 0,1,2 etc). When I use the .put command to update the populated hashmap the few/one I have been working on replaces everything in the populated hashmap - is this normal? Where am I going wrong? I was expecting it to simply replace the key in question + values....
Excuse the not supplying code but it would mean posting quite an amount to demonstrate, just wondering if anyone could help explain where this might be going wrong. I could throw something together to show if needed...
Much obliged!
This is how a code example might look like:
import java.util.*;
public class NumFormEx
{
public static ArrayList <String> listIt (String... params)
{
ArrayList <String> as = new ArrayList <String> ();
for (String s: params)
as.add (s);
return as;
}
public static void main (String args[])
{
Map <Integer, ArrayList<String>> mils = new HashMap<Integer, ArrayList<String>> ();
mils.put (1, listIt ("foo", "bar"));
mils.put (2, listIt ("zacka", "zacka"));
System.out.println ("mils:\t" + mils);
mils.put (1, listIt ("foobar"));
System.out.println ("mils:\t" + mils);
}
}
Testing:
java NumFormEx
mils: {1=[foo, bar], 2=[zacka, zacka]}
mils: {1=[foobar], 2=[zacka, zacka]}
I would say: as expected.
Since map doesn't allow duplicate values you can do :
myMap.put(2, new ArrayList<String>());
This will take element with key 2 and replace it's list with new ("blank") list.
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.