Clear List Type Values ​​in HashMap

I use HashMap to store key / value pairs. The keys contain duplicates, and the value is a list. I want to clear the list of values ​​whenever a new key arrives. My code is still

Map<Integer, List<Integer> > bandsMap = new HashMap< Integer, List<Integer> >();
List<Integer> erfcn = new ArrayList< Integer >();

for(int i=0 ; i<frequencies.length; i++)
    erfcn.add(frequencies[i]);

bandsMap.put( band_number, erfcn);

What I'm doing here is that I have an array of frequencies, and I add the array values ​​to my list, and then put the list on my map. It works fine when band_number is the same.

Suppose that if for the first 10 times band_number = 20it just adds new values ​​to the list and adds this list with key=20to my map. But when a new key arrives, it adds new content to the old key.

Is it possible to check the key, if it is the same as the previous one, and then just put the list on the map, otherwise clear the list first and then add it to Map?

thanks

+4
source share
2 answers

It looks like you only create the list erfcnonce. Each call bandsMap.putassociates the same list object with all different keys. Instead, you need to create a list newfor each band_number. You also need to reuse the existing list for this key, if one exists.

So move this line:

List<Integer> erfcn = new ArrayList< Integer >();

away from group announcements. Declare it directly inside a function that adds frequencies, as follows:

List<Integer> erfcn = bandsMap.get(band_number);
if (erfcn == null) erfcn = new ArrayList<Integer>();
+2
source

You can get Listfor the key from Mapand add to it.

List<Integer> erfcn = bandsMap.get(band_number);

If get(band_number)returns null, create a new one List.

if (erfcn == null) {
  erfcn = new ArrayList<>();
}
+1
source

All Articles