What happens when an item is deleted from a list initialized by hashmap.values()?

Viewed 496

I have the following declaration in class A:

Map<String, MyClass> myMap = Collections.synchronizedMap(new LinkedHashMap<String, MyClass>());

Class A also has this function:

public List<MyClass> getMapValuesAsList() {
    return new ArrayList<>(myMap.values());
}

In class B, I have a List initialized like this:

List<MyClass> myList = cart.getMapValuesAsList();

What I assume is that myList keeps references to the values of myMap. When I call a setter function in an item in myList, the related value is also updated in myMap, supporting my assumption. However, whenever I delete an item from myList, myMap continues to keep the MyClass instance in it. This removed instance is probably not garbage collected since myMap still has a reference to it. Am I right?

Is there any automated way to delete key-value pair from map when the value is removed somewhere else?

UPDATE: Class B pass myList to an Android adapter. Therefore, I need some kind of get functionality. Collection doesn't have such a method. Any recommendations?

1 Answers

Your List contains references to the instances that are the values of your Map, so mutating the state of individual elements of the List mutates values of the Map.

On the other hand, your List is not backed by the Map, so removing elements to it won't affect the entries of the Map.

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.

This is states in the Javadoc of 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.

Related