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 com.google.common.annotations.GwtCompatible;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.VisibleForTesting;
022import com.google.common.base.Preconditions;
023import java.io.IOException;
024import java.io.ObjectInputStream;
025import java.io.ObjectOutputStream;
026import java.util.Collection;
027import java.util.Map;
028import java.util.Set;
029
030/**
031 * Implementation of {@link Multimap} using hash tables.
032 *
033 * <p>The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an
034 * existing key-value pair has no effect.
035 *
036 * <p>Keys and values may be null. All optional multimap methods are supported, and all returned
037 * views are modifiable.
038 *
039 * <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent
040 * read operations will work correctly. To allow concurrent update operations, wrap your multimap
041 * with a call to {@link Multimaps#synchronizedSetMultimap}.
042 *
043 * @author Jared Levy
044 * @since 2.0
045 */
046@GwtCompatible(serializable = true, emulated = true)
047public final class HashMultimap<K, V> extends HashMultimapGwtSerializationDependencies<K, V> {
048  private static final int DEFAULT_VALUES_PER_KEY = 2;
049
050  @VisibleForTesting transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
051
052  /**
053   * Creates a new, empty {@code HashMultimap} with the default initial capacities.
054   *
055   * <p>This method will soon be deprecated in favor of {@code
056   * MultimapBuilder.hashKeys().hashSetValues().build()}.
057   */
058  public static <K, V> HashMultimap<K, V> create() {
059    return new HashMultimap<>();
060  }
061
062  /**
063   * Constructs an empty {@code HashMultimap} with enough capacity to hold the specified numbers of
064   * keys and values without rehashing.
065   *
066   * <p>This method will soon be deprecated in favor of {@code
067   * MultimapBuilder.hashKeys(expectedKeys).hashSetValues(expectedValuesPerKey).build()}.
068   *
069   * @param expectedKeys the expected number of distinct keys
070   * @param expectedValuesPerKey the expected average number of values per key
071   * @throws IllegalArgumentException if {@code expectedKeys} or {@code expectedValuesPerKey} is
072   *     negative
073   */
074  public static <K, V> HashMultimap<K, V> create(int expectedKeys, int expectedValuesPerKey) {
075    return new HashMultimap<>(expectedKeys, expectedValuesPerKey);
076  }
077
078  /**
079   * Constructs a {@code HashMultimap} with the same mappings as the specified multimap. If a
080   * key-value mapping appears multiple times in the input multimap, it only appears once in the
081   * constructed multimap.
082   *
083   * <p>This method will soon be deprecated in favor of {@code
084   * MultimapBuilder.hashKeys().hashSetValues().build(multimap)}.
085   *
086   * @param multimap the multimap whose contents are copied to this multimap
087   */
088  public static <K, V> HashMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
089    return new HashMultimap<>(multimap);
090  }
091
092  private HashMultimap() {
093    this(12, DEFAULT_VALUES_PER_KEY);
094  }
095
096  private HashMultimap(int expectedKeys, int expectedValuesPerKey) {
097    super(Platform.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
098    Preconditions.checkArgument(expectedValuesPerKey >= 0);
099    this.expectedValuesPerKey = expectedValuesPerKey;
100  }
101
102  private HashMultimap(Multimap<? extends K, ? extends V> multimap) {
103    super(Platform.<K, Collection<V>>newHashMapWithExpectedSize(multimap.keySet().size()));
104    putAll(multimap);
105  }
106
107  /**
108   * {@inheritDoc}
109   *
110   * <p>Creates an empty {@code HashSet} for a collection of values for one key.
111   *
112   * @return a new {@code HashSet} containing a collection of values for one key
113   */
114  @Override
115  Set<V> createCollection() {
116    return Platform.<V>newHashSetWithExpectedSize(expectedValuesPerKey);
117  }
118
119  /**
120   * @serialData expectedValuesPerKey, number of distinct keys, and then for each distinct key: the
121   *     key, number of values for that key, and the key's values
122   */
123  @GwtIncompatible // java.io.ObjectOutputStream
124  private void writeObject(ObjectOutputStream stream) throws IOException {
125    stream.defaultWriteObject();
126    Serialization.writeMultimap(this, stream);
127  }
128
129  @GwtIncompatible // java.io.ObjectInputStream
130  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
131    stream.defaultReadObject();
132    expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
133    int distinctKeys = Serialization.readCount(stream);
134    Map<K, Collection<V>> map = Platform.newHashMapWithExpectedSize(12);
135    setMap(map);
136    Serialization.populateMultimap(this, stream, distinctKeys);
137  }
138
139  @GwtIncompatible // Not needed in emulated source
140  private static final long serialVersionUID = 0;
141}