Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap value change after "get"

Tags:

java

I have a

private Map<String,List<ProductScheme>> discountMap = new HashMap<String,List<ProductScheme>>();

now if i get list from discountMap and add an item in list will i have to put the list again in discount map or it will not be required ??

like image 613
Shashank Degloorkar Avatar asked Dec 01 '22 05:12

Shashank Degloorkar


2 Answers

No it's not required. get returns a reference to the list stored in the map. So whatever modification you do on the list obtained with get (add, remove...) will be reflected on the list in the map too, because they are the same object.

like image 104
assylias Avatar answered Dec 02 '22 18:12

assylias


You only need to add a List if it wasn't there before. A pattern I use is

List<ProductScheme> list = discountMap.get(key);
if (list == null)
    discountMap.put(key, list = new ArrayList<>());
list.add(value);
like image 44
Peter Lawrey Avatar answered Dec 02 '22 19:12

Peter Lawrey