If I have a Map<String, List<String>>
and I want to get the List<String>
value for a given key, and then append something to that list, why do I need to call map.put(key, list)
to persist the update? Especially whereas a method like Arrays.sort(input_arr)
does not require resetting the variable again like String[] sorted_arr = Arrays.sort(input_arr)
? Using the below code as an example, is it because when we call List<String> list = map.getOrDefault(arr[i], new ArrayList<String>())
, is the value stored in list not a reference to the ArrayList? Or is it a copy of the original ArrayList that gets set to the list
variable?
HashMap<String, List<String>> map = new HashMap<>();
String[] arr = new String[]{"one", "two"};
for (int i=0; i<arr.length; i++) {
List<String> list = map.getOrDefault(arr[i], new ArrayList<String>());
if (arr[i].equals("one") {
list.add("onetwo");
}
map.put(arr[i], list);
}