Reputation: 67
Java Multimap does .get() method create a dynamic allocation of a temporary list? From the source code:
Collection<V> get(@Nullable K key);
Returns the set of all keys, each appearing once in the returned set.
Changes to the returned set will update the underlying multimap, and vice
versa.
@return the collection of distinct keys
Upvotes: 0
Views: 307
Reputation: 9844
Multimap
is an interface, so ultimately the answer will depend on the implementation. If we take ArrayListMultimap
as an example, we can see the source code here:
If you trace up the inheritance hierarchy, you'll find that get
is defined in abstract base class AbstractMapBasedMultimap
:
We can see that if not found, then a Collection
is created for the key:
@Override
public Collection<V> get(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key, collection);
}
For the implementation of createCollection
, we need to go back down to ArrayListMultimap
:
@Override List<V> createCollection() {
return new ArrayList<V>(expectedValuesPerKey);
}
Here we can see that a new list is being created on demand. However, it would be incorrect to call it "temporary" as described in the original question. This is going to be the real list backing that entry in the map.
However, keep in mind that this answer is for one specific implementation of Multimap
and one specific version of the codebase. This demonstrates the process of exploring the code though, so if you have questions about other implementations or other versions, then you can browse through the code to see the behavior.
Upvotes: 2