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