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