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.common.annotations.J2ktIncompatible;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.DoNotCall;
027import java.io.InvalidObjectException;
028import java.io.ObjectInputStream;
029import java.util.Arrays;
030import java.util.Collection;
031import java.util.Comparator;
032import java.util.Map;
033import javax.annotation.CheckForNull;
034
035/**
036 * A {@link BiMap} whose contents will never change, with many other important properties detailed
037 * at {@link ImmutableCollection}.
038 *
039 * @author Jared Levy
040 * @since 2.0
041 */
042@GwtCompatible(serializable = true, emulated = true)
043@ElementTypesAreNonnullByDefault
044public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> {
045
046  /**
047   * Returns the empty bimap.
048   *
049   * <p><b>Performance note:</b> the instance returned is a singleton.
050   */
051  // Casting to any type is safe because the set will never hold any elements.
052  @SuppressWarnings("unchecked")
053  public static <K, V> ImmutableBiMap<K, V> of() {
054    return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY;
055  }
056
057  /** Returns an immutable bimap containing a single entry. */
058  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
059    checkEntryNotNull(k1, v1);
060    return new RegularImmutableBiMap<>(new Object[] {k1, v1}, 1);
061  }
062
063  /**
064   * Returns an immutable map containing the given entries, in order.
065   *
066   * @throws IllegalArgumentException if duplicate keys or values are added
067   */
068  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
069    checkEntryNotNull(k1, v1);
070    checkEntryNotNull(k2, v2);
071    return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2}, 2);
072  }
073
074  /**
075   * Returns an immutable map containing the given entries, in order.
076   *
077   * @throws IllegalArgumentException if duplicate keys or values are added
078   */
079  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
080    checkEntryNotNull(k1, v1);
081    checkEntryNotNull(k2, v2);
082    checkEntryNotNull(k3, v3);
083    return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2, k3, v3}, 3);
084  }
085
086  /**
087   * Returns an immutable map containing the given entries, in order.
088   *
089   * @throws IllegalArgumentException if duplicate keys or values are added
090   */
091  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
092    checkEntryNotNull(k1, v1);
093    checkEntryNotNull(k2, v2);
094    checkEntryNotNull(k3, v3);
095    checkEntryNotNull(k4, v4);
096    return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2, k3, v3, k4, v4}, 4);
097  }
098
099  /**
100   * Returns an immutable map containing the given entries, in order.
101   *
102   * @throws IllegalArgumentException if duplicate keys or values are added
103   */
104  public static <K, V> ImmutableBiMap<K, V> of(
105      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
106    checkEntryNotNull(k1, v1);
107    checkEntryNotNull(k2, v2);
108    checkEntryNotNull(k3, v3);
109    checkEntryNotNull(k4, v4);
110    checkEntryNotNull(k5, v5);
111    return new RegularImmutableBiMap<K, V>(
112        new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5}, 5);
113  }
114
115  /**
116   * Returns an immutable map containing the given entries, in order.
117   *
118   * @throws IllegalArgumentException if duplicate keys or values are added
119   * @since 31.0
120   */
121  public static <K, V> ImmutableBiMap<K, V> of(
122      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {
123    checkEntryNotNull(k1, v1);
124    checkEntryNotNull(k2, v2);
125    checkEntryNotNull(k3, v3);
126    checkEntryNotNull(k4, v4);
127    checkEntryNotNull(k5, v5);
128    checkEntryNotNull(k6, v6);
129    return new RegularImmutableBiMap<K, V>(
130        new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6}, 6);
131  }
132  /**
133   * Returns an immutable map containing the given entries, in order.
134   *
135   * @throws IllegalArgumentException if duplicate keys or values are added
136   * @since 31.0
137   */
138  public static <K, V> ImmutableBiMap<K, V> of(
139      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {
140    checkEntryNotNull(k1, v1);
141    checkEntryNotNull(k2, v2);
142    checkEntryNotNull(k3, v3);
143    checkEntryNotNull(k4, v4);
144    checkEntryNotNull(k5, v5);
145    checkEntryNotNull(k6, v6);
146    checkEntryNotNull(k7, v7);
147    return new RegularImmutableBiMap<K, V>(
148        new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7}, 7);
149  }
150  /**
151   * Returns an immutable map containing the given entries, in order.
152   *
153   * @throws IllegalArgumentException if duplicate keys or values are added
154   * @since 31.0
155   */
156  public static <K, V> ImmutableBiMap<K, V> of(
157      K k1,
158      V v1,
159      K k2,
160      V v2,
161      K k3,
162      V v3,
163      K k4,
164      V v4,
165      K k5,
166      V v5,
167      K k6,
168      V v6,
169      K k7,
170      V v7,
171      K k8,
172      V v8) {
173    checkEntryNotNull(k1, v1);
174    checkEntryNotNull(k2, v2);
175    checkEntryNotNull(k3, v3);
176    checkEntryNotNull(k4, v4);
177    checkEntryNotNull(k5, v5);
178    checkEntryNotNull(k6, v6);
179    checkEntryNotNull(k7, v7);
180    checkEntryNotNull(k8, v8);
181    return new RegularImmutableBiMap<K, V>(
182        new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8}, 8);
183  }
184  /**
185   * Returns an immutable map containing the given entries, in order.
186   *
187   * @throws IllegalArgumentException if duplicate keys or values are added
188   * @since 31.0
189   */
190  public static <K, V> ImmutableBiMap<K, V> of(
191      K k1,
192      V v1,
193      K k2,
194      V v2,
195      K k3,
196      V v3,
197      K k4,
198      V v4,
199      K k5,
200      V v5,
201      K k6,
202      V v6,
203      K k7,
204      V v7,
205      K k8,
206      V v8,
207      K k9,
208      V v9) {
209    checkEntryNotNull(k1, v1);
210    checkEntryNotNull(k2, v2);
211    checkEntryNotNull(k3, v3);
212    checkEntryNotNull(k4, v4);
213    checkEntryNotNull(k5, v5);
214    checkEntryNotNull(k6, v6);
215    checkEntryNotNull(k7, v7);
216    checkEntryNotNull(k8, v8);
217    checkEntryNotNull(k9, v9);
218    return new RegularImmutableBiMap<K, V>(
219        new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9}, 9);
220  }
221  /**
222   * Returns an immutable map containing the given entries, in order.
223   *
224   * @throws IllegalArgumentException if duplicate keys or values are added
225   * @since 31.0
226   */
227  public static <K, V> ImmutableBiMap<K, V> of(
228      K k1,
229      V v1,
230      K k2,
231      V v2,
232      K k3,
233      V v3,
234      K k4,
235      V v4,
236      K k5,
237      V v5,
238      K k6,
239      V v6,
240      K k7,
241      V v7,
242      K k8,
243      V v8,
244      K k9,
245      V v9,
246      K k10,
247      V v10) {
248    checkEntryNotNull(k1, v1);
249    checkEntryNotNull(k2, v2);
250    checkEntryNotNull(k3, v3);
251    checkEntryNotNull(k4, v4);
252    checkEntryNotNull(k5, v5);
253    checkEntryNotNull(k6, v6);
254    checkEntryNotNull(k7, v7);
255    checkEntryNotNull(k8, v8);
256    checkEntryNotNull(k9, v9);
257    checkEntryNotNull(k10, v10);
258    return new RegularImmutableBiMap<K, V>(
259        new Object[] {
260          k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10
261        },
262        10);
263  }
264
265  // looking for of() with > 10 entries? Use the builder or ofEntries instead.
266
267  /**
268   * Returns an immutable map containing the given entries, in order.
269   *
270   * @throws IllegalArgumentException if duplicate keys or values are provided
271   * @since 31.0
272   */
273  @SafeVarargs
274  public static <K, V> ImmutableBiMap<K, V> ofEntries(Entry<? extends K, ? extends V>... entries) {
275    @SuppressWarnings("unchecked") // we will only ever read these
276    Entry<K, V>[] entries2 = (Entry<K, V>[]) entries;
277    return copyOf(Arrays.asList(entries2));
278  }
279
280  /**
281   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
282   * Builder} constructor.
283   */
284  public static <K, V> Builder<K, V> builder() {
285    return new Builder<>();
286  }
287
288  /**
289   * Returns a new builder, expecting the specified number of entries to be added.
290   *
291   * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
292   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
293   * #builder()} would have.
294   *
295   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
296   * but not exactly, the number of entries added to the builder.
297   *
298   * @since 23.1
299   */
300  @Beta
301  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
302    checkNonnegative(expectedSize, "expectedSize");
303    return new Builder<>(expectedSize);
304  }
305
306  /**
307   * A builder for creating immutable bimap instances, especially {@code public static final} bimaps
308   * ("constant bimaps"). Example:
309   *
310   * <pre>{@code
311   * static final ImmutableBiMap<String, Integer> WORD_TO_INT =
312   *     new ImmutableBiMap.Builder<String, Integer>()
313   *         .put("one", 1)
314   *         .put("two", 2)
315   *         .put("three", 3)
316   *         .buildOrThrow();
317   * }</pre>
318   *
319   * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more
320   * convenient.
321   *
322   * <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order
323   * they were inserted into the builder. For example, in the above example, {@code
324   * WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order {@code "one"=1,
325   * "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same order. If you
326   * want a different order, consider using {@link #orderEntriesByValue(Comparator)}, which changes
327   * this builder to sort entries by value.
328   *
329   * <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to
330   * build multiple bimaps in series. Each bimap is a superset of the bimaps created before it.
331   *
332   * @since 2.0
333   */
334  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
335    /**
336     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
337     * ImmutableBiMap#builder}.
338     */
339    public Builder() {
340      super();
341    }
342
343    Builder(int size) {
344      super(size);
345    }
346
347    /**
348     * Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are
349     * not allowed, and will cause {@link #build} to fail.
350     */
351    @CanIgnoreReturnValue
352    @Override
353    public Builder<K, V> put(K key, V value) {
354      super.put(key, value);
355      return this;
356    }
357
358    /**
359     * Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will
360     * cause {@link #build} to fail.
361     *
362     * @since 19.0
363     */
364    @CanIgnoreReturnValue
365    @Override
366    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
367      super.put(entry);
368      return this;
369    }
370
371    /**
372     * Associates all of the given map's keys and values in the built bimap. Duplicate keys or
373     * values are not allowed, and will cause {@link #build} to fail.
374     *
375     * @throws NullPointerException if any key or value in {@code map} is null
376     */
377    @CanIgnoreReturnValue
378    @Override
379    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
380      super.putAll(map);
381      return this;
382    }
383
384    /**
385     * Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed,
386     * and will cause {@link #build} to fail.
387     *
388     * @throws NullPointerException if any key, value, or entry is null
389     * @since 19.0
390     */
391    @CanIgnoreReturnValue
392    @Beta
393    @Override
394    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
395      super.putAll(entries);
396      return this;
397    }
398
399    /**
400     * Configures this {@code Builder} to order entries by value according to the specified
401     * comparator.
402     *
403     * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
404     * the entry that was inserted first will be first in the built map's iteration order.
405     *
406     * @throws IllegalStateException if this method was already called
407     * @since 19.0
408     */
409    @CanIgnoreReturnValue
410    @Beta
411    @Override
412    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
413      super.orderEntriesByValue(valueComparator);
414      return this;
415    }
416
417    @Override
418    @CanIgnoreReturnValue
419    Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) {
420      super.combine(builder);
421      return this;
422    }
423
424    /**
425     * Returns a newly-created immutable bimap. The iteration order of the returned bimap is the
426     * order in which entries were inserted into the builder, unless {@link #orderEntriesByValue}
427     * was called, in which case entries are sorted by value.
428     *
429     * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method
430     * will throw an exception if there are duplicate keys or values. The {@code build()} method
431     * will soon be deprecated.
432     *
433     * @throws IllegalArgumentException if duplicate keys or values were added
434     */
435    @Override
436    public ImmutableBiMap<K, V> build() {
437      return buildOrThrow();
438    }
439
440    /**
441     * Returns a newly-created immutable bimap, or throws an exception if any key or value was added
442     * more than once. The iteration order of the returned bimap is the order in which entries were
443     * inserted into the builder, unless {@link #orderEntriesByValue} was called, in which case
444     * entries are sorted by value.
445     *
446     * @throws IllegalArgumentException if duplicate keys or values were added
447     * @since 31.0
448     */
449    @Override
450    public ImmutableBiMap<K, V> buildOrThrow() {
451      if (size == 0) {
452        return of();
453      }
454      if (valueComparator != null) {
455        if (entriesUsed) {
456          alternatingKeysAndValues = Arrays.copyOf(alternatingKeysAndValues, 2 * size);
457        }
458        sortEntries(alternatingKeysAndValues, size, valueComparator);
459      }
460      entriesUsed = true;
461      return new RegularImmutableBiMap<K, V>(alternatingKeysAndValues, size);
462    }
463
464    /**
465     * Throws {@link UnsupportedOperationException}. This method is inherited from {@link
466     * ImmutableMap.Builder}, but it does not make sense for bimaps.
467     *
468     * @throws UnsupportedOperationException always
469     * @deprecated This method does not make sense for bimaps and should not be called.
470     * @since 31.1
471     */
472    @DoNotCall
473    @Deprecated
474    @Override
475    public ImmutableBiMap<K, V> buildKeepingLast() {
476      throw new UnsupportedOperationException("Not supported for bimaps");
477    }
478  }
479
480  /**
481   * Returns an immutable bimap containing the same entries as {@code map}. If {@code map} somehow
482   * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
483   * comparator is not <i>consistent with equals</i>), the results of this method are undefined.
484   *
485   * <p>The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet}
486   * of the original map.
487   *
488   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
489   * safe to do so. The exact circumstances under which a copy will or will not be performed are
490   * undocumented and subject to change.
491   *
492   * @throws IllegalArgumentException if two keys have the same value or two values have the same
493   *     key
494   * @throws NullPointerException if any key or value in {@code map} is null
495   */
496  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
497    if (map instanceof ImmutableBiMap) {
498      @SuppressWarnings("unchecked") // safe since map is not writable
499      ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
500      // TODO(lowasser): if we need to make a copy of a BiMap because the
501      // forward map is a view, don't make a copy of the non-view delegate map
502      if (!bimap.isPartialView()) {
503        return bimap;
504      }
505    }
506    return copyOf(map.entrySet());
507  }
508
509  /**
510   * Returns an immutable bimap containing the given entries. The returned bimap iterates over
511   * entries in the same order as the original iterable.
512   *
513   * @throws IllegalArgumentException if two keys have the same value or two values have the same
514   *     key
515   * @throws NullPointerException if any key, value, or entry is null
516   * @since 19.0
517   */
518  @Beta
519  public static <K, V> ImmutableBiMap<K, V> copyOf(
520      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
521    int estimatedSize =
522        (entries instanceof Collection)
523            ? ((Collection<?>) entries).size()
524            : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
525    return new Builder<K, V>(estimatedSize).putAll(entries).build();
526  }
527
528  ImmutableBiMap() {}
529
530  /**
531   * {@inheritDoc}
532   *
533   * <p>The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}.
534   */
535  @Override
536  public abstract ImmutableBiMap<V, K> inverse();
537
538  /**
539   * Returns an immutable set of the values in this map, in the same order they appear in {@link
540   * #entrySet}.
541   */
542  @Override
543  public ImmutableSet<V> values() {
544    return inverse().keySet();
545  }
546
547  @Override
548  final ImmutableSet<V> createValues() {
549    throw new AssertionError("should never be called");
550  }
551
552  /**
553   * Guaranteed to throw an exception and leave the bimap unmodified.
554   *
555   * @throws UnsupportedOperationException always
556   * @deprecated Unsupported operation.
557   */
558  @CanIgnoreReturnValue
559  @Deprecated
560  @Override
561  @DoNotCall("Always throws UnsupportedOperationException")
562  @CheckForNull
563  public final V forcePut(K key, V value) {
564    throw new UnsupportedOperationException();
565  }
566
567  /**
568   * Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are
569   * reconstructed using public factory methods. This ensures that the implementation types remain
570   * as implementation details.
571   *
572   * <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
573   * bimap and its inverse in sync during serialization, the way AbstractBiMap does.
574   */
575  private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
576    SerializedForm(ImmutableBiMap<K, V> bimap) {
577      super(bimap);
578    }
579
580    @Override
581    Builder<K, V> makeBuilder(int size) {
582      return new Builder<>(size);
583    }
584
585    private static final long serialVersionUID = 0;
586  }
587
588  @Override
589  Object writeReplace() {
590    return new SerializedForm<>(this);
591  }
592
593  @J2ktIncompatible // serialization
594  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
595    throw new InvalidObjectException("Use SerializedForm");
596  }
597}