001/*
002 * Copyright (C) 2008 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.checkEntryNotNull;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.errorprone.annotations.CanIgnoreReturnValue;
025import com.google.errorprone.annotations.DoNotCall;
026import java.util.Collection;
027import java.util.Comparator;
028import java.util.Map;
029
030/**
031 * A {@link BiMap} whose contents will never change, with many other important properties detailed
032 * at {@link ImmutableCollection}.
033 *
034 * @author Jared Levy
035 * @since 2.0
036 */
037@GwtCompatible(serializable = true, emulated = true)
038public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> {
039
040  /** Returns the empty bimap. */
041  // Casting to any type is safe because the set will never hold any elements.
042  @SuppressWarnings("unchecked")
043  public static <K, V> ImmutableBiMap<K, V> of() {
044    return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY;
045  }
046
047  /** Returns an immutable bimap containing a single entry. */
048  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
049    checkEntryNotNull(k1, v1);
050    return new RegularImmutableBiMap<>(new Object[] {k1, v1}, 1);
051  }
052
053  /**
054   * Returns an immutable map containing the given entries, in order.
055   *
056   * @throws IllegalArgumentException if duplicate keys or values are added
057   */
058  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
059    checkEntryNotNull(k1, v1);
060    checkEntryNotNull(k2, v2);
061    return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2}, 2);
062  }
063
064  /**
065   * Returns an immutable map containing the given entries, in order.
066   *
067   * @throws IllegalArgumentException if duplicate keys or values are added
068   */
069  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
070    checkEntryNotNull(k1, v1);
071    checkEntryNotNull(k2, v2);
072    checkEntryNotNull(k3, v3);
073    return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2, k3, v3}, 3);
074  }
075
076  /**
077   * Returns an immutable map containing the given entries, in order.
078   *
079   * @throws IllegalArgumentException if duplicate keys or values are added
080   */
081  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
082    checkEntryNotNull(k1, v1);
083    checkEntryNotNull(k2, v2);
084    checkEntryNotNull(k3, v3);
085    checkEntryNotNull(k4, v4);
086    return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2, k3, v3, k4, v4}, 4);
087  }
088
089  /**
090   * Returns an immutable map containing the given entries, in order.
091   *
092   * @throws IllegalArgumentException if duplicate keys or values are added
093   */
094  public static <K, V> ImmutableBiMap<K, V> of(
095      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
096    checkEntryNotNull(k1, v1);
097    checkEntryNotNull(k2, v2);
098    checkEntryNotNull(k3, v3);
099    checkEntryNotNull(k4, v4);
100    checkEntryNotNull(k5, v5);
101    return new RegularImmutableBiMap<K, V>(
102        new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5}, 5);
103  }
104
105  // looking for of() with > 5 entries? Use the builder instead.
106
107  /**
108   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
109   * Builder} constructor.
110   */
111  public static <K, V> Builder<K, V> builder() {
112    return new Builder<>();
113  }
114
115  /**
116   * Returns a new builder, expecting the specified number of entries to be added.
117   *
118   * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
119   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
120   * #builder()} would have.
121   *
122   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
123   * but not exactly, the number of entries added to the builder.
124   *
125   * @since 23.1
126   */
127  @Beta
128  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
129    checkNonnegative(expectedSize, "expectedSize");
130    return new Builder<>(expectedSize);
131  }
132
133  /**
134   * A builder for creating immutable bimap instances, especially {@code public static final} bimaps
135   * ("constant bimaps"). Example:
136   *
137   * <pre>{@code
138   * static final ImmutableBiMap<String, Integer> WORD_TO_INT =
139   *     new ImmutableBiMap.Builder<String, Integer>()
140   *         .put("one", 1)
141   *         .put("two", 2)
142   *         .put("three", 3)
143   *         .build();
144   * }</pre>
145   *
146   * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more
147   * convenient.
148   *
149   * <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order
150   * they were inserted into the builder. For example, in the above example, {@code
151   * WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order {@code "one"=1,
152   * "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same order. If you
153   * want a different order, consider using {@link #orderEntriesByValue(Comparator)}, which changes
154   * this builder to sort entries by value.
155   *
156   * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build
157   * multiple bimaps in series. Each bimap is a superset of the bimaps created before it.
158   *
159   * @since 2.0
160   */
161  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
162    /**
163     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
164     * ImmutableBiMap#builder}.
165     */
166    public Builder() {
167      super();
168    }
169
170    Builder(int size) {
171      super(size);
172    }
173
174    /**
175     * Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are
176     * not allowed, and will cause {@link #build} to fail.
177     */
178    @CanIgnoreReturnValue
179    @Override
180    public Builder<K, V> put(K key, V value) {
181      super.put(key, value);
182      return this;
183    }
184
185    /**
186     * Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will
187     * cause {@link #build} to fail.
188     *
189     * @since 19.0
190     */
191    @CanIgnoreReturnValue
192    @Override
193    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
194      super.put(entry);
195      return this;
196    }
197
198    /**
199     * Associates all of the given map's keys and values in the built bimap. Duplicate keys or
200     * values are not allowed, and will cause {@link #build} to fail.
201     *
202     * @throws NullPointerException if any key or value in {@code map} is null
203     */
204    @CanIgnoreReturnValue
205    @Override
206    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
207      super.putAll(map);
208      return this;
209    }
210
211    /**
212     * Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed,
213     * and will cause {@link #build} to fail.
214     *
215     * @throws NullPointerException if any key, value, or entry is null
216     * @since 19.0
217     */
218    @CanIgnoreReturnValue
219    @Beta
220    @Override
221    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
222      super.putAll(entries);
223      return this;
224    }
225
226    /**
227     * Configures this {@code Builder} to order entries by value according to the specified
228     * comparator.
229     *
230     * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
231     * the entry that was inserted first will be first in the built map's iteration order.
232     *
233     * @throws IllegalStateException if this method was already called
234     * @since 19.0
235     */
236    @CanIgnoreReturnValue
237    @Beta
238    @Override
239    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
240      super.orderEntriesByValue(valueComparator);
241      return this;
242    }
243
244    @Override
245    @CanIgnoreReturnValue
246    Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) {
247      super.combine(builder);
248      return this;
249    }
250
251    /**
252     * Returns a newly-created immutable bimap. The iteration order of the returned bimap is the
253     * order in which entries were inserted into the builder, unless {@link #orderEntriesByValue}
254     * was called, in which case entries are sorted by value.
255     *
256     * @throws IllegalArgumentException if duplicate keys or values were added
257     */
258    @Override
259    public ImmutableBiMap<K, V> build() {
260      if (size == 0) {
261        return of();
262      }
263      sortEntries();
264      entriesUsed = true;
265      return new RegularImmutableBiMap<K, V>(alternatingKeysAndValues, size);
266    }
267  }
268
269  /**
270   * Returns an immutable bimap containing the same entries as {@code map}. If {@code map} somehow
271   * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
272   * comparator is not <i>consistent with equals</i>), the results of this method are undefined.
273   *
274   * <p>The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet}
275   * of the original map.
276   *
277   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
278   * safe to do so. The exact circumstances under which a copy will or will not be performed are
279   * undocumented and subject to change.
280   *
281   * @throws IllegalArgumentException if two keys have the same value or two values have the same
282   *     key
283   * @throws NullPointerException if any key or value in {@code map} is null
284   */
285  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
286    if (map instanceof ImmutableBiMap) {
287      @SuppressWarnings("unchecked") // safe since map is not writable
288      ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
289      // TODO(lowasser): if we need to make a copy of a BiMap because the
290      // forward map is a view, don't make a copy of the non-view delegate map
291      if (!bimap.isPartialView()) {
292        return bimap;
293      }
294    }
295    return copyOf(map.entrySet());
296  }
297
298  /**
299   * Returns an immutable bimap containing the given entries. The returned bimap iterates over
300   * entries in the same order as the original iterable.
301   *
302   * @throws IllegalArgumentException if two keys have the same value or two values have the same
303   *     key
304   * @throws NullPointerException if any key, value, or entry is null
305   * @since 19.0
306   */
307  @Beta
308  public static <K, V> ImmutableBiMap<K, V> copyOf(
309      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
310    int estimatedSize =
311        (entries instanceof Collection)
312            ? ((Collection<?>) entries).size()
313            : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
314    return new Builder<K, V>(estimatedSize).putAll(entries).build();
315  }
316
317  ImmutableBiMap() {}
318
319  /**
320   * {@inheritDoc}
321   *
322   * <p>The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}.
323   */
324  @Override
325  public abstract ImmutableBiMap<V, K> inverse();
326
327  /**
328   * Returns an immutable set of the values in this map, in the same order they appear in {@link
329   * #entrySet}.
330   */
331  @Override
332  public ImmutableSet<V> values() {
333    return inverse().keySet();
334  }
335
336  @Override
337  final ImmutableSet<V> createValues() {
338    throw new AssertionError("should never be called");
339  }
340
341  /**
342   * Guaranteed to throw an exception and leave the bimap unmodified.
343   *
344   * @throws UnsupportedOperationException always
345   * @deprecated Unsupported operation.
346   */
347  @CanIgnoreReturnValue
348  @Deprecated
349  @Override
350  @DoNotCall("Always throws UnsupportedOperationException")
351  public final V forcePut(K key, V value) {
352    throw new UnsupportedOperationException();
353  }
354
355  /**
356   * Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are
357   * reconstructed using public factory methods. This ensures that the implementation types remain
358   * as implementation details.
359   *
360   * <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
361   * bimap and its inverse in sync during serialization, the way AbstractBiMap does.
362   */
363  private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
364    SerializedForm(ImmutableBiMap<K, V> bimap) {
365      super(bimap);
366    }
367
368    @Override
369    Builder<K, V> makeBuilder(int size) {
370      return new Builder<>(size);
371    }
372
373    private static final long serialVersionUID = 0;
374  }
375
376  @Override
377  Object writeReplace() {
378    return new SerializedForm<>(this);
379  }
380}