What happens when I remove an item from the list initialized by hashmap.values()?
I have the following declaration in class A:
Map<String, MyClass> myMap = Collections.synchronizedMap(new LinkedHashMap<String, MyClass>());
Class A also has this feature:
public List<MyClass> getMapValuesAsList() {
return new ArrayList<>(myMap.values());
}
In class B, I have a List
initialized as follows:
List<MyClass> myList = cart.getMapValuesAsList();
I assume that myList
holds a reference to the myMap
value. When I call the setter function in the project in myList
, the relevant values are also updated in myMap
, supporting my hypothesis. However, whenever I delete an item from myList
, myMap
continues to keep MyClass
instances in it. This deleted instance may not have been garbage collected because myMap
still has a reference to it. Am I right?
Is there any automatic way to remove key-value pairs from the mapping when values are deleted elsewhere?
Update: Class B passes myList
to the Android adapter. Therefore, I need some kind of get
function. Collection has no such method. Any suggestions?
Solution
Your List contains references to instances that are your Map
values, so changing the state of individual elements of a List
changes the Map's
value.
On the other hand, your List
is not supported by Map
, so removing an element from it does not affect Map's entry
Is there any automated way to delete key-value pair from map when the value is removed somewhere else?
Yes, if you remove an element directly from the Collection
returned by myMap.values(),
it will also remove the corresponding key-value pair from the map>
map.
This is the state in Javadoc for values().
Collection java.util.Map.values()
Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map arereflected in the collection, and vice-versa. If the map ismodified while an iteration over the collection is in progress(except through the iterator’s own remove operation),the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map , via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does notsupport the add or addAll operations.