Home | History | Annotate | Download | only in collect
      1 /*
      2  * Copyright (C) 2007 The Guava Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.collect;
     18 
     19 import static com.google.common.base.Preconditions.checkArgument;
     20 
     21 import com.google.common.annotations.GwtCompatible;
     22 import com.google.common.annotations.GwtIncompatible;
     23 import com.google.common.annotations.VisibleForTesting;
     24 
     25 import java.io.IOException;
     26 import java.io.ObjectInputStream;
     27 import java.io.ObjectOutputStream;
     28 import java.util.ArrayList;
     29 import java.util.Collection;
     30 import java.util.HashMap;
     31 import java.util.List;
     32 import java.util.Map;
     33 
     34 /**
     35  * Implementation of {@code Multimap} that uses an {@code ArrayList} to store
     36  * the values for a given key. A {@link HashMap} associates each key with an
     37  * {@link ArrayList} of values.
     38  *
     39  * <p>When iterating through the collections supplied by this class, the
     40  * ordering of values for a given key agrees with the order in which the values
     41  * were added.
     42  *
     43  * <p>This multimap allows duplicate key-value pairs. After adding a new
     44  * key-value pair equal to an existing key-value pair, the {@code
     45  * ArrayListMultimap} will contain entries for both the new value and the old
     46  * value.
     47  *
     48  * <p>Keys and values may be null. All optional multimap methods are supported,
     49  * and all returned views are modifiable.
     50  *
     51  * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link
     52  * #replaceValues} all implement {@link java.util.RandomAccess}.
     53  *
     54  * <p>This class is not threadsafe when any concurrent operations update the
     55  * multimap. Concurrent read operations will work correctly. To allow concurrent
     56  * update operations, wrap your multimap with a call to {@link
     57  * Multimaps#synchronizedListMultimap}.
     58  *
     59  * @author Jared Levy
     60  * @since 2.0 (imported from Google Collections Library)
     61  */
     62 @GwtCompatible(serializable = true, emulated = true)
     63 public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> {
     64   // Default from ArrayList
     65   private static final int DEFAULT_VALUES_PER_KEY = 10;
     66 
     67   @VisibleForTesting transient int expectedValuesPerKey;
     68 
     69   /**
     70    * Creates a new, empty {@code ArrayListMultimap} with the default initial
     71    * capacities.
     72    */
     73   public static <K, V> ArrayListMultimap<K, V> create() {
     74     return new ArrayListMultimap<K, V>();
     75   }
     76 
     77   /**
     78    * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold
     79    * the specified numbers of keys and values without resizing.
     80    *
     81    * @param expectedKeys the expected number of distinct keys
     82    * @param expectedValuesPerKey the expected average number of values per key
     83    * @throws IllegalArgumentException if {@code expectedKeys} or {@code
     84    *      expectedValuesPerKey} is negative
     85    */
     86   public static <K, V> ArrayListMultimap<K, V> create(
     87       int expectedKeys, int expectedValuesPerKey) {
     88     return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey);
     89   }
     90 
     91   /**
     92    * Constructs an {@code ArrayListMultimap} with the same mappings as the
     93    * specified multimap.
     94    *
     95    * @param multimap the multimap whose contents are copied to this multimap
     96    */
     97   public static <K, V> ArrayListMultimap<K, V> create(
     98       Multimap<? extends K, ? extends V> multimap) {
     99     return new ArrayListMultimap<K, V>(multimap);
    100   }
    101 
    102   private ArrayListMultimap() {
    103     super(new HashMap<K, Collection<V>>());
    104     expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
    105   }
    106 
    107   private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
    108     super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
    109     checkArgument(expectedValuesPerKey >= 0);
    110     this.expectedValuesPerKey = expectedValuesPerKey;
    111   }
    112 
    113   private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
    114     this(multimap.keySet().size(),
    115         (multimap instanceof ArrayListMultimap) ?
    116             ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey :
    117             DEFAULT_VALUES_PER_KEY);
    118     putAll(multimap);
    119   }
    120 
    121   /**
    122    * Creates a new, empty {@code ArrayList} to hold the collection of values for
    123    * an arbitrary key.
    124    */
    125   @Override List<V> createCollection() {
    126     return new ArrayList<V>(expectedValuesPerKey);
    127   }
    128 
    129   /**
    130    * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
    131    */
    132   public void trimToSize() {
    133     for (Collection<V> collection : backingMap().values()) {
    134       ArrayList<V> arrayList = (ArrayList<V>) collection;
    135       arrayList.trimToSize();
    136     }
    137   }
    138 
    139   /**
    140    * @serialData expectedValuesPerKey, number of distinct keys, and then for
    141    *     each distinct key: the key, number of values for that key, and the
    142    *     key's values
    143    */
    144   @GwtIncompatible("java.io.ObjectOutputStream")
    145   private void writeObject(ObjectOutputStream stream) throws IOException {
    146     stream.defaultWriteObject();
    147     stream.writeInt(expectedValuesPerKey);
    148     Serialization.writeMultimap(this, stream);
    149   }
    150 
    151   @GwtIncompatible("java.io.ObjectOutputStream")
    152   private void readObject(ObjectInputStream stream)
    153       throws IOException, ClassNotFoundException {
    154     stream.defaultReadObject();
    155     expectedValuesPerKey = stream.readInt();
    156     int distinctKeys = Serialization.readCount(stream);
    157     Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys);
    158     setMap(map);
    159     Serialization.populateMultimap(this, stream, distinctKeys);
    160   }
    161 
    162   @GwtIncompatible("Not needed in emulated source.")
    163   private static final long serialVersionUID = 0;
    164 }
    165