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