欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ArrayListMultimap源码

程序员文章站 2022-03-15 21:00:50
总算明白了美悦苦心积虑让我看guava的良苦用心,真是太香了啊!!综述我们都知道,ArrayListMultimap的key允许重复,value可以append,类似于下面这样private final Multimap newFiles = ArrayListMultimap.create();newFiles.put(1, "science");newFiles.put(1, "nature");newFiles.put(1, "nature....

总算明白了美悦苦心积虑让我看guava的良苦用心,真是太香了啊!!

综述

我们都知道,ArrayListMultimap的key允许重复,value可以append,类似于下面这样

private final Multimap<Integer, String> newFiles = ArrayListMultimap.create();
newFiles.put(1, "science");
newFiles.put(1, "nature");
newFiles.put(1, "nature");
System.out.println(newFiles.get(1));
// 会打印出下面的东西
["science", "nature", "nature"]

ArrayListMultimap继承了AbstractListMultimap,AbstractListMultimap继承了AbstractMapBasedMultimap中实现了我们常规的对key、value的操作,源码如下

put方法

@Override
  public boolean put(@Nullable K key, @Nullable V value) {
    Collection<V> collection = map.get(key);
    if (collection == null) {
      collection = createCollection(key);
      if (collection.add(value)) {
        totalSize++;
        map.put(key, collection);
        return true;
      } else {
        throw new AssertionError("New Collection violated the Collection spec");
      }
    } else if (collection.add(value)) {
      totalSize++;
      return true;
    } else {
      return false;
    }
  }

get方法

/**
   * {@inheritDoc}
   *
   * <p>The returned collection is not serializable.
   */
  @Override
  public Collection<V> get(@Nullable K key) {
    Collection<V> collection = map.get(key);
    if (collection == null) {
      collection = createCollection(key);
    }
    return wrapCollection(key, collection);
  }

  /**
   * Generates a decorated collection that remains consistent with the values in
   * the multimap for the provided key. Changes to the multimap may alter the
   * returned collection, and vice versa.
   */
  Collection<V> wrapCollection(@Nullable K key, Collection<V> collection) {
    // We don't deal with NavigableSet here yet for GWT reasons -- instead,
    // non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
    if (collection instanceof SortedSet) {
      return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
    } else if (collection instanceof Set) {
      return new WrappedSet(key, (Set<V>) collection);
    } else if (collection instanceof List) {
      return wrapList(key, (List<V>) collection, null);
    } else {
      return new WrappedCollection(key, collection, null);
    }
  }

  private List<V> wrapList(
      @Nullable K key, List<V> list, @Nullable WrappedCollection ancestor) {
    return (list instanceof RandomAccess)
        ? new RandomAccessWrappedList(key, list, ancestor)
        : new WrappedList(key, list, ancestor);
  }

本文地址:https://blog.csdn.net/u010659877/article/details/110251874