Reputation: 2455
I am using HashMap to store the key/value pairs. The keys contain duplicates and the value is a List. I want to clear the values list whenever a new key comes. My code so far is
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 do here is that I have an array of frequencies and I add the values of the array to my List and then put the list to my Map. It works fine when the band_number is same.
Suppose if for the first 10 times the band_number = 20
, it simply adds new values in the list and adds that list with key=20
in my Map. But when the new key arrives it adds the new content to the old key as well.
Is it somehow possible to check for the key if it is the same as previous key, then simply put the list to the map, otherwise first clear the List and then add it to Map?
Thanks
Upvotes: 4
Views: 945
Reputation: 50021
It sounds like you are only creating the erfcn
list one time. Each bandsMap.put
call is associating that same list object with all the different keys. Instead, you need to create a new
list for each band_number. You also need to re-use the existing list for that key if it exists.
So, move this line:
List<Integer> erfcn = new ArrayList< Integer >();
away from the declaration of bandsMap. Declare it directly inside the function that adds the frequencies, as follows:
List<Integer> erfcn = bandsMap.get(band_number);
if (erfcn == null) erfcn = new ArrayList<Integer>();
Upvotes: 2
Reputation:
You could get the List
for the key from the Map
and append to it.
List<Integer> erfcn = bandsMap.get(band_number);
If get(band_number)
returns null
, create a new List
.
if (erfcn == null) {
erfcn = new ArrayList<>();
}
Upvotes: 1