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.VisibleForTesting;
024import java.io.IOException;
025import java.io.ObjectInputStream;
026import java.io.ObjectOutputStream;
027import java.util.ArrayList;
028import java.util.Collection;
029import java.util.HashMap;
030import java.util.List;
031import java.util.Map;
032
033/**
034 * Implementation of {@code Multimap} that uses an {@code ArrayList} to store the values for a given
035 * key. A {@link HashMap} associates each key with an {@link ArrayList} of values.
036 *
037 * <p>When iterating through the collections supplied by this class, the ordering of values for a
038 * given key agrees with the order in which the values were added.
039 *
040 * <p>This multimap allows duplicate key-value pairs. After adding a new key-value pair equal to an
041 * existing key-value pair, the {@code ArrayListMultimap} will contain entries for both the new
042 * value and the old value.
043 *
044 * <p>Keys and values may be null. All optional multimap methods are supported, and all returned
045 * views are modifiable.
046 *
047 * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link #replaceValues} all
048 * implement {@link java.util.RandomAccess}.
049 *
050 * <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent
051 * read operations will work correctly. To allow concurrent update operations, wrap your multimap
052 * with a call to {@link Multimaps#synchronizedListMultimap}.
053 *
054 * <p>See the Guava User Guide article on <a href=
055 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap"> {@code
056 * Multimap}</a>.
057 *
058 * @author Jared Levy
059 * @since 2.0
060 */
061@GwtCompatible(serializable = true, emulated = true)
062public final class ArrayListMultimap<K, V>
063    extends ArrayListMultimapGwtSerializationDependencies<K, V> {
064  // Default from ArrayList
065  private static final int DEFAULT_VALUES_PER_KEY = 3;
066
067  @VisibleForTesting transient int expectedValuesPerKey;
068
069  /**
070   * Creates a new, empty {@code ArrayListMultimap} with the default initial capacities.
071   *
072   * <p>This method will soon be deprecated in favor of {@code
073   * MultimapBuilder.hashKeys().arrayListValues().build()}.
074   */
075  public static <K, V> ArrayListMultimap<K, V> create() {
076    return new ArrayListMultimap<>();
077  }
078
079  /**
080   * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold the specified
081   * numbers of keys and values without resizing.
082   *
083   * <p>This method will soon be deprecated in favor of {@code
084   * MultimapBuilder.hashKeys(expectedKeys).arrayListValues(expectedValuesPerKey).build()}.
085   *
086   * @param expectedKeys the expected number of distinct keys
087   * @param expectedValuesPerKey the expected average number of values per key
088   * @throws IllegalArgumentException if {@code expectedKeys} or {@code expectedValuesPerKey} is
089   *     negative
090   */
091  public static <K, V> ArrayListMultimap<K, V> create(int expectedKeys, int expectedValuesPerKey) {
092    return new ArrayListMultimap<>(expectedKeys, expectedValuesPerKey);
093  }
094
095  /**
096   * Constructs an {@code ArrayListMultimap} with the same mappings as the specified multimap.
097   *
098   * <p>This method will soon be deprecated in favor of {@code
099   * MultimapBuilder.hashKeys().arrayListValues().build(multimap)}.
100   *
101   * @param multimap the multimap whose contents are copied to this multimap
102   */
103  public static <K, V> ArrayListMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
104    return new ArrayListMultimap<>(multimap);
105  }
106
107  private ArrayListMultimap() {
108    this(12, DEFAULT_VALUES_PER_KEY);
109  }
110
111  private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
112    super(Platform.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
113    checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
114    this.expectedValuesPerKey = expectedValuesPerKey;
115  }
116
117  private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
118    this(
119        multimap.keySet().size(),
120        (multimap instanceof ArrayListMultimap)
121            ? ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey
122            : DEFAULT_VALUES_PER_KEY);
123    putAll(multimap);
124  }
125
126  /**
127   * Creates a new, empty {@code ArrayList} to hold the collection of values for an arbitrary key.
128   */
129  @Override
130  List<V> createCollection() {
131    return new ArrayList<V>(expectedValuesPerKey);
132  }
133
134  /**
135   * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
136   *
137   * @deprecated For a {@link ListMultimap} that automatically trims to size, use {@link
138   *     ImmutableListMultimap}. If you need a mutable collection, remove the {@code trimToSize}
139   *     call, or switch to a {@code HashMap<K, ArrayList<V>>}.
140   */
141  @Deprecated
142  public void trimToSize() {
143    for (Collection<V> collection : backingMap().values()) {
144      ArrayList<V> arrayList = (ArrayList<V>) collection;
145      arrayList.trimToSize();
146    }
147  }
148
149  /**
150   * @serialData expectedValuesPerKey, number of distinct keys, and then for each distinct key: the
151   *     key, number of values for that key, and the key's values
152   */
153  @GwtIncompatible // java.io.ObjectOutputStream
154  private void writeObject(ObjectOutputStream stream) throws IOException {
155    stream.defaultWriteObject();
156    Serialization.writeMultimap(this, stream);
157  }
158
159  @GwtIncompatible // java.io.ObjectOutputStream
160  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
161    stream.defaultReadObject();
162    expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
163    int distinctKeys = Serialization.readCount(stream);
164    Map<K, Collection<V>> map = Maps.newHashMap();
165    setMap(map);
166    Serialization.populateMultimap(this, stream, distinctKeys);
167  }
168
169  @GwtIncompatible // Not needed in emulated source.
170  private static final long serialVersionUID = 0;
171}