001/*
002 * Copyright (C) 2009 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;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.MoreObjects;
025import com.google.common.base.Preconditions;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import com.google.errorprone.annotations.concurrent.LazyInit;
028import com.google.j2objc.annotations.RetainedWith;
029import com.google.j2objc.annotations.Weak;
030import java.io.IOException;
031import java.io.InvalidObjectException;
032import java.io.ObjectInputStream;
033import java.io.ObjectOutputStream;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.Comparator;
037import java.util.Map;
038import java.util.Map.Entry;
039import java.util.function.Function;
040import java.util.stream.Collector;
041import java.util.stream.Collectors;
042import java.util.stream.Stream;
043import org.checkerframework.checker.nullness.qual.Nullable;
044
045/**
046 * A {@link SetMultimap} whose contents will never change, with many other important properties
047 * detailed at {@link ImmutableCollection}.
048 *
049 * <p>See the Guava User Guide article on <a href=
050 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
051 *
052 * @author Mike Ward
053 * @since 2.0
054 */
055@GwtCompatible(serializable = true, emulated = true)
056public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
057    implements SetMultimap<K, V> {
058  /**
059   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap}
060   * whose keys and values are the result of applying the provided mapping functions to the input
061   * elements.
062   *
063   * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link
064   * java.util.stream} Javadoc), that order is preserved, but entries are <a
065   * href="ImmutableMultimap.html#iteration">grouped by key</a>.
066   *
067   * <p>Example:
068   *
069   * <pre>{@code
070   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
071   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
072   *         .collect(toImmutableSetMultimap(str -> str.charAt(0), str -> str.substring(1)));
073   *
074   * // is equivalent to
075   *
076   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
077   *     new ImmutableSetMultimap.Builder<Character, String>()
078   *         .put('b', "anana")
079   *         .putAll('a', "pple", "sparagus")
080   *         .putAll('c', "arrot", "herry")
081   *         .build();
082   * }</pre>
083   *
084   * @since 21.0
085   */
086  public static <T, K, V> Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(
087      Function<? super T, ? extends K> keyFunction,
088      Function<? super T, ? extends V> valueFunction) {
089    checkNotNull(keyFunction, "keyFunction");
090    checkNotNull(valueFunction, "valueFunction");
091    return Collector.of(
092        ImmutableSetMultimap::<K, V>builder,
093        (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)),
094        ImmutableSetMultimap.Builder::combine,
095        ImmutableSetMultimap.Builder::build);
096  }
097
098  /**
099   * Returns a {@code Collector} accumulating entries into an {@code ImmutableSetMultimap}. Each
100   * input element is mapped to a key and a stream of values, each of which are put into the
101   * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the
102   * streams of values.
103   *
104   * <p>Example:
105   *
106   * <pre>{@code
107   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
108   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
109   *         .collect(
110   *             flatteningToImmutableSetMultimap(
111   *                  str -> str.charAt(0),
112   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
113   *
114   * // is equivalent to
115   *
116   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
117   *     ImmutableSetMultimap.<Character, Character>builder()
118   *         .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'))
119   *         .putAll('a', Arrays.asList('p', 'p', 'l', 'e'))
120   *         .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'))
121   *         .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'))
122   *         .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'))
123   *         .build();
124   *
125   * // after deduplication, the resulting multimap is equivalent to
126   *
127   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
128   *     ImmutableSetMultimap.<Character, Character>builder()
129   *         .putAll('b', Arrays.asList('a', 'n'))
130   *         .putAll('a', Arrays.asList('p', 'l', 'e', 's', 'a', 'r', 'g', 'u'))
131   *         .putAll('c', Arrays.asList('a', 'r', 'o', 't', 'h', 'e', 'y'))
132   *         .build();
133   * }
134   * }</pre>
135   *
136   * @since 21.0
137   */
138  public static <T, K, V>
139      Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap(
140          Function<? super T, ? extends K> keyFunction,
141          Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
142    checkNotNull(keyFunction);
143    checkNotNull(valuesFunction);
144    return Collectors.collectingAndThen(
145        Multimaps.flatteningToMultimap(
146            input -> checkNotNull(keyFunction.apply(input)),
147            input -> valuesFunction.apply(input).peek(Preconditions::checkNotNull),
148            MultimapBuilder.linkedHashKeys().linkedHashSetValues()::<K, V>build),
149        ImmutableSetMultimap::copyOf);
150  }
151
152  /** Returns the empty multimap. */
153  // Casting is safe because the multimap will never hold any elements.
154  @SuppressWarnings("unchecked")
155  public static <K, V> ImmutableSetMultimap<K, V> of() {
156    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
157  }
158
159  /** Returns an immutable multimap containing a single entry. */
160  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
161    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
162    builder.put(k1, v1);
163    return builder.build();
164  }
165
166  /**
167   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
168   * an entry (according to {@link Object#equals}) after the first are ignored.
169   */
170  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
171    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
172    builder.put(k1, v1);
173    builder.put(k2, v2);
174    return builder.build();
175  }
176
177  /**
178   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
179   * an entry (according to {@link Object#equals}) after the first are ignored.
180   */
181  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
182    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
183    builder.put(k1, v1);
184    builder.put(k2, v2);
185    builder.put(k3, v3);
186    return builder.build();
187  }
188
189  /**
190   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
191   * an entry (according to {@link Object#equals}) after the first are ignored.
192   */
193  public static <K, V> ImmutableSetMultimap<K, V> of(
194      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
195    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
196    builder.put(k1, v1);
197    builder.put(k2, v2);
198    builder.put(k3, v3);
199    builder.put(k4, v4);
200    return builder.build();
201  }
202
203  /**
204   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
205   * an entry (according to {@link Object#equals}) after the first are ignored.
206   */
207  public static <K, V> ImmutableSetMultimap<K, V> of(
208      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
209    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
210    builder.put(k1, v1);
211    builder.put(k2, v2);
212    builder.put(k3, v3);
213    builder.put(k4, v4);
214    builder.put(k5, v5);
215    return builder.build();
216  }
217
218  // looking for of() with > 5 entries? Use the builder instead.
219
220  /** Returns a new {@link Builder}. */
221  public static <K, V> Builder<K, V> builder() {
222    return new Builder<>();
223  }
224
225  /**
226   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
227   * final} multimaps ("constant multimaps"). Example:
228   *
229   * <pre>{@code
230   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
231   *     new ImmutableSetMultimap.Builder<String, Integer>()
232   *         .put("one", 1)
233   *         .putAll("several", 1, 2, 3)
234   *         .putAll("many", 1, 2, 3, 4, 5)
235   *         .build();
236   * }</pre>
237   *
238   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
239   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
240   * created multimaps.
241   *
242   * @since 2.0
243   */
244  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
245    /**
246     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
247     * ImmutableSetMultimap#builder}.
248     */
249    public Builder() {
250      super();
251    }
252
253    @Override
254    Collection<V> newMutableValueCollection() {
255      return Platform.preservesInsertionOrderOnAddsSet();
256    }
257
258    /** Adds a key-value mapping to the built multimap if it is not already present. */
259    @CanIgnoreReturnValue
260    @Override
261    public Builder<K, V> put(K key, V value) {
262      super.put(key, value);
263      return this;
264    }
265
266    /**
267     * Adds an entry to the built multimap if it is not already present.
268     *
269     * @since 11.0
270     */
271    @CanIgnoreReturnValue
272    @Override
273    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
274      super.put(entry);
275      return this;
276    }
277
278    /**
279     * {@inheritDoc}
280     *
281     * @since 19.0
282     */
283    @CanIgnoreReturnValue
284    @Beta
285    @Override
286    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
287      super.putAll(entries);
288      return this;
289    }
290
291    @CanIgnoreReturnValue
292    @Override
293    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
294      super.putAll(key, values);
295      return this;
296    }
297
298    @CanIgnoreReturnValue
299    @Override
300    public Builder<K, V> putAll(K key, V... values) {
301      return putAll(key, Arrays.asList(values));
302    }
303
304    @CanIgnoreReturnValue
305    @Override
306    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
307      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
308          multimap.asMap().entrySet()) {
309        putAll(entry.getKey(), entry.getValue());
310      }
311      return this;
312    }
313
314    @CanIgnoreReturnValue
315    @Override
316    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
317      super.combine(other);
318      return this;
319    }
320
321    /**
322     * {@inheritDoc}
323     *
324     * @since 8.0
325     */
326    @CanIgnoreReturnValue
327    @Override
328    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
329      super.orderKeysBy(keyComparator);
330      return this;
331    }
332
333    /**
334     * Specifies the ordering of the generated multimap's values for each key.
335     *
336     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
337     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
338     * However, serialization does not preserve that property, though it does maintain the key and
339     * value ordering.
340     *
341     * @since 8.0
342     */
343    // TODO: Make serialization behavior consistent.
344    @CanIgnoreReturnValue
345    @Override
346    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
347      super.orderValuesBy(valueComparator);
348      return this;
349    }
350
351    /** Returns a newly-created immutable set multimap. */
352    @Override
353    public ImmutableSetMultimap<K, V> build() {
354      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
355      if (keyComparator != null) {
356        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
357      }
358      return fromMapEntries(mapEntries, valueComparator);
359    }
360  }
361
362  /**
363   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
364   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
365   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
366   * ignored.
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 multimap} is null
373   */
374  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
375      Multimap<? extends K, ? extends V> multimap) {
376    return copyOf(multimap, null);
377  }
378
379  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
380      Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) {
381    checkNotNull(multimap); // eager for GWT
382    if (multimap.isEmpty() && valueComparator == null) {
383      return of();
384    }
385
386    if (multimap instanceof ImmutableSetMultimap) {
387      @SuppressWarnings("unchecked") // safe since multimap is not writable
388      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
389      if (!kvMultimap.isPartialView()) {
390        return kvMultimap;
391      }
392    }
393
394    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
395  }
396
397  /**
398   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
399   * over keys in the order they were first encountered in the input, and the values for each key
400   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
401   * Object#equals equal}, the first value encountered is used.
402   *
403   * @throws NullPointerException if any key, value, or entry is null
404   * @since 19.0
405   */
406  @Beta
407  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
408      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
409    return new Builder<K, V>().putAll(entries).build();
410  }
411
412  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
413  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
414      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
415      @Nullable Comparator<? super V> valueComparator) {
416    if (mapEntries.isEmpty()) {
417      return of();
418    }
419    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
420        new ImmutableMap.Builder<>(mapEntries.size());
421    int size = 0;
422
423    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
424      K key = entry.getKey();
425      Collection<? extends V> values = entry.getValue();
426      ImmutableSet<V> set = valueSet(valueComparator, values);
427      if (!set.isEmpty()) {
428        builder.put(key, set);
429        size += set.size();
430      }
431    }
432
433    return new ImmutableSetMultimap<>(builder.build(), size, valueComparator);
434  }
435
436  /**
437   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
438   * values.
439   */
440  private final transient ImmutableSet<V> emptySet;
441
442  ImmutableSetMultimap(
443      ImmutableMap<K, ImmutableSet<V>> map,
444      int size,
445      @Nullable Comparator<? super V> valueComparator) {
446    super(map, size);
447    this.emptySet = emptySet(valueComparator);
448  }
449
450  // views
451
452  /**
453   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
454   * the provided key, an empty immutable set is returned. The values are in the same order as the
455   * parameters used to build this multimap.
456   */
457  @Override
458  public ImmutableSet<V> get(@Nullable K key) {
459    // This cast is safe as its type is known in constructor.
460    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
461    return MoreObjects.firstNonNull(set, emptySet);
462  }
463
464  @LazyInit @RetainedWith private transient @Nullable ImmutableSetMultimap<V, K> inverse;
465
466  /**
467   * {@inheritDoc}
468   *
469   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
470   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
471   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
472   */
473  @Override
474  public ImmutableSetMultimap<V, K> inverse() {
475    ImmutableSetMultimap<V, K> result = inverse;
476    return (result == null) ? (inverse = invert()) : result;
477  }
478
479  private ImmutableSetMultimap<V, K> invert() {
480    Builder<V, K> builder = builder();
481    for (Entry<K, V> entry : entries()) {
482      builder.put(entry.getValue(), entry.getKey());
483    }
484    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
485    invertedMultimap.inverse = this;
486    return invertedMultimap;
487  }
488
489  /**
490   * Guaranteed to throw an exception and leave the multimap unmodified.
491   *
492   * @throws UnsupportedOperationException always
493   * @deprecated Unsupported operation.
494   */
495  @CanIgnoreReturnValue
496  @Deprecated
497  @Override
498  public ImmutableSet<V> removeAll(Object key) {
499    throw new UnsupportedOperationException();
500  }
501
502  /**
503   * Guaranteed to throw an exception and leave the multimap unmodified.
504   *
505   * @throws UnsupportedOperationException always
506   * @deprecated Unsupported operation.
507   */
508  @CanIgnoreReturnValue
509  @Deprecated
510  @Override
511  public ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
512    throw new UnsupportedOperationException();
513  }
514
515  @LazyInit @RetainedWith private transient @Nullable ImmutableSet<Entry<K, V>> entries;
516
517  /**
518   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
519   * the values for the first key, the values for the second key, and so on.
520   */
521  @Override
522  public ImmutableSet<Entry<K, V>> entries() {
523    ImmutableSet<Entry<K, V>> result = entries;
524    return result == null ? (entries = new EntrySet<>(this)) : result;
525  }
526
527  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
528    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
529
530    EntrySet(ImmutableSetMultimap<K, V> multimap) {
531      this.multimap = multimap;
532    }
533
534    @Override
535    public boolean contains(@Nullable Object object) {
536      if (object instanceof Entry) {
537        Entry<?, ?> entry = (Entry<?, ?>) object;
538        return multimap.containsEntry(entry.getKey(), entry.getValue());
539      }
540      return false;
541    }
542
543    @Override
544    public int size() {
545      return multimap.size();
546    }
547
548    @Override
549    public UnmodifiableIterator<Entry<K, V>> iterator() {
550      return multimap.entryIterator();
551    }
552
553    @Override
554    boolean isPartialView() {
555      return false;
556    }
557  }
558
559  private static <V> ImmutableSet<V> valueSet(
560      @Nullable Comparator<? super V> valueComparator, Collection<? extends V> values) {
561    return (valueComparator == null)
562        ? ImmutableSet.copyOf(values)
563        : ImmutableSortedSet.copyOf(valueComparator, values);
564  }
565
566  private static <V> ImmutableSet<V> emptySet(@Nullable Comparator<? super V> valueComparator) {
567    return (valueComparator == null)
568        ? ImmutableSet.<V>of()
569        : ImmutableSortedSet.<V>emptySet(valueComparator);
570  }
571
572  private static <V> ImmutableSet.Builder<V> valuesBuilder(
573      @Nullable Comparator<? super V> valueComparator) {
574    return (valueComparator == null)
575        ? new ImmutableSet.Builder<V>()
576        : new ImmutableSortedSet.Builder<V>(valueComparator);
577  }
578
579  /**
580   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
581   *     values for that key, and the key's values
582   */
583  @GwtIncompatible // java.io.ObjectOutputStream
584  private void writeObject(ObjectOutputStream stream) throws IOException {
585    stream.defaultWriteObject();
586    stream.writeObject(valueComparator());
587    Serialization.writeMultimap(this, stream);
588  }
589
590  @Nullable
591  Comparator<? super V> valueComparator() {
592    return emptySet instanceof ImmutableSortedSet
593        ? ((ImmutableSortedSet<V>) emptySet).comparator()
594        : null;
595  }
596
597  @GwtIncompatible // java serialization
598  private static final class SetFieldSettersHolder {
599    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
600        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
601  }
602
603  @GwtIncompatible // java.io.ObjectInputStream
604  // Serialization type safety is at the caller's mercy.
605  @SuppressWarnings("unchecked")
606  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
607    stream.defaultReadObject();
608    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
609    int keyCount = stream.readInt();
610    if (keyCount < 0) {
611      throw new InvalidObjectException("Invalid key count " + keyCount);
612    }
613    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
614    int tmpSize = 0;
615
616    for (int i = 0; i < keyCount; i++) {
617      Object key = stream.readObject();
618      int valueCount = stream.readInt();
619      if (valueCount <= 0) {
620        throw new InvalidObjectException("Invalid value count " + valueCount);
621      }
622
623      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
624      for (int j = 0; j < valueCount; j++) {
625        valuesBuilder.add(stream.readObject());
626      }
627      ImmutableSet<Object> valueSet = valuesBuilder.build();
628      if (valueSet.size() != valueCount) {
629        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
630      }
631      builder.put(key, valueSet);
632      tmpSize += valueCount;
633    }
634
635    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
636    try {
637      tmpMap = builder.build();
638    } catch (IllegalArgumentException e) {
639      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
640    }
641
642    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
643    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
644    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
645  }
646
647  @GwtIncompatible // not needed in emulated source.
648  private static final long serialVersionUID = 0;
649}