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.GwtCompatible;
023import com.google.common.annotations.J2ktIncompatible;
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  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
300    checkNonnegative(expectedSize, "expectedSize");
301    return new Builder<>(expectedSize);
302  }
303
304  /**
305   * A builder for creating immutable bimap instances, especially {@code public static final} bimaps
306   * ("constant bimaps"). Example:
307   *
308   * <pre>{@code
309   * static final ImmutableBiMap<String, Integer> WORD_TO_INT =
310   *     new ImmutableBiMap.Builder<String, Integer>()
311   *         .put("one", 1)
312   *         .put("two", 2)
313   *         .put("three", 3)
314   *         .buildOrThrow();
315   * }</pre>
316   *
317   * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more
318   * convenient.
319   *
320   * <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order
321   * they were inserted into the builder. For example, in the above example, {@code
322   * WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order {@code "one"=1,
323   * "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same order. If you
324   * want a different order, consider using {@link #orderEntriesByValue(Comparator)}, which changes
325   * this builder to sort entries by value.
326   *
327   * <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to
328   * build multiple bimaps in series. Each bimap is a superset of the bimaps created before it.
329   *
330   * @since 2.0
331   */
332  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
333    /**
334     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
335     * ImmutableBiMap#builder}.
336     */
337    public Builder() {
338      super();
339    }
340
341    Builder(int size) {
342      super(size);
343    }
344
345    /**
346     * Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are
347     * not allowed, and will cause {@link #build} to fail.
348     */
349    @CanIgnoreReturnValue
350    @Override
351    public Builder<K, V> put(K key, V value) {
352      super.put(key, value);
353      return this;
354    }
355
356    /**
357     * Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will
358     * cause {@link #build} to fail.
359     *
360     * @since 19.0
361     */
362    @CanIgnoreReturnValue
363    @Override
364    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
365      super.put(entry);
366      return this;
367    }
368
369    /**
370     * Associates all of the given map's keys and values in the built bimap. Duplicate keys or
371     * values are not allowed, and will cause {@link #build} to fail.
372     *
373     * @throws NullPointerException if any key or value in {@code map} is null
374     */
375    @CanIgnoreReturnValue
376    @Override
377    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
378      super.putAll(map);
379      return this;
380    }
381
382    /**
383     * Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed,
384     * and will cause {@link #build} to fail.
385     *
386     * @throws NullPointerException if any key, value, or entry is null
387     * @since 19.0
388     */
389    @CanIgnoreReturnValue
390    @Override
391    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
392      super.putAll(entries);
393      return this;
394    }
395
396    /**
397     * Configures this {@code Builder} to order entries by value according to the specified
398     * comparator.
399     *
400     * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
401     * the entry that was inserted first will be first in the built map's iteration order.
402     *
403     * @throws IllegalStateException if this method was already called
404     * @since 19.0
405     */
406    @CanIgnoreReturnValue
407    @Override
408    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
409      super.orderEntriesByValue(valueComparator);
410      return this;
411    }
412
413    @Override
414    @CanIgnoreReturnValue
415    Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) {
416      super.combine(builder);
417      return this;
418    }
419
420    /**
421     * Returns a newly-created immutable bimap. The iteration order of the returned bimap is the
422     * order in which entries were inserted into the builder, unless {@link #orderEntriesByValue}
423     * was called, in which case entries are sorted by value.
424     *
425     * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method
426     * will throw an exception if there are duplicate keys or values. The {@code build()} method
427     * will soon be deprecated.
428     *
429     * @throws IllegalArgumentException if duplicate keys or values were added
430     */
431    @Override
432    public ImmutableBiMap<K, V> build() {
433      return buildOrThrow();
434    }
435
436    /**
437     * Returns a newly-created immutable bimap, or throws an exception if any key or value was added
438     * more than once. The iteration order of the returned bimap is the order in which entries were
439     * inserted into the builder, unless {@link #orderEntriesByValue} was called, in which case
440     * entries are sorted by value.
441     *
442     * @throws IllegalArgumentException if duplicate keys or values were added
443     * @since 31.0
444     */
445    @Override
446    public ImmutableBiMap<K, V> buildOrThrow() {
447      if (size == 0) {
448        return of();
449      }
450      if (valueComparator != null) {
451        if (entriesUsed) {
452          alternatingKeysAndValues = Arrays.copyOf(alternatingKeysAndValues, 2 * size);
453        }
454        sortEntries(alternatingKeysAndValues, size, valueComparator);
455      }
456      entriesUsed = true;
457      return new RegularImmutableBiMap<K, V>(alternatingKeysAndValues, size);
458    }
459
460    /**
461     * Throws {@link UnsupportedOperationException}. This method is inherited from {@link
462     * ImmutableMap.Builder}, but it does not make sense for bimaps.
463     *
464     * @throws UnsupportedOperationException always
465     * @deprecated This method does not make sense for bimaps and should not be called.
466     * @since 31.1
467     */
468    @DoNotCall
469    @Deprecated
470    @Override
471    public ImmutableBiMap<K, V> buildKeepingLast() {
472      throw new UnsupportedOperationException("Not supported for bimaps");
473    }
474  }
475
476  /**
477   * Returns an immutable bimap containing the same entries as {@code map}. If {@code map} somehow
478   * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
479   * comparator is not <i>consistent with equals</i>), the results of this method are undefined.
480   *
481   * <p>The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet}
482   * of the original map.
483   *
484   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
485   * safe to do so. The exact circumstances under which a copy will or will not be performed are
486   * undocumented and subject to change.
487   *
488   * @throws IllegalArgumentException if two keys have the same value or two values have the same
489   *     key
490   * @throws NullPointerException if any key or value in {@code map} is null
491   */
492  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
493    if (map instanceof ImmutableBiMap) {
494      @SuppressWarnings("unchecked") // safe since map is not writable
495      ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
496      // TODO(lowasser): if we need to make a copy of a BiMap because the
497      // forward map is a view, don't make a copy of the non-view delegate map
498      if (!bimap.isPartialView()) {
499        return bimap;
500      }
501    }
502    return copyOf(map.entrySet());
503  }
504
505  /**
506   * Returns an immutable bimap containing the given entries. The returned bimap iterates over
507   * entries in the same order as the original iterable.
508   *
509   * @throws IllegalArgumentException if two keys have the same value or two values have the same
510   *     key
511   * @throws NullPointerException if any key, value, or entry is null
512   * @since 19.0
513   */
514  public static <K, V> ImmutableBiMap<K, V> copyOf(
515      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
516    int estimatedSize =
517        (entries instanceof Collection)
518            ? ((Collection<?>) entries).size()
519            : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
520    return new Builder<K, V>(estimatedSize).putAll(entries).build();
521  }
522
523  ImmutableBiMap() {}
524
525  /**
526   * {@inheritDoc}
527   *
528   * <p>The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}.
529   */
530  @Override
531  public abstract ImmutableBiMap<V, K> inverse();
532
533  /**
534   * Returns an immutable set of the values in this map, in the same order they appear in {@link
535   * #entrySet}.
536   */
537  @Override
538  public ImmutableSet<V> values() {
539    return inverse().keySet();
540  }
541
542  @Override
543  final ImmutableSet<V> createValues() {
544    throw new AssertionError("should never be called");
545  }
546
547  /**
548   * Guaranteed to throw an exception and leave the bimap unmodified.
549   *
550   * @throws UnsupportedOperationException always
551   * @deprecated Unsupported operation.
552   */
553  @CanIgnoreReturnValue
554  @Deprecated
555  @Override
556  @DoNotCall("Always throws UnsupportedOperationException")
557  @CheckForNull
558  public final V forcePut(K key, V value) {
559    throw new UnsupportedOperationException();
560  }
561
562  /**
563   * Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are
564   * reconstructed using public factory methods. This ensures that the implementation types remain
565   * as implementation details.
566   *
567   * <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
568   * bimap and its inverse in sync during serialization, the way AbstractBiMap does.
569   */
570  @J2ktIncompatible // serialization
571  private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
572    SerializedForm(ImmutableBiMap<K, V> bimap) {
573      super(bimap);
574    }
575
576    @Override
577    Builder<K, V> makeBuilder(int size) {
578      return new Builder<>(size);
579    }
580
581    private static final long serialVersionUID = 0;
582  }
583
584  @Override
585  @J2ktIncompatible // serialization
586  Object writeReplace() {
587    return new SerializedForm<>(this);
588  }
589
590  @J2ktIncompatible // serialization
591  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
592    throw new InvalidObjectException("Use SerializedForm");
593  }
594}