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