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