"获取"后HashMap值的变化

Sha*_*kar 3 java

我有一个

private Map<String,List<ProductScheme>> discountMap = new HashMap<String,List<ProductScheme>>();
Run Code Online (Sandbox Code Playgroud)

现在,如果我从列表中获取列表discountMap并在列表中添加项目,我将不得不重新列入列表,discount map否则将不需要?

ass*_*ias 9

不,不是必需的.get返回对映射中存储的列表的引用.因此,对使用get(添加,删除...)获得的列表所做的任何修改也将反映在地图中的列表中,因为它们是相同的对象.


Pet*_*rey 9

如果以前没有List,你只需要添加一个List.我使用的模式是

List<ProductScheme> list = discountMap.get(key);
if (list == null)
    discountMap.put(key, list = new ArrayList<>());
list.add(value);
Run Code Online (Sandbox Code Playgroud)

  • +1:`discountMap.put(key,list = new ArrayList <>());`很好 (3认同)