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;
023
024import com.google.common.annotations.Beta;
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.VisibleForTesting;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import com.google.errorprone.annotations.DoNotMock;
029import com.google.errorprone.annotations.concurrent.LazyInit;
030import com.google.j2objc.annotations.RetainedWith;
031import com.google.j2objc.annotations.WeakOuter;
032import java.io.Serializable;
033import java.util.AbstractMap;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.Collections;
037import java.util.Comparator;
038import java.util.EnumMap;
039import java.util.Iterator;
040import java.util.LinkedHashMap;
041import java.util.Map;
042import java.util.SortedMap;
043import java.util.Spliterator;
044import java.util.Spliterators;
045import java.util.function.BiFunction;
046import java.util.function.BinaryOperator;
047import java.util.function.Function;
048import java.util.stream.Collector;
049import java.util.stream.Collectors;
050import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
051import org.checkerframework.checker.nullness.qual.Nullable;
052
053/**
054 * A {@link Map} whose contents will never change, with many other important properties detailed at
055 * {@link ImmutableCollection}.
056 *
057 * <p>See the Guava User Guide article on <a href=
058 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
059 *
060 * @author Jesse Wilson
061 * @author Kevin Bourrillion
062 * @since 2.0
063 */
064@DoNotMock("Use ImmutableMap.of or another implementation")
065@GwtCompatible(serializable = true, emulated = true)
066@SuppressWarnings("serial") // we're overriding default serialization
067public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
068
069  /**
070   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
071   * and values are the result of applying the provided mapping functions to the input elements.
072   * Entries appear in the result {@code ImmutableMap} in encounter order.
073   *
074   * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}, an {@code
075   * IllegalArgumentException} is thrown when the collection operation is performed. (This differs
076   * from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, which
077   * throws an {@code IllegalStateException}.)
078   *
079   * @since 21.0
080   */
081  public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
082      Function<? super T, ? extends K> keyFunction,
083      Function<? super T, ? extends V> valueFunction) {
084    return CollectCollectors.toImmutableMap(keyFunction, valueFunction);
085  }
086
087  /**
088   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
089   * and values are the result of applying the provided mapping functions to the input elements.
090   *
091   * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}), the
092   * values are merged using the specified merging function. Entries will appear in the encounter
093   * order of the first occurrence of the key.
094   *
095   * @since 21.0
096   */
097  public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
098      Function<? super T, ? extends K> keyFunction,
099      Function<? super T, ? extends V> valueFunction,
100      BinaryOperator<V> mergeFunction) {
101    checkNotNull(keyFunction);
102    checkNotNull(valueFunction);
103    checkNotNull(mergeFunction);
104    return Collectors.collectingAndThen(
105        Collectors.toMap(keyFunction, valueFunction, mergeFunction, LinkedHashMap::new),
106        ImmutableMap::copyOf);
107  }
108
109  /**
110   * Returns the empty map. This map behaves and performs comparably to {@link
111   * Collections#emptyMap}, and is preferable mainly for consistency and maintainability of your
112   * code.
113   */
114  @SuppressWarnings("unchecked")
115  public static <K, V> ImmutableMap<K, V> of() {
116    return (ImmutableMap<K, V>) RegularImmutableMap.EMPTY;
117  }
118
119  /**
120   * Returns an immutable map containing a single entry. This map behaves and performs comparably to
121   * {@link Collections#singletonMap} but will not accept a null key or value. It is preferable
122   * mainly for consistency and maintainability of your code.
123   */
124  public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
125    return ImmutableBiMap.of(k1, v1);
126  }
127
128  /**
129   * Returns an immutable map containing the given entries, in order.
130   *
131   * @throws IllegalArgumentException if duplicate keys are provided
132   */
133  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
134    return RegularImmutableMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2));
135  }
136
137  /**
138   * Returns an immutable map containing the given entries, in order.
139   *
140   * @throws IllegalArgumentException if duplicate keys are provided
141   */
142  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
143    return RegularImmutableMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
144  }
145
146  /**
147   * Returns an immutable map containing the given entries, in order.
148   *
149   * @throws IllegalArgumentException if duplicate keys are provided
150   */
151  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
152    return RegularImmutableMap.fromEntries(
153        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
154  }
155
156  /**
157   * Returns an immutable map containing the given entries, in order.
158   *
159   * @throws IllegalArgumentException if duplicate keys are provided
160   */
161  public static <K, V> ImmutableMap<K, V> of(
162      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
163    return RegularImmutableMap.fromEntries(
164        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
165  }
166
167  // looking for of() with > 5 entries? Use the builder instead.
168
169  /**
170   * Verifies that {@code key} and {@code value} are non-null, and returns a new immutable entry
171   * with those values.
172   *
173   * <p>A call to {@link Entry#setValue} on the returned entry will always throw {@link
174   * UnsupportedOperationException}.
175   */
176  static <K, V> Entry<K, V> entryOf(K key, V value) {
177    checkEntryNotNull(key, value);
178    return new AbstractMap.SimpleImmutableEntry<>(key, value);
179  }
180
181  /**
182   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
183   * Builder} constructor.
184   */
185  public static <K, V> Builder<K, V> builder() {
186    return new Builder<>();
187  }
188
189  /**
190   * Returns a new builder, expecting the specified number of entries to be added.
191   *
192   * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
193   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
194   * #builder()} would have.
195   *
196   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
197   * but not exactly, the number of entries added to the builder.
198   *
199   * @since 23.1
200   */
201  @Beta
202  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
203    checkNonnegative(expectedSize, "expectedSize");
204    return new Builder<>(expectedSize);
205  }
206
207  static void checkNoConflict(
208      boolean safe, String conflictDescription, Entry<?, ?> entry1, Entry<?, ?> entry2) {
209    if (!safe) {
210      throw conflictException(conflictDescription, entry1, entry2);
211    }
212  }
213
214  static IllegalArgumentException conflictException(
215      String conflictDescription, Object entry1, Object entry2) {
216    return new IllegalArgumentException(
217        "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2);
218  }
219
220  /**
221   * A builder for creating immutable map instances, especially {@code public static final} maps
222   * ("constant maps"). Example:
223   *
224   * <pre>{@code
225   * static final ImmutableMap<String, Integer> WORD_TO_INT =
226   *     new ImmutableMap.Builder<String, Integer>()
227   *         .put("one", 1)
228   *         .put("two", 2)
229   *         .put("three", 3)
230   *         .build();
231   * }</pre>
232   *
233   * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are even more
234   * convenient.
235   *
236   * <p>By default, a {@code Builder} will generate maps that iterate over entries in the order they
237   * were inserted into the builder, equivalently to {@code LinkedHashMap}. For example, in the
238   * above example, {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the
239   * order {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect
240   * the same order. If you want a different order, consider using {@link ImmutableSortedMap} to
241   * sort by keys, or call {@link #orderEntriesByValue(Comparator)}, which changes this builder to
242   * sort entries by value.
243   *
244   * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build
245   * multiple maps in series. Each map is a superset of the maps created before it.
246   *
247   * @since 2.0
248   */
249  @DoNotMock
250  public static class Builder<K, V> {
251    @MonotonicNonNull Comparator<? super V> valueComparator;
252    Entry<K, V>[] entries;
253    int size;
254    boolean entriesUsed;
255
256    /**
257     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
258     * ImmutableMap#builder}.
259     */
260    public Builder() {
261      this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY);
262    }
263
264    @SuppressWarnings("unchecked")
265    Builder(int initialCapacity) {
266      this.entries = new Entry[initialCapacity];
267      this.size = 0;
268      this.entriesUsed = false;
269    }
270
271    private void ensureCapacity(int minCapacity) {
272      if (minCapacity > entries.length) {
273        entries =
274            Arrays.copyOf(
275                entries, ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity));
276        entriesUsed = false;
277      }
278    }
279
280    /**
281     * Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed,
282     * and will cause {@link #build} to fail.
283     */
284    @CanIgnoreReturnValue
285    public Builder<K, V> put(K key, V value) {
286      ensureCapacity(size + 1);
287      Entry<K, V> entry = entryOf(key, value);
288      // don't inline this: we want to fail atomically if key or value is null
289      entries[size++] = entry;
290      return this;
291    }
292
293    /**
294     * Adds the given {@code entry} to the map, making it immutable if necessary. Duplicate keys are
295     * not allowed, and will cause {@link #build} to fail.
296     *
297     * @since 11.0
298     */
299    @CanIgnoreReturnValue
300    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
301      return put(entry.getKey(), entry.getValue());
302    }
303
304    /**
305     * Associates all of the given map's keys and values in the built map. Duplicate keys are not
306     * allowed, and will cause {@link #build} to fail.
307     *
308     * @throws NullPointerException if any key or value in {@code map} is null
309     */
310    @CanIgnoreReturnValue
311    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
312      return putAll(map.entrySet());
313    }
314
315    /**
316     * Adds all of the given entries to the built map. Duplicate keys are not allowed, and will
317     * cause {@link #build} to fail.
318     *
319     * @throws NullPointerException if any key, value, or entry is null
320     * @since 19.0
321     */
322    @CanIgnoreReturnValue
323    @Beta
324    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
325      if (entries instanceof Collection) {
326        ensureCapacity(size + ((Collection<?>) entries).size());
327      }
328      for (Entry<? extends K, ? extends V> entry : entries) {
329        put(entry);
330      }
331      return this;
332    }
333
334    /**
335     * Configures this {@code Builder} to order entries by value according to the specified
336     * comparator.
337     *
338     * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
339     * the entry that was inserted first will be first in the built map's iteration order.
340     *
341     * @throws IllegalStateException if this method was already called
342     * @since 19.0
343     */
344    @CanIgnoreReturnValue
345    @Beta
346    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
347      checkState(this.valueComparator == null, "valueComparator was already set");
348      this.valueComparator = checkNotNull(valueComparator, "valueComparator");
349      return this;
350    }
351
352    @CanIgnoreReturnValue
353    Builder<K, V> combine(Builder<K, V> other) {
354      checkNotNull(other);
355      ensureCapacity(this.size + other.size);
356      System.arraycopy(other.entries, 0, this.entries, this.size, other.size);
357      this.size += other.size;
358      return this;
359    }
360
361    /*
362     * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap
363     * versions throw an IllegalStateException instead?
364     */
365
366    /**
367     * Returns a newly-created immutable map. The iteration order of the returned map is the order
368     * in which entries were inserted into the builder, unless {@link #orderEntriesByValue} was
369     * called, in which case entries are sorted by value.
370     *
371     * @throws IllegalArgumentException if duplicate keys were added
372     */
373    public ImmutableMap<K, V> build() {
374      /*
375       * If entries is full, or if hash flooding is detected, then this implementation may end up
376       * using the entries array directly and writing over the entry objects with non-terminal
377       * entries, but this is safe; if this Builder is used further, it will grow the entries array
378       * (so it can't affect the original array), and future build() calls will always copy any
379       * entry objects that cannot be safely reused.
380       */
381      if (valueComparator != null) {
382        if (entriesUsed) {
383          entries = Arrays.copyOf(entries, size);
384        }
385        Arrays.sort(
386            entries, 0, size, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
387      }
388      switch (size) {
389        case 0:
390          return of();
391        case 1:
392          return of(entries[0].getKey(), entries[0].getValue());
393        default:
394          entriesUsed = true;
395          return RegularImmutableMap.fromEntryArray(size, entries);
396      }
397    }
398
399    @VisibleForTesting // only for testing JDK backed implementation
400    ImmutableMap<K, V> buildJdkBacked() {
401      checkState(
402          valueComparator == null, "buildJdkBacked is only for testing; can't use valueComparator");
403      switch (size) {
404        case 0:
405          return of();
406        case 1:
407          return of(entries[0].getKey(), entries[0].getValue());
408        default:
409          entriesUsed = true;
410          return JdkBackedImmutableMap.create(size, entries);
411      }
412    }
413  }
414
415  /**
416   * Returns an immutable map containing the same entries as {@code map}. The returned map iterates
417   * over entries in the same order as the {@code entrySet} of the original map. If {@code map}
418   * somehow contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
419   * comparator is not <i>consistent with equals</i>), the results of this method are undefined.
420   *
421   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
422   * safe to do so. The exact circumstances under which a copy will or will not be performed are
423   * undocumented and subject to change.
424   *
425   * @throws NullPointerException if any key or value in {@code map} is null
426   */
427  public static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
428    if ((map instanceof ImmutableMap) && !(map instanceof SortedMap)) {
429      @SuppressWarnings("unchecked") // safe since map is not writable
430      ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
431      if (!kvMap.isPartialView()) {
432        return kvMap;
433      }
434    } else if (map instanceof EnumMap) {
435      @SuppressWarnings("unchecked") // safe since map is not writable
436      ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) copyOfEnumMap((EnumMap<?, ?>) map);
437      return kvMap;
438    }
439    return copyOf(map.entrySet());
440  }
441
442  /**
443   * Returns an immutable map containing the specified entries. The returned map iterates over
444   * entries in the same order as the original iterable.
445   *
446   * @throws NullPointerException if any key, value, or entry is null
447   * @throws IllegalArgumentException if two entries have the same key
448   * @since 19.0
449   */
450  @Beta
451  public static <K, V> ImmutableMap<K, V> copyOf(
452      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
453    @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
454    Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
455    switch (entryArray.length) {
456      case 0:
457        return of();
458      case 1:
459        Entry<K, V> onlyEntry = entryArray[0];
460        return of(onlyEntry.getKey(), onlyEntry.getValue());
461      default:
462        /*
463         * The current implementation will end up using entryArray directly, though it will write
464         * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray.
465         */
466        return RegularImmutableMap.fromEntries(entryArray);
467    }
468  }
469
470  private static <K extends Enum<K>, V> ImmutableMap<K, V> copyOfEnumMap(
471      EnumMap<K, ? extends V> original) {
472    EnumMap<K, V> copy = new EnumMap<>(original);
473    for (Entry<?, ?> entry : copy.entrySet()) {
474      checkEntryNotNull(entry.getKey(), entry.getValue());
475    }
476    return ImmutableEnumMap.asImmutable(copy);
477  }
478
479  static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0];
480
481  abstract static class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> {
482    abstract UnmodifiableIterator<Entry<K, V>> entryIterator();
483
484    Spliterator<Entry<K, V>> entrySpliterator() {
485      return Spliterators.spliterator(
486          entryIterator(),
487          size(),
488          Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.IMMUTABLE | Spliterator.ORDERED);
489    }
490
491    @Override
492    ImmutableSet<K> createKeySet() {
493      return new ImmutableMapKeySet<>(this);
494    }
495
496    @Override
497    ImmutableSet<Entry<K, V>> createEntrySet() {
498      class EntrySetImpl extends ImmutableMapEntrySet<K, V> {
499        @Override
500        ImmutableMap<K, V> map() {
501          return IteratorBasedImmutableMap.this;
502        }
503
504        @Override
505        public UnmodifiableIterator<Entry<K, V>> iterator() {
506          return entryIterator();
507        }
508      }
509      return new EntrySetImpl();
510    }
511
512    @Override
513    ImmutableCollection<V> createValues() {
514      return new ImmutableMapValues<>(this);
515    }
516  }
517
518  ImmutableMap() {}
519
520  /**
521   * Guaranteed to throw an exception and leave the map unmodified.
522   *
523   * @throws UnsupportedOperationException always
524   * @deprecated Unsupported operation.
525   */
526  @CanIgnoreReturnValue
527  @Deprecated
528  @Override
529  public final V put(K k, V v) {
530    throw new UnsupportedOperationException();
531  }
532
533  /**
534   * Guaranteed to throw an exception and leave the map unmodified.
535   *
536   * @throws UnsupportedOperationException always
537   * @deprecated Unsupported operation.
538   */
539  @CanIgnoreReturnValue
540  @Deprecated
541  @Override
542  public final V putIfAbsent(K key, V value) {
543    throw new UnsupportedOperationException();
544  }
545
546  /**
547   * Guaranteed to throw an exception and leave the map unmodified.
548   *
549   * @throws UnsupportedOperationException always
550   * @deprecated Unsupported operation.
551   */
552  @Deprecated
553  @Override
554  public final boolean replace(K key, V oldValue, V newValue) {
555    throw new UnsupportedOperationException();
556  }
557
558  /**
559   * Guaranteed to throw an exception and leave the map unmodified.
560   *
561   * @throws UnsupportedOperationException always
562   * @deprecated Unsupported operation.
563   */
564  @Deprecated
565  @Override
566  public final V replace(K key, V value) {
567    throw new UnsupportedOperationException();
568  }
569
570  /**
571   * Guaranteed to throw an exception and leave the map unmodified.
572   *
573   * @throws UnsupportedOperationException always
574   * @deprecated Unsupported operation.
575   */
576  @Deprecated
577  @Override
578  public final V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
579    throw new UnsupportedOperationException();
580  }
581
582  /**
583   * Guaranteed to throw an exception and leave the map unmodified.
584   *
585   * @throws UnsupportedOperationException always
586   * @deprecated Unsupported operation.
587   */
588  @Deprecated
589  @Override
590  public final V computeIfPresent(
591      K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
592    throw new UnsupportedOperationException();
593  }
594
595  /**
596   * Guaranteed to throw an exception and leave the map unmodified.
597   *
598   * @throws UnsupportedOperationException always
599   * @deprecated Unsupported operation.
600   */
601  @Deprecated
602  @Override
603  public final V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
604    throw new UnsupportedOperationException();
605  }
606
607  /**
608   * Guaranteed to throw an exception and leave the map unmodified.
609   *
610   * @throws UnsupportedOperationException always
611   * @deprecated Unsupported operation.
612   */
613  @Deprecated
614  @Override
615  public final V merge(
616      K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
617    throw new UnsupportedOperationException();
618  }
619
620  /**
621   * Guaranteed to throw an exception and leave the map unmodified.
622   *
623   * @throws UnsupportedOperationException always
624   * @deprecated Unsupported operation.
625   */
626  @Deprecated
627  @Override
628  public final void putAll(Map<? extends K, ? extends V> map) {
629    throw new UnsupportedOperationException();
630  }
631
632  /**
633   * Guaranteed to throw an exception and leave the map unmodified.
634   *
635   * @throws UnsupportedOperationException always
636   * @deprecated Unsupported operation.
637   */
638  @Deprecated
639  @Override
640  public final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
641    throw new UnsupportedOperationException();
642  }
643
644  /**
645   * Guaranteed to throw an exception and leave the map unmodified.
646   *
647   * @throws UnsupportedOperationException always
648   * @deprecated Unsupported operation.
649   */
650  @Deprecated
651  @Override
652  public final V remove(Object o) {
653    throw new UnsupportedOperationException();
654  }
655
656  /**
657   * Guaranteed to throw an exception and leave the map unmodified.
658   *
659   * @throws UnsupportedOperationException always
660   * @deprecated Unsupported operation.
661   */
662  @Deprecated
663  @Override
664  public final boolean remove(Object key, Object value) {
665    throw new UnsupportedOperationException();
666  }
667
668  /**
669   * Guaranteed to throw an exception and leave the map unmodified.
670   *
671   * @throws UnsupportedOperationException always
672   * @deprecated Unsupported operation.
673   */
674  @Deprecated
675  @Override
676  public final void clear() {
677    throw new UnsupportedOperationException();
678  }
679
680  @Override
681  public boolean isEmpty() {
682    return size() == 0;
683  }
684
685  @Override
686  public boolean containsKey(@Nullable Object key) {
687    return get(key) != null;
688  }
689
690  @Override
691  public boolean containsValue(@Nullable Object value) {
692    return values().contains(value);
693  }
694
695  // Overriding to mark it Nullable
696  @Override
697  public abstract V get(@Nullable Object key);
698
699  /**
700   * @since 21.0 (but only since 23.5 in the Android <a
701   *     href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>).
702   *     Note, however, that Java 8 users can call this method with any version and flavor of Guava.
703   */
704  @Override
705  public final V getOrDefault(@Nullable Object key, @Nullable V defaultValue) {
706    V result = get(key);
707    return (result != null) ? result : defaultValue;
708  }
709
710  @LazyInit @RetainedWith private transient ImmutableSet<Entry<K, V>> entrySet;
711
712  /**
713   * Returns an immutable set of the mappings in this map. The iteration order is specified by the
714   * method used to create this map. Typically, this is insertion order.
715   */
716  @Override
717  public ImmutableSet<Entry<K, V>> entrySet() {
718    ImmutableSet<Entry<K, V>> result = entrySet;
719    return (result == null) ? entrySet = createEntrySet() : result;
720  }
721
722  abstract ImmutableSet<Entry<K, V>> createEntrySet();
723
724  @LazyInit @RetainedWith private transient ImmutableSet<K> keySet;
725
726  /**
727   * Returns an immutable set of the keys in this map, in the same order that they appear in {@link
728   * #entrySet}.
729   */
730  @Override
731  public ImmutableSet<K> keySet() {
732    ImmutableSet<K> result = keySet;
733    return (result == null) ? keySet = createKeySet() : result;
734  }
735
736  /*
737   * This could have a good default implementation of return new ImmutableKeySet<K, V>(this),
738   * but ProGuard can't figure out how to eliminate that default when RegularImmutableMap
739   * overrides it.
740   */
741  abstract ImmutableSet<K> createKeySet();
742
743  UnmodifiableIterator<K> keyIterator() {
744    final UnmodifiableIterator<Entry<K, V>> entryIterator = entrySet().iterator();
745    return new UnmodifiableIterator<K>() {
746      @Override
747      public boolean hasNext() {
748        return entryIterator.hasNext();
749      }
750
751      @Override
752      public K next() {
753        return entryIterator.next().getKey();
754      }
755    };
756  }
757
758  Spliterator<K> keySpliterator() {
759    return CollectSpliterators.map(entrySet().spliterator(), Entry::getKey);
760  }
761
762  @LazyInit @RetainedWith private transient ImmutableCollection<V> values;
763
764  /**
765   * Returns an immutable collection of the values in this map, in the same order that they appear
766   * in {@link #entrySet}.
767   */
768  @Override
769  public ImmutableCollection<V> values() {
770    ImmutableCollection<V> result = values;
771    return (result == null) ? values = createValues() : result;
772  }
773
774  /*
775   * This could have a good default implementation of {@code return new
776   * ImmutableMapValues<K, V>(this)}, but ProGuard can't figure out how to eliminate that default
777   * when RegularImmutableMap overrides it.
778   */
779  abstract ImmutableCollection<V> createValues();
780
781  // cached so that this.multimapView().inverse() only computes inverse once
782  @LazyInit private transient ImmutableSetMultimap<K, V> multimapView;
783
784  /**
785   * Returns a multimap view of the map.
786   *
787   * @since 14.0
788   */
789  public ImmutableSetMultimap<K, V> asMultimap() {
790    if (isEmpty()) {
791      return ImmutableSetMultimap.of();
792    }
793    ImmutableSetMultimap<K, V> result = multimapView;
794    return (result == null)
795        ? (multimapView =
796            new ImmutableSetMultimap<>(new MapViewOfValuesAsSingletonSets(), size(), null))
797        : result;
798  }
799
800  @WeakOuter
801  private final class MapViewOfValuesAsSingletonSets
802      extends IteratorBasedImmutableMap<K, ImmutableSet<V>> {
803
804    @Override
805    public int size() {
806      return ImmutableMap.this.size();
807    }
808
809    @Override
810    ImmutableSet<K> createKeySet() {
811      return ImmutableMap.this.keySet();
812    }
813
814    @Override
815    public boolean containsKey(@Nullable Object key) {
816      return ImmutableMap.this.containsKey(key);
817    }
818
819    @Override
820    public ImmutableSet<V> get(@Nullable Object key) {
821      V outerValue = ImmutableMap.this.get(key);
822      return (outerValue == null) ? null : ImmutableSet.of(outerValue);
823    }
824
825    @Override
826    boolean isPartialView() {
827      return ImmutableMap.this.isPartialView();
828    }
829
830    @Override
831    public int hashCode() {
832      // ImmutableSet.of(value).hashCode() == value.hashCode(), so the hashes are the same
833      return ImmutableMap.this.hashCode();
834    }
835
836    @Override
837    boolean isHashCodeFast() {
838      return ImmutableMap.this.isHashCodeFast();
839    }
840
841    @Override
842    UnmodifiableIterator<Entry<K, ImmutableSet<V>>> entryIterator() {
843      final Iterator<Entry<K, V>> backingIterator = ImmutableMap.this.entrySet().iterator();
844      return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() {
845        @Override
846        public boolean hasNext() {
847          return backingIterator.hasNext();
848        }
849
850        @Override
851        public Entry<K, ImmutableSet<V>> next() {
852          final Entry<K, V> backingEntry = backingIterator.next();
853          return new AbstractMapEntry<K, ImmutableSet<V>>() {
854            @Override
855            public K getKey() {
856              return backingEntry.getKey();
857            }
858
859            @Override
860            public ImmutableSet<V> getValue() {
861              return ImmutableSet.of(backingEntry.getValue());
862            }
863          };
864        }
865      };
866    }
867  }
868
869  @Override
870  public boolean equals(@Nullable Object object) {
871    return Maps.equalsImpl(this, object);
872  }
873
874  abstract boolean isPartialView();
875
876  @Override
877  public int hashCode() {
878    return Sets.hashCodeImpl(entrySet());
879  }
880
881  boolean isHashCodeFast() {
882    return false;
883  }
884
885  @Override
886  public String toString() {
887    return Maps.toStringImpl(this);
888  }
889
890  /**
891   * Serialized type for all ImmutableMap instances. It captures the logical contents and they are
892   * reconstructed using public factory methods. This ensures that the implementation types remain
893   * as implementation details.
894   */
895  static class SerializedForm implements Serializable {
896    private final Object[] keys;
897    private final Object[] values;
898
899    SerializedForm(ImmutableMap<?, ?> map) {
900      keys = new Object[map.size()];
901      values = new Object[map.size()];
902      int i = 0;
903      for (Entry<?, ?> entry : map.entrySet()) {
904        keys[i] = entry.getKey();
905        values[i] = entry.getValue();
906        i++;
907      }
908    }
909
910    Object readResolve() {
911      Builder<Object, Object> builder = new Builder<>(keys.length);
912      return createMap(builder);
913    }
914
915    Object createMap(Builder<Object, Object> builder) {
916      for (int i = 0; i < keys.length; i++) {
917        builder.put(keys[i], values[i]);
918      }
919      return builder.build();
920    }
921
922    private static final long serialVersionUID = 0;
923  }
924
925  Object writeReplace() {
926    return new SerializedForm(this);
927  }
928}