001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.collect.CollectPreconditions.checkNonnegative;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.annotations.J2ktIncompatible;
024import com.google.common.annotations.VisibleForTesting;
025import java.io.IOException;
026import java.io.ObjectInputStream;
027import java.io.ObjectOutputStream;
028import java.util.ArrayList;
029import java.util.Collection;
030import java.util.HashMap;
031import java.util.List;
032import java.util.Map;
033import org.checkerframework.checker.nullness.qual.Nullable;
034
035/**
036 * Implementation of {@code Multimap} that uses an {@code ArrayList} to store the values for a given
037 * key. A {@link HashMap} associates each key with an {@link ArrayList} of values.
038 *
039 * <p>When iterating through the collections supplied by this class, the ordering of values for a
040 * given key agrees with the order in which the values were added.
041 *
042 * <p>This multimap allows duplicate key-value pairs. After adding a new key-value pair equal to an
043 * existing key-value pair, the {@code ArrayListMultimap} will contain entries for both the new
044 * value and the old value.
045 *
046 * <p>Keys and values may be null. All optional multimap methods are supported, and all returned
047 * views are modifiable.
048 *
049 * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link #replaceValues} all
050 * implement {@link java.util.RandomAccess}.
051 *
052 * <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent
053 * read operations will work correctly. To allow concurrent update operations, wrap your multimap
054 * with a call to {@link Multimaps#synchronizedListMultimap}.
055 *
056 * <p>See the Guava User Guide article on <a href=
057 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap">{@code Multimap}</a>.
058 *
059 * @author Jared Levy
060 * @since 2.0
061 */
062@GwtCompatible(serializable = true, emulated = true)
063@ElementTypesAreNonnullByDefault
064public final class ArrayListMultimap<K extends @Nullable Object, V extends @Nullable Object>
065    extends ArrayListMultimapGwtSerializationDependencies<K, V> {
066  // Default from ArrayList
067  private static final int DEFAULT_VALUES_PER_KEY = 3;
068
069  @VisibleForTesting transient int expectedValuesPerKey;
070
071  /**
072   * Creates a new, empty {@code ArrayListMultimap} with the default initial capacities.
073   *
074   * <p>You may also consider the equivalent {@code
075   * MultimapBuilder.hashKeys().arrayListValues().build()}, which provides more control over the
076   * underlying data structure.
077   */
078  public static <K extends @Nullable Object, V extends @Nullable Object>
079      ArrayListMultimap<K, V> create() {
080    return new ArrayListMultimap<>();
081  }
082
083  /**
084   * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold the specified
085   * numbers of keys and values without resizing.
086   *
087   * <p>You may also consider the equivalent {@code
088   * MultimapBuilder.hashKeys(expectedKeys).arrayListValues(expectedValuesPerKey).build()}, which
089   * provides more control over the underlying data structure.
090   *
091   * @param expectedKeys the expected number of distinct keys
092   * @param expectedValuesPerKey the expected average number of values per key
093   * @throws IllegalArgumentException if {@code expectedKeys} or {@code expectedValuesPerKey} is
094   *     negative
095   */
096  public static <K extends @Nullable Object, V extends @Nullable Object>
097      ArrayListMultimap<K, V> create(int expectedKeys, int expectedValuesPerKey) {
098    return new ArrayListMultimap<>(expectedKeys, expectedValuesPerKey);
099  }
100
101  /**
102   * Constructs an {@code ArrayListMultimap} with the same mappings as the specified multimap.
103   *
104   * <p>You may also consider the equivalent {@code
105   * MultimapBuilder.hashKeys().arrayListValues().build(multimap)}, which provides more control over
106   * the underlying data structure.
107   *
108   * @param multimap the multimap whose contents are copied to this multimap
109   */
110  public static <K extends @Nullable Object, V extends @Nullable Object>
111      ArrayListMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
112    return new ArrayListMultimap<>(multimap);
113  }
114
115  private ArrayListMultimap() {
116    this(12, DEFAULT_VALUES_PER_KEY);
117  }
118
119  private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
120    super(Platform.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
121    checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
122    this.expectedValuesPerKey = expectedValuesPerKey;
123  }
124
125  private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
126    this(
127        multimap.keySet().size(),
128        (multimap instanceof ArrayListMultimap)
129            ? ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey
130            : DEFAULT_VALUES_PER_KEY);
131    putAll(multimap);
132  }
133
134  /**
135   * Creates a new, empty {@code ArrayList} to hold the collection of values for an arbitrary key.
136   */
137  @Override
138  List<V> createCollection() {
139    return new ArrayList<>(expectedValuesPerKey);
140  }
141
142  /**
143   * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
144   *
145   * @deprecated For a {@link ListMultimap} that automatically trims to size, use {@link
146   *     ImmutableListMultimap}. If you need a mutable collection, remove the {@code trimToSize}
147   *     call, or switch to a {@code HashMap<K, ArrayList<V>>}.
148   */
149  @Deprecated
150  public void trimToSize() {
151    for (Collection<V> collection : backingMap().values()) {
152      ArrayList<V> arrayList = (ArrayList<V>) collection;
153      arrayList.trimToSize();
154    }
155  }
156
157  /**
158   * @serialData expectedValuesPerKey, number of distinct keys, and then for each distinct key: the
159   *     key, number of values for that key, and the key's values
160   */
161  @GwtIncompatible // java.io.ObjectOutputStream
162  @J2ktIncompatible
163  private void writeObject(ObjectOutputStream stream) throws IOException {
164    stream.defaultWriteObject();
165    Serialization.writeMultimap(this, stream);
166  }
167
168  @GwtIncompatible // java.io.ObjectOutputStream
169  @J2ktIncompatible
170  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
171    stream.defaultReadObject();
172    expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
173    int distinctKeys = Serialization.readCount(stream);
174    Map<K, Collection<V>> map = Maps.newHashMap();
175    setMap(map);
176    Serialization.populateMultimap(this, stream, distinctKeys);
177  }
178
179  @GwtIncompatible // Not needed in emulated source.
180  @J2ktIncompatible
181  private static final long serialVersionUID = 0;
182}