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.errorprone.annotations.CanIgnoreReturnValue; 027import com.google.errorprone.annotations.concurrent.LazyInit; 028import com.google.j2objc.annotations.WeakOuter; 029import java.io.Serializable; 030import java.util.AbstractMap; 031import java.util.Arrays; 032import java.util.Collection; 033import java.util.Collections; 034import java.util.Comparator; 035import java.util.Iterator; 036import java.util.Map; 037import java.util.Map.Entry; 038import java.util.SortedMap; 039import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl; 040import org.checkerframework.checker.nullness.compatqual.NullableDecl; 041 042/** 043 * A {@link Map} whose contents will never change, with many other important properties detailed at 044 * {@link ImmutableCollection}. 045 * 046 * <p>See the Guava User Guide article on <a href= 047 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>. 048 * 049 * @author Jesse Wilson 050 * @author Kevin Bourrillion 051 * @since 2.0 052 */ 053@GwtCompatible(serializable = true, emulated = true) 054@SuppressWarnings("serial") // we're overriding default serialization 055public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable { 056 057 /** 058 * Returns the empty map. This map behaves and performs comparably to {@link 059 * Collections#emptyMap}, and is preferable mainly for consistency and maintainability of your 060 * code. 061 */ 062 @SuppressWarnings("unchecked") 063 public static <K, V> ImmutableMap<K, V> of() { 064 return (ImmutableMap<K, V>) RegularImmutableMap.EMPTY; 065 } 066 067 /** 068 * Returns an immutable map containing a single entry. This map behaves and performs comparably to 069 * {@link Collections#singletonMap} but will not accept a null key or value. It is preferable 070 * mainly for consistency and maintainability of your code. 071 */ 072 public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { 073 checkEntryNotNull(k1, v1); 074 return RegularImmutableMap.create(1, new Object[] {k1, v1}); 075 } 076 077 /** 078 * Returns an immutable map containing the given entries, in order. 079 * 080 * @throws IllegalArgumentException if duplicate keys are provided 081 */ 082 public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { 083 checkEntryNotNull(k1, v1); 084 checkEntryNotNull(k2, v2); 085 return RegularImmutableMap.create(2, new Object[] {k1, v1, k2, v2}); 086 } 087 088 /** 089 * Returns an immutable map containing the given entries, in order. 090 * 091 * @throws IllegalArgumentException if duplicate keys are provided 092 */ 093 public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 094 checkEntryNotNull(k1, v1); 095 checkEntryNotNull(k2, v2); 096 checkEntryNotNull(k3, v3); 097 return RegularImmutableMap.create(3, new Object[] {k1, v1, k2, v2, k3, v3}); 098 } 099 100 /** 101 * Returns an immutable map containing the given entries, in order. 102 * 103 * @throws IllegalArgumentException if duplicate keys are provided 104 */ 105 public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 106 checkEntryNotNull(k1, v1); 107 checkEntryNotNull(k2, v2); 108 checkEntryNotNull(k3, v3); 109 checkEntryNotNull(k4, v4); 110 return RegularImmutableMap.create(4, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4}); 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( 119 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 120 checkEntryNotNull(k1, v1); 121 checkEntryNotNull(k2, v2); 122 checkEntryNotNull(k3, v3); 123 checkEntryNotNull(k4, v4); 124 checkEntryNotNull(k5, v5); 125 return RegularImmutableMap.create(5, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5}); 126 } 127 128 // looking for of() with > 5 entries? Use the builder instead. 129 130 /** 131 * Verifies that {@code key} and {@code value} are non-null, and returns a new immutable entry 132 * with those values. 133 * 134 * <p>A call to {@link Entry#setValue} on the returned entry will always throw {@link 135 * UnsupportedOperationException}. 136 */ 137 static <K, V> Entry<K, V> entryOf(K key, V value) { 138 checkEntryNotNull(key, value); 139 return new AbstractMap.SimpleImmutableEntry<>(key, value); 140 } 141 142 /** 143 * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 144 * Builder} constructor. 145 */ 146 public static <K, V> Builder<K, V> builder() { 147 return new Builder<>(); 148 } 149 150 /** 151 * Returns a new builder, expecting the specified number of entries to be added. 152 * 153 * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link 154 * Builder#build} is called, the builder is likely to perform better than an unsized {@link 155 * #builder()} would have. 156 * 157 * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, 158 * but not exactly, the number of entries added to the builder. 159 * 160 * @since 23.1 161 */ 162 @Beta 163 public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) { 164 checkNonnegative(expectedSize, "expectedSize"); 165 return new Builder<>(expectedSize); 166 } 167 168 static void checkNoConflict( 169 boolean safe, String conflictDescription, Entry<?, ?> entry1, Entry<?, ?> entry2) { 170 if (!safe) { 171 throw conflictException(conflictDescription, entry1, entry2); 172 } 173 } 174 175 static IllegalArgumentException conflictException( 176 String conflictDescription, Object entry1, Object entry2) { 177 return new IllegalArgumentException( 178 "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2); 179 } 180 181 /** 182 * A builder for creating immutable map instances, especially {@code public static final} maps 183 * ("constant maps"). Example: 184 * 185 * <pre>{@code 186 * static final ImmutableMap<String, Integer> WORD_TO_INT = 187 * new ImmutableMap.Builder<String, Integer>() 188 * .put("one", 1) 189 * .put("two", 2) 190 * .put("three", 3) 191 * .build(); 192 * }</pre> 193 * 194 * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are even more 195 * convenient. 196 * 197 * <p>By default, a {@code Builder} will generate maps that iterate over entries in the order they 198 * were inserted into the builder, equivalently to {@code LinkedHashMap}. For example, in the 199 * above example, {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the 200 * order {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect 201 * the same order. If you want a different order, consider using {@link ImmutableSortedMap} to 202 * sort by keys, or call {@link #orderEntriesByValue(Comparator)}, which changes this builder to 203 * sort entries by value. 204 * 205 * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build 206 * multiple maps in series. Each map is a superset of the maps created before it. 207 * 208 * @since 2.0 209 */ 210 public static class Builder<K, V> { 211 @MonotonicNonNullDecl Comparator<? super V> valueComparator; 212 Object[] alternatingKeysAndValues; 213 int size; 214 boolean entriesUsed; 215 216 /** 217 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 218 * ImmutableMap#builder}. 219 */ 220 public Builder() { 221 this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); 222 } 223 224 @SuppressWarnings("unchecked") 225 Builder(int initialCapacity) { 226 this.alternatingKeysAndValues = new Object[2 * initialCapacity]; 227 this.size = 0; 228 this.entriesUsed = false; 229 } 230 231 private void ensureCapacity(int minCapacity) { 232 if (minCapacity * 2 > alternatingKeysAndValues.length) { 233 alternatingKeysAndValues = 234 Arrays.copyOf( 235 alternatingKeysAndValues, 236 ImmutableCollection.Builder.expandedCapacity( 237 alternatingKeysAndValues.length, minCapacity * 2)); 238 entriesUsed = false; 239 } 240 } 241 242 /** 243 * Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed, 244 * and will cause {@link #build} to fail. 245 */ 246 @CanIgnoreReturnValue 247 public Builder<K, V> put(K key, V value) { 248 ensureCapacity(size + 1); 249 checkEntryNotNull(key, value); 250 alternatingKeysAndValues[2 * size] = key; 251 alternatingKeysAndValues[2 * size + 1] = value; 252 size++; 253 return this; 254 } 255 256 /** 257 * Adds the given {@code entry} to the map, making it immutable if necessary. Duplicate keys are 258 * not allowed, and will cause {@link #build} to fail. 259 * 260 * @since 11.0 261 */ 262 @CanIgnoreReturnValue 263 public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 264 return put(entry.getKey(), entry.getValue()); 265 } 266 267 /** 268 * Associates all of the given map's keys and values in the built map. Duplicate keys are not 269 * allowed, and will cause {@link #build} to fail. 270 * 271 * @throws NullPointerException if any key or value in {@code map} is null 272 */ 273 @CanIgnoreReturnValue 274 public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { 275 return putAll(map.entrySet()); 276 } 277 278 /** 279 * Adds all of the given entries to the built map. Duplicate keys are not allowed, and will 280 * cause {@link #build} to fail. 281 * 282 * @throws NullPointerException if any key, value, or entry is null 283 * @since 19.0 284 */ 285 @CanIgnoreReturnValue 286 @Beta 287 public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 288 if (entries instanceof Collection) { 289 ensureCapacity(size + ((Collection<?>) entries).size()); 290 } 291 for (Entry<? extends K, ? extends V> entry : entries) { 292 put(entry); 293 } 294 return this; 295 } 296 297 /** 298 * Configures this {@code Builder} to order entries by value according to the specified 299 * comparator. 300 * 301 * <p>The sort order is stable, that is, if two entries have values that compare as equivalent, 302 * the entry that was inserted first will be first in the built map's iteration order. 303 * 304 * @throws IllegalStateException if this method was already called 305 * @since 19.0 306 */ 307 @CanIgnoreReturnValue 308 @Beta 309 public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { 310 checkState(this.valueComparator == null, "valueComparator was already set"); 311 this.valueComparator = checkNotNull(valueComparator, "valueComparator"); 312 return this; 313 } 314 315 /* 316 * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap 317 * versions throw an IllegalStateException instead? 318 */ 319 320 /** 321 * Returns a newly-created immutable map. The iteration order of the returned map is the order 322 * in which entries were inserted into the builder, unless {@link #orderEntriesByValue} was 323 * called, in which case entries are sorted by value. 324 * 325 * @throws IllegalArgumentException if duplicate keys were added 326 */ 327 @SuppressWarnings("unchecked") 328 public ImmutableMap<K, V> build() { 329 /* 330 * If entries is full, then this implementation may end up using the entries array 331 * directly and writing over the entry objects with non-terminal entries, but this is 332 * safe; if this Builder is used further, it will grow the entries array (so it can't 333 * affect the original array), and future build() calls will always copy any entry 334 * objects that cannot be safely reused. 335 */ 336 sortEntries(); 337 entriesUsed = true; 338 return RegularImmutableMap.create(size, alternatingKeysAndValues); 339 } 340 341 void sortEntries() { 342 if (valueComparator != null) { 343 if (entriesUsed) { 344 alternatingKeysAndValues = Arrays.copyOf(alternatingKeysAndValues, 2 * size); 345 } 346 Entry<K, V>[] entries = new Entry[size]; 347 for (int i = 0; i < size; i++) { 348 entries[i] = 349 new AbstractMap.SimpleImmutableEntry<K, V>( 350 (K) alternatingKeysAndValues[2 * i], (V) alternatingKeysAndValues[2 * i + 1]); 351 } 352 Arrays.sort( 353 entries, 0, size, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction())); 354 for (int i = 0; i < size; i++) { 355 alternatingKeysAndValues[2 * i] = entries[i].getKey(); 356 alternatingKeysAndValues[2 * i + 1] = entries[i].getValue(); 357 } 358 } 359 } 360 } 361 362 /** 363 * Returns an immutable map containing the same entries as {@code map}. The returned map iterates 364 * over entries in the same order as the {@code entrySet} of the original map. If {@code map} 365 * somehow contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose 366 * comparator is not <i>consistent with equals</i>), the results of this method are undefined. 367 * 368 * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 369 * safe to do so. The exact circumstances under which a copy will or will not be performed are 370 * undocumented and subject to change. 371 * 372 * @throws NullPointerException if any key or value in {@code map} is null 373 */ 374 public static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V> map) { 375 if ((map instanceof ImmutableMap) && !(map instanceof SortedMap)) { 376 @SuppressWarnings("unchecked") // safe since map is not writable 377 ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map; 378 if (!kvMap.isPartialView()) { 379 return kvMap; 380 } 381 } 382 return copyOf(map.entrySet()); 383 } 384 385 /** 386 * Returns an immutable map containing the specified entries. The returned map iterates over 387 * entries in the same order as the original iterable. 388 * 389 * @throws NullPointerException if any key, value, or entry is null 390 * @throws IllegalArgumentException if two entries have the same key 391 * @since 19.0 392 */ 393 @Beta 394 public static <K, V> ImmutableMap<K, V> copyOf( 395 Iterable<? extends Entry<? extends K, ? extends V>> entries) { 396 int initialCapacity = 397 (entries instanceof Collection) 398 ? ((Collection<?>) entries).size() 399 : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY; 400 ImmutableMap.Builder<K, V> builder = new ImmutableMap.Builder<K, V>(initialCapacity); 401 builder.putAll(entries); 402 return builder.build(); 403 } 404 405 static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0]; 406 407 abstract static class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> { 408 abstract UnmodifiableIterator<Entry<K, V>> entryIterator(); 409 410 @Override 411 ImmutableSet<K> createKeySet() { 412 return new ImmutableMapKeySet<>(this); 413 } 414 415 @Override 416 ImmutableSet<Entry<K, V>> createEntrySet() { 417 @WeakOuter 418 class EntrySetImpl extends ImmutableMapEntrySet<K, V> { 419 @Override 420 ImmutableMap<K, V> map() { 421 return IteratorBasedImmutableMap.this; 422 } 423 424 @Override 425 public UnmodifiableIterator<Entry<K, V>> iterator() { 426 return entryIterator(); 427 } 428 } 429 return new EntrySetImpl(); 430 } 431 432 @Override 433 ImmutableCollection<V> createValues() { 434 return new ImmutableMapValues<>(this); 435 } 436 } 437 438 ImmutableMap() {} 439 440 /** 441 * Guaranteed to throw an exception and leave the map unmodified. 442 * 443 * @throws UnsupportedOperationException always 444 * @deprecated Unsupported operation. 445 */ 446 @CanIgnoreReturnValue 447 @Deprecated 448 @Override 449 public final V put(K k, V v) { 450 throw new UnsupportedOperationException(); 451 } 452 453 /** 454 * Guaranteed to throw an exception and leave the map unmodified. 455 * 456 * @throws UnsupportedOperationException always 457 * @deprecated Unsupported operation. 458 */ 459 @CanIgnoreReturnValue 460 @Deprecated 461 @Override 462 public final V remove(Object o) { 463 throw new UnsupportedOperationException(); 464 } 465 466 /** 467 * Guaranteed to throw an exception and leave the map unmodified. 468 * 469 * @throws UnsupportedOperationException always 470 * @deprecated Unsupported operation. 471 */ 472 @Deprecated 473 @Override 474 public final void putAll(Map<? extends K, ? extends V> map) { 475 throw new UnsupportedOperationException(); 476 } 477 478 /** 479 * Guaranteed to throw an exception and leave the map unmodified. 480 * 481 * @throws UnsupportedOperationException always 482 * @deprecated Unsupported operation. 483 */ 484 @Deprecated 485 @Override 486 public final void clear() { 487 throw new UnsupportedOperationException(); 488 } 489 490 @Override 491 public boolean isEmpty() { 492 return size() == 0; 493 } 494 495 @Override 496 public boolean containsKey(@NullableDecl Object key) { 497 return get(key) != null; 498 } 499 500 @Override 501 public boolean containsValue(@NullableDecl Object value) { 502 return values().contains(value); 503 } 504 505 // Overriding to mark it Nullable 506 @Override 507 public abstract V get(@NullableDecl Object key); 508 509 /** 510 * {@inheritDoc} 511 * 512 * <p>See <a 513 * href="https://developer.android.com/reference/java/util/Map.html#getOrDefault%28java.lang.Object,%20V%29">{@code 514 * Map.getOrDefault}</a>. 515 * 516 * @since 23.5 (but since 21.0 in the JRE <a 517 * href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>). 518 * Note that API Level 24 users can call this method with any version of Guava. 519 */ 520 // @Override under Java 8 / API Level 24 521 public final V getOrDefault(@NullableDecl Object key, @NullableDecl V defaultValue) { 522 V result = get(key); 523 return (result != null) ? result : defaultValue; 524 } 525 526 @LazyInit private transient ImmutableSet<Entry<K, V>> entrySet; 527 528 /** 529 * Returns an immutable set of the mappings in this map. The iteration order is specified by the 530 * method used to create this map. Typically, this is insertion order. 531 */ 532 @Override 533 public ImmutableSet<Entry<K, V>> entrySet() { 534 ImmutableSet<Entry<K, V>> result = entrySet; 535 return (result == null) ? entrySet = createEntrySet() : result; 536 } 537 538 abstract ImmutableSet<Entry<K, V>> createEntrySet(); 539 540 @LazyInit private transient ImmutableSet<K> keySet; 541 542 /** 543 * Returns an immutable set of the keys in this map, in the same order that they appear in {@link 544 * #entrySet}. 545 */ 546 @Override 547 public ImmutableSet<K> keySet() { 548 ImmutableSet<K> result = keySet; 549 return (result == null) ? keySet = createKeySet() : result; 550 } 551 552 /* 553 * This could have a good default implementation of return new ImmutableKeySet<K, V>(this), 554 * but ProGuard can't figure out how to eliminate that default when RegularImmutableMap 555 * overrides it. 556 */ 557 abstract ImmutableSet<K> createKeySet(); 558 559 UnmodifiableIterator<K> keyIterator() { 560 final UnmodifiableIterator<Entry<K, V>> entryIterator = entrySet().iterator(); 561 return new UnmodifiableIterator<K>() { 562 @Override 563 public boolean hasNext() { 564 return entryIterator.hasNext(); 565 } 566 567 @Override 568 public K next() { 569 return entryIterator.next().getKey(); 570 } 571 }; 572 } 573 574 @LazyInit private transient ImmutableCollection<V> values; 575 576 /** 577 * Returns an immutable collection of the values in this map, in the same order that they appear 578 * in {@link #entrySet}. 579 */ 580 @Override 581 public ImmutableCollection<V> values() { 582 ImmutableCollection<V> result = values; 583 return (result == null) ? values = createValues() : result; 584 } 585 586 /* 587 * This could have a good default implementation of {@code return new 588 * ImmutableMapValues<K, V>(this)}, but ProGuard can't figure out how to eliminate that default 589 * when RegularImmutableMap overrides it. 590 */ 591 abstract ImmutableCollection<V> createValues(); 592 593 // cached so that this.multimapView().inverse() only computes inverse once 594 @LazyInit private transient ImmutableSetMultimap<K, V> multimapView; 595 596 /** 597 * Returns a multimap view of the map. 598 * 599 * @since 14.0 600 */ 601 public ImmutableSetMultimap<K, V> asMultimap() { 602 if (isEmpty()) { 603 return ImmutableSetMultimap.of(); 604 } 605 ImmutableSetMultimap<K, V> result = multimapView; 606 return (result == null) 607 ? (multimapView = 608 new ImmutableSetMultimap<>(new MapViewOfValuesAsSingletonSets(), size(), null)) 609 : result; 610 } 611 612 @WeakOuter 613 private final class MapViewOfValuesAsSingletonSets 614 extends IteratorBasedImmutableMap<K, ImmutableSet<V>> { 615 616 @Override 617 public int size() { 618 return ImmutableMap.this.size(); 619 } 620 621 @Override 622 ImmutableSet<K> createKeySet() { 623 return ImmutableMap.this.keySet(); 624 } 625 626 @Override 627 public boolean containsKey(@NullableDecl Object key) { 628 return ImmutableMap.this.containsKey(key); 629 } 630 631 @Override 632 public ImmutableSet<V> get(@NullableDecl Object key) { 633 V outerValue = ImmutableMap.this.get(key); 634 return (outerValue == null) ? null : ImmutableSet.of(outerValue); 635 } 636 637 @Override 638 boolean isPartialView() { 639 return ImmutableMap.this.isPartialView(); 640 } 641 642 @Override 643 public int hashCode() { 644 // ImmutableSet.of(value).hashCode() == value.hashCode(), so the hashes are the same 645 return ImmutableMap.this.hashCode(); 646 } 647 648 @Override 649 boolean isHashCodeFast() { 650 return ImmutableMap.this.isHashCodeFast(); 651 } 652 653 @Override 654 UnmodifiableIterator<Entry<K, ImmutableSet<V>>> entryIterator() { 655 final Iterator<Entry<K, V>> backingIterator = ImmutableMap.this.entrySet().iterator(); 656 return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() { 657 @Override 658 public boolean hasNext() { 659 return backingIterator.hasNext(); 660 } 661 662 @Override 663 public Entry<K, ImmutableSet<V>> next() { 664 final Entry<K, V> backingEntry = backingIterator.next(); 665 return new AbstractMapEntry<K, ImmutableSet<V>>() { 666 @Override 667 public K getKey() { 668 return backingEntry.getKey(); 669 } 670 671 @Override 672 public ImmutableSet<V> getValue() { 673 return ImmutableSet.of(backingEntry.getValue()); 674 } 675 }; 676 } 677 }; 678 } 679 } 680 681 @Override 682 public boolean equals(@NullableDecl Object object) { 683 return Maps.equalsImpl(this, object); 684 } 685 686 abstract boolean isPartialView(); 687 688 @Override 689 public int hashCode() { 690 return Sets.hashCodeImpl(entrySet()); 691 } 692 693 boolean isHashCodeFast() { 694 return false; 695 } 696 697 @Override 698 public String toString() { 699 return Maps.toStringImpl(this); 700 } 701 702 /** 703 * Serialized type for all ImmutableMap instances. It captures the logical contents and they are 704 * reconstructed using public factory methods. This ensures that the implementation types remain 705 * as implementation details. 706 */ 707 static class SerializedForm implements Serializable { 708 private final Object[] keys; 709 private final Object[] values; 710 711 SerializedForm(ImmutableMap<?, ?> map) { 712 keys = new Object[map.size()]; 713 values = new Object[map.size()]; 714 int i = 0; 715 for (Entry<?, ?> entry : map.entrySet()) { 716 keys[i] = entry.getKey(); 717 values[i] = entry.getValue(); 718 i++; 719 } 720 } 721 722 Object readResolve() { 723 Builder<Object, Object> builder = new Builder<>(keys.length); 724 return createMap(builder); 725 } 726 727 Object createMap(Builder<Object, Object> builder) { 728 for (int i = 0; i < keys.length; i++) { 729 builder.put(keys[i], values[i]); 730 } 731 return builder.build(); 732 } 733 734 private static final long serialVersionUID = 0; 735 } 736 737 Object writeReplace() { 738 return new SerializedForm(this); 739 } 740}