001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the
010 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
011 * express or implied. See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.VisibleForTesting;
022import com.google.common.math.IntMath;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import com.google.errorprone.annotations.DoNotCall;
025import com.google.errorprone.annotations.concurrent.LazyInit;
026import java.io.InvalidObjectException;
027import java.io.ObjectInputStream;
028import java.io.Serializable;
029import java.util.Arrays;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.Comparator;
033import java.util.Iterator;
034import java.util.List;
035import javax.annotation.CheckForNull;
036
037/**
038 * A {@link SortedMultiset} whose contents will never change, with many other important properties
039 * detailed at {@link ImmutableCollection}.
040 *
041 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
042 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
043 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
044 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting
045 * collection will not correctly obey its specification.
046 *
047 * <p>See the Guava User Guide article on <a href=
048 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
049 *
050 * @author Louis Wasserman
051 * @since 12.0
052 */
053@GwtIncompatible // hasn't been tested yet
054@ElementTypesAreNonnullByDefault
055public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultisetFauxverideShim<E>
056    implements SortedMultiset<E> {
057  // TODO(lowasser): GWT compatibility
058
059  /**
060   * Returns the empty immutable sorted multiset.
061   *
062   * <p><b>Performance note:</b> the instance returned is a singleton.
063   */
064  @SuppressWarnings("unchecked")
065  public static <E> ImmutableSortedMultiset<E> of() {
066    return (ImmutableSortedMultiset) RegularImmutableSortedMultiset.NATURAL_EMPTY_MULTISET;
067  }
068
069  /** Returns an immutable sorted multiset containing a single element. */
070  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) {
071    RegularImmutableSortedSet<E> elementSet =
072        (RegularImmutableSortedSet<E>) ImmutableSortedSet.of(element);
073    long[] cumulativeCounts = {0, 1};
074    return new RegularImmutableSortedMultiset<E>(elementSet, cumulativeCounts, 0, 1);
075  }
076
077  /**
078   * Returns an immutable sorted multiset containing the given elements sorted by their natural
079   * ordering.
080   *
081   * @throws NullPointerException if any element is null
082   */
083  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2) {
084    return copyOf(Ordering.natural(), Arrays.asList(e1, e2));
085  }
086
087  /**
088   * Returns an immutable sorted multiset containing the given elements sorted by their natural
089   * ordering.
090   *
091   * @throws NullPointerException if any element is null
092   */
093  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) {
094    return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3));
095  }
096
097  /**
098   * Returns an immutable sorted multiset containing the given elements sorted by their natural
099   * ordering.
100   *
101   * @throws NullPointerException if any element is null
102   */
103  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
104      E e1, E e2, E e3, E e4) {
105    return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4));
106  }
107
108  /**
109   * Returns an immutable sorted multiset containing the given elements sorted by their natural
110   * ordering.
111   *
112   * @throws NullPointerException if any element is null
113   */
114  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
115      E e1, E e2, E e3, E e4, E e5) {
116    return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4, e5));
117  }
118
119  /**
120   * Returns an immutable sorted multiset containing the given elements sorted by their natural
121   * ordering.
122   *
123   * @throws NullPointerException if any element is null
124   */
125  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
126      E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
127    int size = remaining.length + 6;
128    List<E> all = Lists.newArrayListWithCapacity(size);
129    Collections.addAll(all, e1, e2, e3, e4, e5, e6);
130    Collections.addAll(all, remaining);
131    return copyOf(Ordering.natural(), all);
132  }
133
134  /**
135   * Returns an immutable sorted multiset containing the given elements sorted by their natural
136   * ordering.
137   *
138   * @throws NullPointerException if any of {@code elements} is null
139   */
140  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> copyOf(E[] elements) {
141    return copyOf(Ordering.natural(), Arrays.asList(elements));
142  }
143
144  /**
145   * Returns an immutable sorted multiset containing the given elements sorted by their natural
146   * ordering. To create a copy of a {@code SortedMultiset} that preserves the comparator, call
147   * {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
148   *
149   * <p>Note that if {@code s} is a {@code Multiset<String>}, then {@code
150   * ImmutableSortedMultiset.copyOf(s)} returns an {@code ImmutableSortedMultiset<String>}
151   * containing each of the strings in {@code s}, while {@code ImmutableSortedMultiset.of(s)}
152   * returns an {@code ImmutableSortedMultiset<Multiset<String>>} containing one element (the given
153   * multiset itself).
154   *
155   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
156   * safe to do so. The exact circumstances under which a copy will or will not be performed are
157   * undocumented and subject to change.
158   *
159   * <p>This method is not type-safe, as it may be called on elements that are not mutually
160   * comparable.
161   *
162   * @throws ClassCastException if the elements are not mutually comparable
163   * @throws NullPointerException if any of {@code elements} is null
164   */
165  public static <E> ImmutableSortedMultiset<E> copyOf(Iterable<? extends E> elements) {
166    // Hack around E not being a subtype of Comparable.
167    // Unsafe, see ImmutableSortedMultisetFauxverideShim.
168    @SuppressWarnings("unchecked")
169    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
170    return copyOf(naturalOrder, elements);
171  }
172
173  /**
174   * Returns an immutable sorted multiset containing the given elements sorted by their natural
175   * ordering.
176   *
177   * <p>This method is not type-safe, as it may be called on elements that are not mutually
178   * comparable.
179   *
180   * @throws ClassCastException if the elements are not mutually comparable
181   * @throws NullPointerException if any of {@code elements} is null
182   */
183  public static <E> ImmutableSortedMultiset<E> copyOf(Iterator<? extends E> elements) {
184    // Hack around E not being a subtype of Comparable.
185    // Unsafe, see ImmutableSortedMultisetFauxverideShim.
186    @SuppressWarnings("unchecked")
187    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
188    return copyOf(naturalOrder, elements);
189  }
190
191  /**
192   * Returns an immutable sorted multiset containing the given elements sorted by the given {@code
193   * Comparator}.
194   *
195   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
196   */
197  public static <E> ImmutableSortedMultiset<E> copyOf(
198      Comparator<? super E> comparator, Iterator<? extends E> elements) {
199    checkNotNull(comparator);
200    return new Builder<E>(comparator).addAll(elements).build();
201  }
202
203  /**
204   * Returns an immutable sorted multiset containing the given elements sorted by the given {@code
205   * Comparator}. This method iterates over {@code elements} at most once.
206   *
207   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
208   * safe to do so. The exact circumstances under which a copy will or will not be performed are
209   * undocumented and subject to change.
210   *
211   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
212   */
213  @SuppressWarnings("unchecked")
214  public static <E> ImmutableSortedMultiset<E> copyOf(
215      Comparator<? super E> comparator, Iterable<? extends E> elements) {
216    if (elements instanceof ImmutableSortedMultiset) {
217      @SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts
218      ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements;
219      if (comparator.equals(multiset.comparator())) {
220        if (multiset.isPartialView()) {
221          return copyOfSortedEntries(comparator, multiset.entrySet().asList());
222        } else {
223          return multiset;
224        }
225      }
226    }
227    return new ImmutableSortedMultiset.Builder<E>(comparator).addAll(elements).build();
228  }
229
230  /**
231   * Returns an immutable sorted multiset containing the elements of a sorted multiset, sorted by
232   * the same {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always
233   * uses the natural ordering of the elements.
234   *
235   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
236   * safe to do so. The exact circumstances under which a copy will or will not be performed are
237   * undocumented and subject to change.
238   *
239   * <p>This method is safe to use even when {@code sortedMultiset} is a synchronized or concurrent
240   * collection that is currently being modified by another thread.
241   *
242   * @throws NullPointerException if {@code sortedMultiset} or any of its elements is null
243   */
244  public static <E> ImmutableSortedMultiset<E> copyOfSorted(SortedMultiset<E> sortedMultiset) {
245    return copyOfSortedEntries(
246        sortedMultiset.comparator(), Lists.newArrayList(sortedMultiset.entrySet()));
247  }
248
249  private static <E> ImmutableSortedMultiset<E> copyOfSortedEntries(
250      Comparator<? super E> comparator, Collection<Entry<E>> entries) {
251    if (entries.isEmpty()) {
252      return emptyMultiset(comparator);
253    }
254    ImmutableList.Builder<E> elementsBuilder = new ImmutableList.Builder<E>(entries.size());
255    long[] cumulativeCounts = new long[entries.size() + 1];
256    int i = 0;
257    for (Entry<E> entry : entries) {
258      elementsBuilder.add(entry.getElement());
259      cumulativeCounts[i + 1] = cumulativeCounts[i] + entry.getCount();
260      i++;
261    }
262    return new RegularImmutableSortedMultiset<E>(
263        new RegularImmutableSortedSet<E>(elementsBuilder.build(), comparator),
264        cumulativeCounts,
265        0,
266        entries.size());
267  }
268
269  @SuppressWarnings("unchecked")
270  static <E> ImmutableSortedMultiset<E> emptyMultiset(Comparator<? super E> comparator) {
271    if (Ordering.natural().equals(comparator)) {
272      return (ImmutableSortedMultiset<E>) RegularImmutableSortedMultiset.NATURAL_EMPTY_MULTISET;
273    } else {
274      return new RegularImmutableSortedMultiset<E>(comparator);
275    }
276  }
277
278  ImmutableSortedMultiset() {}
279
280  @Override
281  public final Comparator<? super E> comparator() {
282    return elementSet().comparator();
283  }
284
285  @Override
286  public abstract ImmutableSortedSet<E> elementSet();
287
288  @LazyInit @CheckForNull transient ImmutableSortedMultiset<E> descendingMultiset;
289
290  @Override
291  public ImmutableSortedMultiset<E> descendingMultiset() {
292    ImmutableSortedMultiset<E> result = descendingMultiset;
293    if (result == null) {
294      return descendingMultiset =
295          this.isEmpty()
296              ? emptyMultiset(Ordering.from(comparator()).reverse())
297              : new DescendingImmutableSortedMultiset<E>(this);
298    }
299    return result;
300  }
301
302  /**
303   * {@inheritDoc}
304   *
305   * <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}.
306   *
307   * @throws UnsupportedOperationException always
308   * @deprecated Unsupported operation.
309   */
310  @CanIgnoreReturnValue
311  @Deprecated
312  @Override
313  @DoNotCall("Always throws UnsupportedOperationException")
314  @CheckForNull
315  public final Entry<E> pollFirstEntry() {
316    throw new UnsupportedOperationException();
317  }
318
319  /**
320   * {@inheritDoc}
321   *
322   * <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}.
323   *
324   * @throws UnsupportedOperationException always
325   * @deprecated Unsupported operation.
326   */
327  @CanIgnoreReturnValue
328  @Deprecated
329  @Override
330  @DoNotCall("Always throws UnsupportedOperationException")
331  @CheckForNull
332  public final Entry<E> pollLastEntry() {
333    throw new UnsupportedOperationException();
334  }
335
336  @Override
337  public abstract ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType);
338
339  @Override
340  public ImmutableSortedMultiset<E> subMultiset(
341      E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) {
342    checkArgument(
343        comparator().compare(lowerBound, upperBound) <= 0,
344        "Expected lowerBound <= upperBound but %s > %s",
345        lowerBound,
346        upperBound);
347    return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType);
348  }
349
350  @Override
351  public abstract ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType);
352
353  /**
354   * Returns a builder that creates immutable sorted multisets with an explicit comparator. If the
355   * comparator has a more general type than the set being generated, such as creating a {@code
356   * SortedMultiset<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} constructor
357   * instead.
358   *
359   * @throws NullPointerException if {@code comparator} is null
360   */
361  public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
362    return new Builder<E>(comparator);
363  }
364
365  /**
366   * Returns a builder that creates immutable sorted multisets whose elements are ordered by the
367   * reverse of their natural ordering.
368   *
369   * <p>Note: the type parameter {@code E} extends {@code Comparable<?>} rather than {@code
370   * Comparable<? super E>} as a workaround for javac <a
371   * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>.
372   */
373  public static <E extends Comparable<?>> Builder<E> reverseOrder() {
374    return new Builder<E>(Ordering.natural().reverse());
375  }
376
377  /**
378   * Returns a builder that creates immutable sorted multisets whose elements are ordered by their
379   * natural ordering. The sorted multisets use {@link Ordering#natural()} as the comparator. This
380   * method provides more type-safety than {@link #builder}, as it can be called only for classes
381   * that implement {@link Comparable}.
382   *
383   * <p>Note: the type parameter {@code E} extends {@code Comparable<?>} rather than {@code
384   * Comparable<? super E>} as a workaround for javac <a
385   * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>.
386   */
387  public static <E extends Comparable<?>> Builder<E> naturalOrder() {
388    return new Builder<E>(Ordering.natural());
389  }
390
391  /**
392   * A builder for creating immutable multiset instances, especially {@code public static final}
393   * multisets ("constant multisets"). Example:
394   *
395   * <pre>{@code
396   * public static final ImmutableSortedMultiset<Bean> BEANS =
397   *     new ImmutableSortedMultiset.Builder<Bean>(colorComparator())
398   *         .addCopies(Bean.COCOA, 4)
399   *         .addCopies(Bean.GARDEN, 6)
400   *         .addCopies(Bean.RED, 8)
401   *         .addCopies(Bean.BLACK_EYED, 10)
402   *         .build();
403   * }</pre>
404   *
405   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
406   * multiple multisets in series.
407   *
408   * @since 12.0
409   */
410  public static class Builder<E> extends ImmutableMultiset.Builder<E> {
411    /*
412     * We keep an array of elements and counts.  Periodically -- when we need more room in the
413     * array, or when we're building, or the like -- we sort, deduplicate, and combine the counts.
414     * Negative counts indicate a setCount operation with ~counts[i].
415     */
416
417    private final Comparator<? super E> comparator;
418
419    @VisibleForTesting E[] elements;
420    private int[] counts;
421
422    /*
423     * The number of used positions in the elements array.  We deduplicate periodically, so this
424     * may fluctuate up and down.
425     */
426    private int length;
427
428    // True if we just called build() and the elements array is being used by a created ISM, meaning
429    // we shouldn't modify that array further.
430    private boolean forceCopyElements;
431
432    /**
433     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
434     * ImmutableSortedMultiset#orderedBy(Comparator)}.
435     */
436    @SuppressWarnings("unchecked")
437    public Builder(Comparator<? super E> comparator) {
438      super(true); // doesn't allocate hash table in supertype
439      this.comparator = checkNotNull(comparator);
440      this.elements = (E[]) new Object[ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY];
441      this.counts = new int[ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY];
442    }
443
444    /** Check if we need to do deduplication and coalescing, and if so, do it. */
445    private void maintenance() {
446      if (length == elements.length) {
447        dedupAndCoalesce(true);
448      } else if (forceCopyElements) {
449        this.elements = Arrays.copyOf(elements, elements.length);
450        // we don't currently need to copy the counts array, because we don't use it directly
451        // in built ISMs
452      }
453      forceCopyElements = false;
454    }
455
456    private void dedupAndCoalesce(boolean maybeExpand) {
457      if (length == 0) {
458        return;
459      }
460      E[] sortedElements = Arrays.copyOf(elements, length);
461      Arrays.sort(sortedElements, comparator);
462      int uniques = 1;
463      for (int i = 1; i < sortedElements.length; i++) {
464        if (comparator.compare(sortedElements[uniques - 1], sortedElements[i]) < 0) {
465          sortedElements[uniques] = sortedElements[i];
466          uniques++;
467        }
468      }
469      Arrays.fill(sortedElements, uniques, length, null);
470      if (maybeExpand && uniques * 4 > length * 3) {
471        // lots of nonduplicated elements, expand the array by 50%
472        sortedElements =
473            Arrays.copyOf(sortedElements, IntMath.saturatedAdd(length, length / 2 + 1));
474      }
475      int[] sortedCounts = new int[sortedElements.length];
476      for (int i = 0; i < length; i++) {
477        int index = Arrays.binarySearch(sortedElements, 0, uniques, elements[i], comparator);
478        if (counts[i] >= 0) {
479          sortedCounts[index] += counts[i];
480        } else {
481          sortedCounts[index] = ~counts[i];
482        }
483      }
484      // Note that we're not getting rid, yet, of elements with count 0.  We'll do that in build().
485      this.elements = sortedElements;
486      this.counts = sortedCounts;
487      this.length = uniques;
488    }
489
490    /**
491     * Adds {@code element} to the {@code ImmutableSortedMultiset}.
492     *
493     * @param element the element to add
494     * @return this {@code Builder} object
495     * @throws NullPointerException if {@code element} is null
496     */
497    @CanIgnoreReturnValue
498    @Override
499    public Builder<E> add(E element) {
500      return addCopies(element, 1);
501    }
502
503    /**
504     * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}.
505     *
506     * @param elements the elements to add
507     * @return this {@code Builder} object
508     * @throws NullPointerException if {@code elements} is null or contains a null element
509     */
510    @CanIgnoreReturnValue
511    @Override
512    public Builder<E> add(E... elements) {
513      for (E element : elements) {
514        add(element);
515      }
516      return this;
517    }
518
519    /**
520     * Adds a number of occurrences of an element to this {@code ImmutableSortedMultiset}.
521     *
522     * @param element the element to add
523     * @param occurrences the number of occurrences of the element to add. May be zero, in which
524     *     case no change will be made.
525     * @return this {@code Builder} object
526     * @throws NullPointerException if {@code element} is null
527     * @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation
528     *     would result in more than {@link Integer#MAX_VALUE} occurrences of the element
529     */
530    @CanIgnoreReturnValue
531    @Override
532    public Builder<E> addCopies(E element, int occurrences) {
533      checkNotNull(element);
534      CollectPreconditions.checkNonnegative(occurrences, "occurrences");
535      if (occurrences == 0) {
536        return this;
537      }
538      maintenance();
539      elements[length] = element;
540      counts[length] = occurrences;
541      length++;
542      return this;
543    }
544
545    /**
546     * Adds or removes the necessary occurrences of an element such that the element attains the
547     * desired count.
548     *
549     * @param element the element to add or remove occurrences of
550     * @param count the desired count of the element in this multiset
551     * @return this {@code Builder} object
552     * @throws NullPointerException if {@code element} is null
553     * @throws IllegalArgumentException if {@code count} is negative
554     */
555    @CanIgnoreReturnValue
556    @Override
557    public Builder<E> setCount(E element, int count) {
558      checkNotNull(element);
559      CollectPreconditions.checkNonnegative(count, "count");
560      maintenance();
561      elements[length] = element;
562      counts[length] = ~count;
563      length++;
564      return this;
565    }
566
567    /**
568     * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}.
569     *
570     * @param elements the {@code Iterable} to add to the {@code ImmutableSortedMultiset}
571     * @return this {@code Builder} object
572     * @throws NullPointerException if {@code elements} is null or contains a null element
573     */
574    @CanIgnoreReturnValue
575    @Override
576    public Builder<E> addAll(Iterable<? extends E> elements) {
577      if (elements instanceof Multiset) {
578        for (Entry<? extends E> entry : ((Multiset<? extends E>) elements).entrySet()) {
579          addCopies(entry.getElement(), entry.getCount());
580        }
581      } else {
582        for (E e : elements) {
583          add(e);
584        }
585      }
586      return this;
587    }
588
589    /**
590     * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}.
591     *
592     * @param elements the elements to add to the {@code ImmutableSortedMultiset}
593     * @return this {@code Builder} object
594     * @throws NullPointerException if {@code elements} is null or contains a null element
595     */
596    @CanIgnoreReturnValue
597    @Override
598    public Builder<E> addAll(Iterator<? extends E> elements) {
599      while (elements.hasNext()) {
600        add(elements.next());
601      }
602      return this;
603    }
604
605    private void dedupAndCoalesceAndDeleteEmpty() {
606      dedupAndCoalesce(false);
607
608      // If there was a setCount(elem, 0), those elements are still present.  Eliminate them.
609      int size = 0;
610      for (int i = 0; i < length; i++) {
611        if (counts[i] > 0) {
612          elements[size] = elements[i];
613          counts[size] = counts[i];
614          size++;
615        }
616      }
617      Arrays.fill(elements, size, length, null);
618      Arrays.fill(counts, size, length, 0);
619      length = size;
620    }
621
622    /**
623     * Returns a newly-created {@code ImmutableSortedMultiset} based on the contents of the {@code
624     * Builder}.
625     */
626    @Override
627    public ImmutableSortedMultiset<E> build() {
628      dedupAndCoalesceAndDeleteEmpty();
629      if (length == 0) {
630        return emptyMultiset(comparator);
631      }
632      RegularImmutableSortedSet<E> elementSet =
633          (RegularImmutableSortedSet<E>) ImmutableSortedSet.construct(comparator, length, elements);
634      long[] cumulativeCounts = new long[length + 1];
635      for (int i = 0; i < length; i++) {
636        cumulativeCounts[i + 1] = cumulativeCounts[i] + counts[i];
637      }
638      forceCopyElements = true;
639      return new RegularImmutableSortedMultiset<E>(elementSet, cumulativeCounts, 0, length);
640    }
641  }
642
643  private static final class SerializedForm<E> implements Serializable {
644    final Comparator<? super E> comparator;
645    final E[] elements;
646    final int[] counts;
647
648    @SuppressWarnings("unchecked")
649    SerializedForm(SortedMultiset<E> multiset) {
650      this.comparator = multiset.comparator();
651      int n = multiset.entrySet().size();
652      elements = (E[]) new Object[n];
653      counts = new int[n];
654      int i = 0;
655      for (Entry<E> entry : multiset.entrySet()) {
656        elements[i] = entry.getElement();
657        counts[i] = entry.getCount();
658        i++;
659      }
660    }
661
662    Object readResolve() {
663      int n = elements.length;
664      Builder<E> builder = new Builder<>(comparator);
665      for (int i = 0; i < n; i++) {
666        builder.addCopies(elements[i], counts[i]);
667      }
668      return builder.build();
669    }
670  }
671
672  @Override
673  Object writeReplace() {
674    return new SerializedForm<E>(this);
675  }
676
677  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
678    throw new InvalidObjectException("Use SerializedForm");
679  }
680}