简体   繁体   中英

Java Multimap does get method create a dynamic allocation of a temporary list?

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

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:

https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/ArrayListMultimap.java

If you trace up the inheritance hierarchy, you'll find that get is defined in abstract base class AbstractMapBasedMultimap :

https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java#303

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 :

https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/ArrayListMultimap.java#129

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM