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