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