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