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.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkState;
021import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
022import static com.google.common.collect.CollectPreconditions.checkNonnegative;
023import static java.util.Objects.requireNonNull;
024
025import com.google.common.annotations.Beta;
026import com.google.common.annotations.GwtCompatible;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import com.google.errorprone.annotations.DoNotCall;
029import com.google.errorprone.annotations.DoNotMock;
030import com.google.errorprone.annotations.concurrent.LazyInit;
031import com.google.j2objc.annotations.RetainedWith;
032import com.google.j2objc.annotations.WeakOuter;
033import java.io.InvalidObjectException;
034import java.io.ObjectInputStream;
035import java.io.Serializable;
036import java.util.AbstractMap;
037import java.util.Arrays;
038import java.util.BitSet;
039import java.util.Collection;
040import java.util.Collections;
041import java.util.Comparator;
042import java.util.HashSet;
043import java.util.Iterator;
044import java.util.Map;
045import java.util.Map.Entry;
046import java.util.Set;
047import java.util.SortedMap;
048import javax.annotation.CheckForNull;
049import org.checkerframework.checker.nullness.qual.Nullable;
050
051/**
052 * A {@link Map} whose contents will never change, with many other important properties detailed at
053 * {@link ImmutableCollection}.
054 *
055 * <p>See the Guava User Guide article on <a href=
056 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
057 *
058 * @author Jesse Wilson
059 * @author Kevin Bourrillion
060 * @since 2.0
061 */
062@DoNotMock("Use ImmutableMap.of or another implementation")
063@GwtCompatible(serializable = true, emulated = true)
064@SuppressWarnings("serial") // we're overriding default serialization
065@ElementTypesAreNonnullByDefault
066public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
067
068  /**
069   * Returns the empty map. This map behaves and performs comparably to {@link
070   * Collections#emptyMap}, and is preferable mainly for consistency and maintainability of your
071   * code.
072   *
073   * <p><b>Performance note:</b> the instance returned is a singleton.
074   */
075  @SuppressWarnings("unchecked")
076  public static <K, V> ImmutableMap<K, V> of() {
077    return (ImmutableMap<K, V>) RegularImmutableMap.EMPTY;
078  }
079
080  /**
081   * Returns an immutable map containing a single entry. This map behaves and performs comparably to
082   * {@link Collections#singletonMap} but will not accept a null key or value. It is preferable
083   * mainly for consistency and maintainability of your code.
084   */
085  public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
086    checkEntryNotNull(k1, v1);
087    return RegularImmutableMap.create(1, new Object[] {k1, v1});
088  }
089
090  /**
091   * Returns an immutable map containing the given entries, in order.
092   *
093   * @throws IllegalArgumentException if duplicate keys are provided
094   */
095  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
096    checkEntryNotNull(k1, v1);
097    checkEntryNotNull(k2, v2);
098    return RegularImmutableMap.create(2, new Object[] {k1, v1, k2, v2});
099  }
100
101  /**
102   * Returns an immutable map containing the given entries, in order.
103   *
104   * @throws IllegalArgumentException if duplicate keys are provided
105   */
106  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
107    checkEntryNotNull(k1, v1);
108    checkEntryNotNull(k2, v2);
109    checkEntryNotNull(k3, v3);
110    return RegularImmutableMap.create(3, new Object[] {k1, v1, k2, v2, k3, v3});
111  }
112
113  /**
114   * Returns an immutable map containing the given entries, in order.
115   *
116   * @throws IllegalArgumentException if duplicate keys are provided
117   */
118  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
119    checkEntryNotNull(k1, v1);
120    checkEntryNotNull(k2, v2);
121    checkEntryNotNull(k3, v3);
122    checkEntryNotNull(k4, v4);
123    return RegularImmutableMap.create(4, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4});
124  }
125
126  /**
127   * Returns an immutable map containing the given entries, in order.
128   *
129   * @throws IllegalArgumentException if duplicate keys are provided
130   */
131  public static <K, V> ImmutableMap<K, V> of(
132      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
133    checkEntryNotNull(k1, v1);
134    checkEntryNotNull(k2, v2);
135    checkEntryNotNull(k3, v3);
136    checkEntryNotNull(k4, v4);
137    checkEntryNotNull(k5, v5);
138    return RegularImmutableMap.create(5, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5});
139  }
140
141  /**
142   * Returns an immutable map containing the given entries, in order.
143   *
144   * @throws IllegalArgumentException if duplicate keys are provided
145   * @since 31.0
146   */
147  public static <K, V> ImmutableMap<K, V> of(
148      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {
149    checkEntryNotNull(k1, v1);
150    checkEntryNotNull(k2, v2);
151    checkEntryNotNull(k3, v3);
152    checkEntryNotNull(k4, v4);
153    checkEntryNotNull(k5, v5);
154    checkEntryNotNull(k6, v6);
155    return RegularImmutableMap.create(
156        6, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6});
157  }
158  /**
159   * Returns an immutable map containing the given entries, in order.
160   *
161   * @throws IllegalArgumentException if duplicate keys are provided
162   * @since 31.0
163   */
164  public static <K, V> ImmutableMap<K, V> of(
165      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) {
166    checkEntryNotNull(k1, v1);
167    checkEntryNotNull(k2, v2);
168    checkEntryNotNull(k3, v3);
169    checkEntryNotNull(k4, v4);
170    checkEntryNotNull(k5, v5);
171    checkEntryNotNull(k6, v6);
172    checkEntryNotNull(k7, v7);
173    return RegularImmutableMap.create(
174        7, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7});
175  }
176  /**
177   * Returns an immutable map containing the given entries, in order.
178   *
179   * @throws IllegalArgumentException if duplicate keys are provided
180   * @since 31.0
181   */
182  public static <K, V> ImmutableMap<K, V> of(
183      K k1,
184      V v1,
185      K k2,
186      V v2,
187      K k3,
188      V v3,
189      K k4,
190      V v4,
191      K k5,
192      V v5,
193      K k6,
194      V v6,
195      K k7,
196      V v7,
197      K k8,
198      V v8) {
199    checkEntryNotNull(k1, v1);
200    checkEntryNotNull(k2, v2);
201    checkEntryNotNull(k3, v3);
202    checkEntryNotNull(k4, v4);
203    checkEntryNotNull(k5, v5);
204    checkEntryNotNull(k6, v6);
205    checkEntryNotNull(k7, v7);
206    checkEntryNotNull(k8, v8);
207    return RegularImmutableMap.create(
208        8, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8});
209  }
210  /**
211   * Returns an immutable map containing the given entries, in order.
212   *
213   * @throws IllegalArgumentException if duplicate keys are provided
214   * @since 31.0
215   */
216  public static <K, V> ImmutableMap<K, V> of(
217      K k1,
218      V v1,
219      K k2,
220      V v2,
221      K k3,
222      V v3,
223      K k4,
224      V v4,
225      K k5,
226      V v5,
227      K k6,
228      V v6,
229      K k7,
230      V v7,
231      K k8,
232      V v8,
233      K k9,
234      V v9) {
235    checkEntryNotNull(k1, v1);
236    checkEntryNotNull(k2, v2);
237    checkEntryNotNull(k3, v3);
238    checkEntryNotNull(k4, v4);
239    checkEntryNotNull(k5, v5);
240    checkEntryNotNull(k6, v6);
241    checkEntryNotNull(k7, v7);
242    checkEntryNotNull(k8, v8);
243    checkEntryNotNull(k9, v9);
244    return RegularImmutableMap.create(
245        9, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9});
246  }
247  /**
248   * Returns an immutable map containing the given entries, in order.
249   *
250   * @throws IllegalArgumentException if duplicate keys are provided
251   * @since 31.0
252   */
253  public static <K, V> ImmutableMap<K, V> of(
254      K k1,
255      V v1,
256      K k2,
257      V v2,
258      K k3,
259      V v3,
260      K k4,
261      V v4,
262      K k5,
263      V v5,
264      K k6,
265      V v6,
266      K k7,
267      V v7,
268      K k8,
269      V v8,
270      K k9,
271      V v9,
272      K k10,
273      V v10) {
274    checkEntryNotNull(k1, v1);
275    checkEntryNotNull(k2, v2);
276    checkEntryNotNull(k3, v3);
277    checkEntryNotNull(k4, v4);
278    checkEntryNotNull(k5, v5);
279    checkEntryNotNull(k6, v6);
280    checkEntryNotNull(k7, v7);
281    checkEntryNotNull(k8, v8);
282    checkEntryNotNull(k9, v9);
283    checkEntryNotNull(k10, v10);
284    return RegularImmutableMap.create(
285        10,
286        new Object[] {
287          k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10
288        });
289  }
290
291  // looking for of() with > 10 entries? Use the builder or ofEntries instead.
292
293  /**
294   * Returns an immutable map containing the given entries, in order.
295   *
296   * @throws IllegalArgumentException if duplicate keys are provided
297   * @since 31.0
298   */
299  @SafeVarargs
300  public static <K, V> ImmutableMap<K, V> ofEntries(Entry<? extends K, ? extends V>... entries) {
301    @SuppressWarnings("unchecked") // we will only ever read these
302    Entry<K, V>[] entries2 = (Entry<K, V>[]) entries;
303    return copyOf(Arrays.asList(entries2));
304  }
305
306  /**
307   * Verifies that {@code key} and {@code value} are non-null, and returns a new immutable entry
308   * with those values.
309   *
310   * <p>A call to {@link Entry#setValue} on the returned entry will always throw {@link
311   * UnsupportedOperationException}.
312   */
313  static <K, V> Entry<K, V> entryOf(K key, V value) {
314    checkEntryNotNull(key, value);
315    return new AbstractMap.SimpleImmutableEntry<>(key, value);
316  }
317
318  /**
319   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
320   * Builder} constructor.
321   */
322  public static <K, V> Builder<K, V> builder() {
323    return new Builder<>();
324  }
325
326  /**
327   * Returns a new builder, expecting the specified number of entries to be added.
328   *
329   * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
330   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
331   * #builder()} would have.
332   *
333   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
334   * but not exactly, the number of entries added to the builder.
335   *
336   * @since 23.1
337   */
338  @Beta
339  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
340    checkNonnegative(expectedSize, "expectedSize");
341    return new Builder<>(expectedSize);
342  }
343
344  static void checkNoConflict(
345      boolean safe, String conflictDescription, Object entry1, Object entry2) {
346    if (!safe) {
347      throw conflictException(conflictDescription, entry1, entry2);
348    }
349  }
350
351  static IllegalArgumentException conflictException(
352      String conflictDescription, Object entry1, Object entry2) {
353    return new IllegalArgumentException(
354        "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2);
355  }
356
357  /**
358   * A builder for creating immutable map instances, especially {@code public static final} maps
359   * ("constant maps"). Example:
360   *
361   * <pre>{@code
362   * static final ImmutableMap<String, Integer> WORD_TO_INT =
363   *     new ImmutableMap.Builder<String, Integer>()
364   *         .put("one", 1)
365   *         .put("two", 2)
366   *         .put("three", 3)
367   *         .buildOrThrow();
368   * }</pre>
369   *
370   * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are even more
371   * convenient.
372   *
373   * <p>By default, a {@code Builder} will generate maps that iterate over entries in the order they
374   * were inserted into the builder, equivalently to {@code LinkedHashMap}. For example, in the
375   * above example, {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the
376   * order {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect
377   * the same order. If you want a different order, consider using {@link ImmutableSortedMap} to
378   * sort by keys, or call {@link #orderEntriesByValue(Comparator)}, which changes this builder to
379   * sort entries by value.
380   *
381   * <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to
382   * build multiple maps in series. Each map is a superset of the maps created before it.
383   *
384   * @since 2.0
385   */
386  @DoNotMock
387  public static class Builder<K, V> {
388    @CheckForNull Comparator<? super V> valueComparator;
389    @Nullable Object[] alternatingKeysAndValues;
390    int size;
391    boolean entriesUsed;
392    /**
393     * If non-null, a duplicate key we found in a previous buildKeepingLast() or buildOrThrow()
394     * call. A later buildOrThrow() can simply report this duplicate immediately.
395     */
396    @Nullable DuplicateKey duplicateKey;
397
398    /**
399     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
400     * ImmutableMap#builder}.
401     */
402    public Builder() {
403      this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY);
404    }
405
406    @SuppressWarnings({"unchecked", "rawtypes"})
407    Builder(int initialCapacity) {
408      this.alternatingKeysAndValues = new @Nullable Object[2 * initialCapacity];
409      this.size = 0;
410      this.entriesUsed = false;
411    }
412
413    private void ensureCapacity(int minCapacity) {
414      if (minCapacity * 2 > alternatingKeysAndValues.length) {
415        alternatingKeysAndValues =
416            Arrays.copyOf(
417                alternatingKeysAndValues,
418                ImmutableCollection.Builder.expandedCapacity(
419                    alternatingKeysAndValues.length, minCapacity * 2));
420        entriesUsed = false;
421      }
422    }
423
424    /**
425     * Associates {@code key} with {@code value} in the built map. If the same key is put more than
426     * once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep the last
427     * value put for that key.
428     */
429    @CanIgnoreReturnValue
430    public Builder<K, V> put(K key, V value) {
431      ensureCapacity(size + 1);
432      checkEntryNotNull(key, value);
433      alternatingKeysAndValues[2 * size] = key;
434      alternatingKeysAndValues[2 * size + 1] = value;
435      size++;
436      return this;
437    }
438
439    /**
440     * Adds the given {@code entry} to the map, making it immutable if necessary. If the same key is
441     * put more than once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will
442     * keep the last value put for that key.
443     *
444     * @since 11.0
445     */
446    @CanIgnoreReturnValue
447    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
448      return put(entry.getKey(), entry.getValue());
449    }
450
451    /**
452     * Associates all of the given map's keys and values in the built map. If the same key is put
453     * more than once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep
454     * the last value put for that key.
455     *
456     * @throws NullPointerException if any key or value in {@code map} is null
457     */
458    @CanIgnoreReturnValue
459    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
460      return putAll(map.entrySet());
461    }
462
463    /**
464     * Adds all of the given entries to the built map. If the same key is put more than once, {@link
465     * #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep the last value put for
466     * that key.
467     *
468     * @throws NullPointerException if any key, value, or entry is null
469     * @since 19.0
470     */
471    @CanIgnoreReturnValue
472    @Beta
473    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
474      if (entries instanceof Collection) {
475        ensureCapacity(size + ((Collection<?>) entries).size());
476      }
477      for (Entry<? extends K, ? extends V> entry : entries) {
478        put(entry);
479      }
480      return this;
481    }
482
483    /**
484     * Configures this {@code Builder} to order entries by value according to the specified
485     * comparator.
486     *
487     * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
488     * the entry that was inserted first will be first in the built map's iteration order.
489     *
490     * @throws IllegalStateException if this method was already called
491     * @since 19.0
492     */
493    @CanIgnoreReturnValue
494    @Beta
495    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
496      checkState(this.valueComparator == null, "valueComparator was already set");
497      this.valueComparator = checkNotNull(valueComparator, "valueComparator");
498      return this;
499    }
500
501    @CanIgnoreReturnValue
502    Builder<K, V> combine(Builder<K, V> other) {
503      checkNotNull(other);
504      ensureCapacity(this.size + other.size);
505      System.arraycopy(
506          other.alternatingKeysAndValues,
507          0,
508          this.alternatingKeysAndValues,
509          this.size * 2,
510          other.size * 2);
511      this.size += other.size;
512      return this;
513    }
514
515    private ImmutableMap<K, V> build(boolean throwIfDuplicateKeys) {
516      if (throwIfDuplicateKeys && duplicateKey != null) {
517        throw duplicateKey.exception();
518      }
519      /*
520       * If entries is full, then this implementation may end up using the entries array
521       * directly and writing over the entry objects with non-terminal entries, but this is
522       * safe; if this Builder is used further, it will grow the entries array (so it can't
523       * affect the original array), and future build() calls will always copy any entry
524       * objects that cannot be safely reused.
525       */
526      // localAlternatingKeysAndValues is an alias for the alternatingKeysAndValues field, except if
527      // we end up removing duplicates in a copy of the array.
528      @Nullable Object[] localAlternatingKeysAndValues;
529      int localSize = size;
530      if (valueComparator == null) {
531        localAlternatingKeysAndValues = alternatingKeysAndValues;
532      } else {
533        if (entriesUsed) {
534          alternatingKeysAndValues = Arrays.copyOf(alternatingKeysAndValues, 2 * size);
535        }
536        localAlternatingKeysAndValues = alternatingKeysAndValues;
537        if (!throwIfDuplicateKeys) {
538          // We want to retain only the last-put value for any given key, before sorting.
539          // This could be improved, but orderEntriesByValue is rather rarely used anyway.
540          localAlternatingKeysAndValues = lastEntryForEachKey(localAlternatingKeysAndValues, size);
541          if (localAlternatingKeysAndValues.length < alternatingKeysAndValues.length) {
542            localSize = localAlternatingKeysAndValues.length >>> 1;
543          }
544        }
545        sortEntries(localAlternatingKeysAndValues, localSize, valueComparator);
546      }
547      entriesUsed = true;
548      ImmutableMap<K, V> map =
549          RegularImmutableMap.create(localSize, localAlternatingKeysAndValues, this);
550      if (throwIfDuplicateKeys && duplicateKey != null) {
551        throw duplicateKey.exception();
552      }
553      return map;
554    }
555
556    /**
557     * Returns a newly-created immutable map. The iteration order of the returned map is the order
558     * in which entries were inserted into the builder, unless {@link #orderEntriesByValue} was
559     * called, in which case entries are sorted by value.
560     *
561     * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method
562     * will throw an exception if there are duplicate keys. The {@code build()} method will soon be
563     * deprecated.
564     *
565     * @throws IllegalArgumentException if duplicate keys were added
566     */
567    public ImmutableMap<K, V> build() {
568      return buildOrThrow();
569    }
570
571    /**
572     * Returns a newly-created immutable map, or throws an exception if any key was added more than
573     * once. The iteration order of the returned map is the order in which entries were inserted
574     * into the builder, unless {@link #orderEntriesByValue} was called, in which case entries are
575     * sorted by value.
576     *
577     * @throws IllegalArgumentException if duplicate keys were added
578     * @since 31.0
579     */
580    public ImmutableMap<K, V> buildOrThrow() {
581      return build(true);
582    }
583
584    /**
585     * Returns a newly-created immutable map, using the last value for any key that was added more
586     * than once. The iteration order of the returned map is the order in which entries were
587     * inserted into the builder, unless {@link #orderEntriesByValue} was called, in which case
588     * entries are sorted by value. If a key was added more than once, it appears in iteration order
589     * based on the first time it was added, again unless {@link #orderEntriesByValue} was called.
590     *
591     * <p>In the current implementation, all values associated with a given key are stored in the
592     * {@code Builder} object, even though only one of them will be used in the built map. If there
593     * can be many repeated keys, it may be more space-efficient to use a {@link
594     * java.util.LinkedHashMap LinkedHashMap} and {@link ImmutableMap#copyOf(Map)} rather than
595     * {@code ImmutableMap.Builder}.
596     *
597     * @since 31.1
598     */
599    public ImmutableMap<K, V> buildKeepingLast() {
600      return build(false);
601    }
602
603    static <V> void sortEntries(
604        @Nullable Object[] alternatingKeysAndValues,
605        int size,
606        Comparator<? super V> valueComparator) {
607      @SuppressWarnings({"rawtypes", "unchecked"})
608      Entry<Object, V>[] entries = new Entry[size];
609      for (int i = 0; i < size; i++) {
610        // requireNonNull is safe because the first `2*size` elements have been filled in.
611        Object key = requireNonNull(alternatingKeysAndValues[2 * i]);
612        @SuppressWarnings("unchecked")
613        V value = (V) requireNonNull(alternatingKeysAndValues[2 * i + 1]);
614        entries[i] = new AbstractMap.SimpleImmutableEntry<Object, V>(key, value);
615      }
616      Arrays.sort(
617          entries, 0, size, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
618      for (int i = 0; i < size; i++) {
619        alternatingKeysAndValues[2 * i] = entries[i].getKey();
620        alternatingKeysAndValues[2 * i + 1] = entries[i].getValue();
621      }
622    }
623
624    private @Nullable Object[] lastEntryForEachKey(
625        @Nullable Object[] localAlternatingKeysAndValues, int size) {
626      Set<Object> seenKeys = new HashSet<>();
627      BitSet dups = new BitSet(); // slots that are overridden by a later duplicate key
628      for (int i = size - 1; i >= 0; i--) {
629        Object key = requireNonNull(localAlternatingKeysAndValues[2 * i]);
630        if (!seenKeys.add(key)) {
631          dups.set(i);
632        }
633      }
634      if (dups.isEmpty()) {
635        return localAlternatingKeysAndValues;
636      }
637      Object[] newAlternatingKeysAndValues = new Object[(size - dups.cardinality()) * 2];
638      for (int inI = 0, outI = 0; inI < size * 2; ) {
639        if (dups.get(inI >>> 1)) {
640          inI += 2;
641        } else {
642          newAlternatingKeysAndValues[outI++] =
643              requireNonNull(localAlternatingKeysAndValues[inI++]);
644          newAlternatingKeysAndValues[outI++] =
645              requireNonNull(localAlternatingKeysAndValues[inI++]);
646        }
647      }
648      return newAlternatingKeysAndValues;
649    }
650
651    static final class DuplicateKey {
652      private final Object key;
653      private final Object value1;
654      private final Object value2;
655
656      DuplicateKey(Object key, Object value1, Object value2) {
657        this.key = key;
658        this.value1 = value1;
659        this.value2 = value2;
660      }
661
662      IllegalArgumentException exception() {
663        return new IllegalArgumentException(
664            "Multiple entries with same key: " + key + "=" + value1 + " and " + key + "=" + value2);
665      }
666    }
667  }
668
669  /**
670   * Returns an immutable map containing the same entries as {@code map}. The returned map iterates
671   * over entries in the same order as the {@code entrySet} of the original map. If {@code map}
672   * somehow contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
673   * comparator is not <i>consistent with equals</i>), the results of this method are undefined.
674   *
675   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
676   * safe to do so. The exact circumstances under which a copy will or will not be performed are
677   * undocumented and subject to change.
678   *
679   * @throws NullPointerException if any key or value in {@code map} is null
680   */
681  public static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
682    if ((map instanceof ImmutableMap) && !(map instanceof SortedMap)) {
683      @SuppressWarnings("unchecked") // safe since map is not writable
684      ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
685      if (!kvMap.isPartialView()) {
686        return kvMap;
687      }
688    }
689    return copyOf(map.entrySet());
690  }
691
692  /**
693   * Returns an immutable map containing the specified entries. The returned map iterates over
694   * entries in the same order as the original iterable.
695   *
696   * @throws NullPointerException if any key, value, or entry is null
697   * @throws IllegalArgumentException if two entries have the same key
698   * @since 19.0
699   */
700  @Beta
701  public static <K, V> ImmutableMap<K, V> copyOf(
702      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
703    int initialCapacity =
704        (entries instanceof Collection)
705            ? ((Collection<?>) entries).size()
706            : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
707    ImmutableMap.Builder<K, V> builder = new ImmutableMap.Builder<K, V>(initialCapacity);
708    builder.putAll(entries);
709    return builder.build();
710  }
711
712  static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0];
713
714  abstract static class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> {
715    abstract UnmodifiableIterator<Entry<K, V>> entryIterator();
716
717    @Override
718    ImmutableSet<K> createKeySet() {
719      return new ImmutableMapKeySet<>(this);
720    }
721
722    @Override
723    ImmutableSet<Entry<K, V>> createEntrySet() {
724      class EntrySetImpl extends ImmutableMapEntrySet<K, V> {
725        @Override
726        ImmutableMap<K, V> map() {
727          return IteratorBasedImmutableMap.this;
728        }
729
730        @Override
731        public UnmodifiableIterator<Entry<K, V>> iterator() {
732          return entryIterator();
733        }
734      }
735      return new EntrySetImpl();
736    }
737
738    @Override
739    ImmutableCollection<V> createValues() {
740      return new ImmutableMapValues<>(this);
741    }
742  }
743
744  ImmutableMap() {}
745
746  /**
747   * Guaranteed to throw an exception and leave the map unmodified.
748   *
749   * @throws UnsupportedOperationException always
750   * @deprecated Unsupported operation.
751   */
752  @CanIgnoreReturnValue
753  @Deprecated
754  @Override
755  @DoNotCall("Always throws UnsupportedOperationException")
756  @CheckForNull
757  public final V put(K k, V v) {
758    throw new UnsupportedOperationException();
759  }
760
761  /**
762   * Guaranteed to throw an exception and leave the map unmodified.
763   *
764   * @throws UnsupportedOperationException always
765   * @deprecated Unsupported operation.
766   */
767  @CanIgnoreReturnValue
768  @Deprecated
769  @Override
770  @CheckForNull
771  public final V remove(@CheckForNull Object o) {
772    throw new UnsupportedOperationException();
773  }
774
775  /**
776   * Guaranteed to throw an exception and leave the map unmodified.
777   *
778   * @throws UnsupportedOperationException always
779   * @deprecated Unsupported operation.
780   */
781  @Deprecated
782  @Override
783  @DoNotCall("Always throws UnsupportedOperationException")
784  public final void putAll(Map<? extends K, ? extends V> map) {
785    throw new UnsupportedOperationException();
786  }
787
788  /**
789   * Guaranteed to throw an exception and leave the map unmodified.
790   *
791   * @throws UnsupportedOperationException always
792   * @deprecated Unsupported operation.
793   */
794  @Deprecated
795  @Override
796  @DoNotCall("Always throws UnsupportedOperationException")
797  public final void clear() {
798    throw new UnsupportedOperationException();
799  }
800
801  @Override
802  public boolean isEmpty() {
803    return size() == 0;
804  }
805
806  @Override
807  public boolean containsKey(@CheckForNull Object key) {
808    return get(key) != null;
809  }
810
811  @Override
812  public boolean containsValue(@CheckForNull Object value) {
813    return values().contains(value);
814  }
815
816  // Overriding to mark it Nullable
817  @Override
818  @CheckForNull
819  public abstract V get(@CheckForNull Object key);
820
821  /**
822   * {@inheritDoc}
823   *
824   * <p>See <a
825   * href="https://developer.android.com/reference/java/util/Map.html#getOrDefault%28java.lang.Object,%20V%29">{@code
826   * Map.getOrDefault}</a>.
827   *
828   * @since 23.5 (but since 21.0 in the JRE <a
829   *     href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>).
830   *     Note that API Level 24 users can call this method with any version of Guava.
831   */
832  // @Override under Java 8 / API Level 24
833  @CheckForNull
834  public final V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
835    /*
836     * Even though it's weird to pass a defaultValue that is null, some callers do so. Those who
837     * pass a literal "null" should probably just use `get`, but I would expect other callers to
838     * pass an expression that *might* be null. This could happen with:
839     *
840     * - a `getFooOrDefault(@CheckForNull Foo defaultValue)` method that returns
841     *   `map.getOrDefault(FOO_KEY, defaultValue)`
842     *
843     * - a call that consults a chain of maps, as in `mapA.getOrDefault(key, mapB.getOrDefault(key,
844     *   ...))`
845     *
846     * So it makes sense for the parameter (and thus the return type) to be @CheckForNull.
847     *
848     * Two other points:
849     *
850     * 1. We'll want to use something like @PolyNull once we can make that work for the various
851     * platforms we target.
852     *
853     * 2. Kotlin's Map type has a getOrDefault method that accepts and returns a "plain V," in
854     * contrast to the "V?" type that we're using. As a result, Kotlin sees a conflict between the
855     * nullness annotations in ImmutableMap and those in its own Map type. In response, it considers
856     * the parameter and return type both to be platform types. As a result, Kotlin permits calls
857     * that can lead to NullPointerException. That's unfortunate. But hopefully most Kotlin callers
858     * use `get(key) ?: defaultValue` instead of this method, anyway.
859     */
860    V result = get(key);
861    // TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker.
862    if (result != null) {
863      return result;
864    } else {
865      return defaultValue;
866    }
867  }
868
869  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entrySet;
870
871  /**
872   * Returns an immutable set of the mappings in this map. The iteration order is specified by the
873   * method used to create this map. Typically, this is insertion order.
874   */
875  @Override
876  public ImmutableSet<Entry<K, V>> entrySet() {
877    ImmutableSet<Entry<K, V>> result = entrySet;
878    return (result == null) ? entrySet = createEntrySet() : result;
879  }
880
881  abstract ImmutableSet<Entry<K, V>> createEntrySet();
882
883  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<K> keySet;
884
885  /**
886   * Returns an immutable set of the keys in this map, in the same order that they appear in {@link
887   * #entrySet}.
888   */
889  @Override
890  public ImmutableSet<K> keySet() {
891    ImmutableSet<K> result = keySet;
892    return (result == null) ? keySet = createKeySet() : result;
893  }
894
895  /*
896   * This could have a good default implementation of return new ImmutableKeySet<K, V>(this),
897   * but ProGuard can't figure out how to eliminate that default when RegularImmutableMap
898   * overrides it.
899   */
900  abstract ImmutableSet<K> createKeySet();
901
902  UnmodifiableIterator<K> keyIterator() {
903    final UnmodifiableIterator<Entry<K, V>> entryIterator = entrySet().iterator();
904    return new UnmodifiableIterator<K>() {
905      @Override
906      public boolean hasNext() {
907        return entryIterator.hasNext();
908      }
909
910      @Override
911      public K next() {
912        return entryIterator.next().getKey();
913      }
914    };
915  }
916
917  @LazyInit @RetainedWith @CheckForNull private transient ImmutableCollection<V> values;
918
919  /**
920   * Returns an immutable collection of the values in this map, in the same order that they appear
921   * in {@link #entrySet}.
922   */
923  @Override
924  public ImmutableCollection<V> values() {
925    ImmutableCollection<V> result = values;
926    return (result == null) ? values = createValues() : result;
927  }
928
929  /*
930   * This could have a good default implementation of {@code return new
931   * ImmutableMapValues<K, V>(this)}, but ProGuard can't figure out how to eliminate that default
932   * when RegularImmutableMap overrides it.
933   */
934  abstract ImmutableCollection<V> createValues();
935
936  // cached so that this.multimapView().inverse() only computes inverse once
937  @LazyInit @CheckForNull private transient ImmutableSetMultimap<K, V> multimapView;
938
939  /**
940   * Returns a multimap view of the map.
941   *
942   * @since 14.0
943   */
944  public ImmutableSetMultimap<K, V> asMultimap() {
945    if (isEmpty()) {
946      return ImmutableSetMultimap.of();
947    }
948    ImmutableSetMultimap<K, V> result = multimapView;
949    return (result == null)
950        ? (multimapView =
951            new ImmutableSetMultimap<>(new MapViewOfValuesAsSingletonSets(), size(), null))
952        : result;
953  }
954
955  @WeakOuter
956  private final class MapViewOfValuesAsSingletonSets
957      extends IteratorBasedImmutableMap<K, ImmutableSet<V>> {
958
959    @Override
960    public int size() {
961      return ImmutableMap.this.size();
962    }
963
964    @Override
965    ImmutableSet<K> createKeySet() {
966      return ImmutableMap.this.keySet();
967    }
968
969    @Override
970    public boolean containsKey(@CheckForNull Object key) {
971      return ImmutableMap.this.containsKey(key);
972    }
973
974    @Override
975    @CheckForNull
976    public ImmutableSet<V> get(@CheckForNull Object key) {
977      V outerValue = ImmutableMap.this.get(key);
978      return (outerValue == null) ? null : ImmutableSet.of(outerValue);
979    }
980
981    @Override
982    boolean isPartialView() {
983      return ImmutableMap.this.isPartialView();
984    }
985
986    @Override
987    public int hashCode() {
988      // ImmutableSet.of(value).hashCode() == value.hashCode(), so the hashes are the same
989      return ImmutableMap.this.hashCode();
990    }
991
992    @Override
993    boolean isHashCodeFast() {
994      return ImmutableMap.this.isHashCodeFast();
995    }
996
997    @Override
998    UnmodifiableIterator<Entry<K, ImmutableSet<V>>> entryIterator() {
999      final Iterator<Entry<K, V>> backingIterator = ImmutableMap.this.entrySet().iterator();
1000      return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() {
1001        @Override
1002        public boolean hasNext() {
1003          return backingIterator.hasNext();
1004        }
1005
1006        @Override
1007        public Entry<K, ImmutableSet<V>> next() {
1008          final Entry<K, V> backingEntry = backingIterator.next();
1009          return new AbstractMapEntry<K, ImmutableSet<V>>() {
1010            @Override
1011            public K getKey() {
1012              return backingEntry.getKey();
1013            }
1014
1015            @Override
1016            public ImmutableSet<V> getValue() {
1017              return ImmutableSet.of(backingEntry.getValue());
1018            }
1019          };
1020        }
1021      };
1022    }
1023  }
1024
1025  @Override
1026  public boolean equals(@CheckForNull Object object) {
1027    return Maps.equalsImpl(this, object);
1028  }
1029
1030  abstract boolean isPartialView();
1031
1032  @Override
1033  public int hashCode() {
1034    return Sets.hashCodeImpl(entrySet());
1035  }
1036
1037  boolean isHashCodeFast() {
1038    return false;
1039  }
1040
1041  @Override
1042  public String toString() {
1043    return Maps.toStringImpl(this);
1044  }
1045
1046  /**
1047   * Serialized type for all ImmutableMap instances. It captures the logical contents and they are
1048   * reconstructed using public factory methods. This ensures that the implementation types remain
1049   * as implementation details.
1050   */
1051  static class SerializedForm<K, V> implements Serializable {
1052    // This object retains references to collections returned by keySet() and value(). This saves
1053    // bytes when the both the map and its keySet or value collection are written to the same
1054    // instance of ObjectOutputStream.
1055
1056    // TODO(b/160980469): remove support for the old serialization format after some time
1057    private static final boolean USE_LEGACY_SERIALIZATION = true;
1058
1059    private final Object keys;
1060    private final Object values;
1061
1062    SerializedForm(ImmutableMap<K, V> map) {
1063      if (USE_LEGACY_SERIALIZATION) {
1064        Object[] keys = new Object[map.size()];
1065        Object[] values = new Object[map.size()];
1066        int i = 0;
1067        // "extends Object" works around https://github.com/typetools/checker-framework/issues/3013
1068        for (Entry<? extends Object, ? extends Object> entry : map.entrySet()) {
1069          keys[i] = entry.getKey();
1070          values[i] = entry.getValue();
1071          i++;
1072        }
1073        this.keys = keys;
1074        this.values = values;
1075        return;
1076      }
1077      this.keys = map.keySet();
1078      this.values = map.values();
1079    }
1080
1081    @SuppressWarnings("unchecked")
1082    final Object readResolve() {
1083      if (!(this.keys instanceof ImmutableSet)) {
1084        return legacyReadResolve();
1085      }
1086
1087      ImmutableSet<K> keySet = (ImmutableSet<K>) this.keys;
1088      ImmutableCollection<V> values = (ImmutableCollection<V>) this.values;
1089
1090      Builder<K, V> builder = makeBuilder(keySet.size());
1091
1092      UnmodifiableIterator<K> keyIter = keySet.iterator();
1093      UnmodifiableIterator<V> valueIter = values.iterator();
1094
1095      while (keyIter.hasNext()) {
1096        builder.put(keyIter.next(), valueIter.next());
1097      }
1098
1099      return builder.buildOrThrow();
1100    }
1101
1102    @SuppressWarnings("unchecked")
1103    final Object legacyReadResolve() {
1104      K[] keys = (K[]) this.keys;
1105      V[] values = (V[]) this.values;
1106
1107      Builder<K, V> builder = makeBuilder(keys.length);
1108
1109      for (int i = 0; i < keys.length; i++) {
1110        builder.put(keys[i], values[i]);
1111      }
1112      return builder.buildOrThrow();
1113    }
1114
1115    /**
1116     * Returns a builder that builds the unserialized type. Subclasses should override this method.
1117     */
1118    Builder<K, V> makeBuilder(int size) {
1119      return new Builder<>(size);
1120    }
1121
1122    private static final long serialVersionUID = 0;
1123  }
1124
1125  /**
1126   * Returns a serializable form of this object. Non-public subclasses should not override this
1127   * method. Publicly-accessible subclasses must override this method and should return a subclass
1128   * of SerializedForm whose readResolve() method returns objects of the subclass type.
1129   */
1130  Object writeReplace() {
1131    return new SerializedForm<>(this);
1132  }
1133
1134  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
1135    throw new InvalidObjectException("Use SerializedForm");
1136  }
1137}