Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
   * in compliance with the License. You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software distributed under the
  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.List;

An immutable SortedMultiset that stores its elements in a sorted array. Some instances are ordered by an explicit comparator, while others follow the natural sort ordering of their elements. Either way, null elements are not supported.

Unlike Multisets.unmodifiableSortedMultiset(com.google.common.collect.SortedMultiset), which is a view of a separate collection that can still change, an instance of ImmutableSortedMultiset contains its own private data and will never change. This class is convenient for public static final multisets ("constant multisets") and also lets you easily make a "defensive copy" of a set provided to your class by a caller.

The multisets returned by the headMultiset(java.lang.Object,com.google.common.collect.BoundType), tailMultiset(java.lang.Object,com.google.common.collect.BoundType), and subMultiset(java.lang.Object,com.google.common.collect.BoundType,java.lang.Object,com.google.common.collect.BoundType) methods share the same array as the original multiset, preventing that array from being garbage collected. If this is a concern, the data may be copied into a correctly-sized array by calling copyOfSorted(com.google.common.collect.SortedMultiset).

Note on element equivalence: The ImmutableMultiset.contains(java.lang.Object), ImmutableMultiset.containsAll(java.util.Collection), and ImmutableMultiset.equals(java.lang.Object) implementations must check whether a provided object is equivalent to an element in the collection. Unlike most collections, an ImmutableSortedMultiset doesn't use java.lang.Object.equals(java.lang.Object) to determine if two elements are equivalent. Instead, with an explicit comparator, the following relation determines whether elements x and y are equivalent:

   {(x, y) | comparator.compare(x, y) == 0}
With natural ordering of elements, the following relation determines whether two elements are equivalent:
   {(x, y) | x.compareTo(y) == 0}
Warning: Like most multisets, an ImmutableSortedMultiset will not function correctly if an element is modified after being placed in the multiset. For this reason, and to avoid general confusion, it is strongly recommended to place only immutable objects into this collection.

Note: Although this class is not final, it cannot be subclassed as it has no public or protected constructors. Thus, instances of this type are guaranteed to be immutable.

See the Guava User Guide article on immutable collections.

Author(s):
Louis Wasserman
Since:
12.0
 
 @GwtIncompatible("hasn't been tested yet")
 public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultisetFauxverideShim<E>
     implements SortedMultiset<E> {
   // TODO(user): GWT compatibility
 
   private static final Comparator<ComparableNATURAL_ORDER = Ordering.natural();
 
Returns the empty immutable sorted multiset.
 
   @SuppressWarnings("unchecked")
   public static <E> ImmutableSortedMultiset<E> of() {
   }

  
Returns an immutable sorted multiset containing a single element.
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) {
    RegularImmutableSortedSet<E> elementSet =
        (RegularImmutableSortedSet<E>) ImmutableSortedSet.of(element);
    int[] counts = {1};
    long[] cumulativeCounts = {0, 1};
    return new RegularImmutableSortedMultiset<E>(elementSetcountscumulativeCounts, 0, 1);
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

Throws:
java.lang.NullPointerException if any element is null
  @SuppressWarnings("unchecked")
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2) {
    return copyOf(Ordering.natural(), Arrays.asList(e1e2));
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

Throws:
java.lang.NullPointerException if any element is null
  @SuppressWarnings("unchecked")
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) {
    return copyOf(Ordering.natural(), Arrays.asList(e1e2e3));
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

Throws:
java.lang.NullPointerException if any element is null
  @SuppressWarnings("unchecked")
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
      E e1, E e2, E e3, E e4) {
    return copyOf(Ordering.natural(), Arrays.asList(e1e2e3e4));
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

Throws:
java.lang.NullPointerException if any element is null
  @SuppressWarnings("unchecked")
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
      E e1, E e2, E e3, E e4, E e5) {
    return copyOf(Ordering.natural(), Arrays.asList(e1e2e3e4e5));
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

Throws:
java.lang.NullPointerException if any element is null
  @SuppressWarnings("unchecked")
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
    int size = remaining.length + 6;
    List<E> all = Lists.newArrayListWithCapacity(size);
    Collections.addAll(alle1e2e3e4e5e6);
    Collections.addAll(allremaining);
    return copyOf(Ordering.natural(), all);
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

Throws:
java.lang.NullPointerException if any of elements is null
  public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> copyOf(E[] elements) {
    return copyOf(Ordering.natural(), Arrays.asList(elements));
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering. To create a copy of a SortedMultiset that preserves the comparator, call copyOfSorted(com.google.common.collect.SortedMultiset) instead. This method iterates over elements at most once.

Note that if s is a multiset<String>, then ImmutableSortedMultiset.copyOf(s) returns an ImmutableSortedMultiset<String> containing each of the strings in s, while ImmutableSortedMultiset.of(s) returns an ImmutableSortedMultiset<multiset<String>> containing one element (the given multiset itself).

Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change.

This method is not type-safe, as it may be called on elements that are not mutually comparable.

Throws:
java.lang.ClassCastException if the elements are not mutually comparable
java.lang.NullPointerException if any of elements is null
  public static <E> ImmutableSortedMultiset<E> copyOf(Iterable<? extends E> elements) {
    // Hack around E not being a subtype of Comparable.
    // Unsafe, see ImmutableSortedMultisetFauxverideShim.
    @SuppressWarnings("unchecked")
    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
    return copyOf(naturalOrderelements);
  }

  
Returns an immutable sorted multiset containing the given elements sorted by their natural ordering.

This method is not type-safe, as it may be called on elements that are not mutually comparable.

Throws:
java.lang.ClassCastException if the elements are not mutually comparable
java.lang.NullPointerException if any of elements is null
  public static <E> ImmutableSortedMultiset<E> copyOf(Iterator<? extends E> elements) {
    // Hack around E not being a subtype of Comparable.
    // Unsafe, see ImmutableSortedMultisetFauxverideShim.
    @SuppressWarnings("unchecked")
    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
    return copyOf(naturalOrderelements);
  }

  
Returns an immutable sorted multiset containing the given elements sorted by the given Comparator.

Throws:
java.lang.NullPointerException if comparator or any of elements is null
  public static <E> ImmutableSortedMultiset<E> copyOf(
      Comparator<? super E> comparatorIterator<? extends E> elements) {
    checkNotNull(comparator);
    return new Builder<E>(comparator).addAll(elements).build();
  }

  
Returns an immutable sorted multiset containing the given elements sorted by the given Comparator. This method iterates over elements at most once.

Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change.

Throws:
java.lang.NullPointerException if comparator or any of elements is null
  public static <E> ImmutableSortedMultiset<E> copyOf(
      Comparator<? super E> comparatorIterable<? extends E> elements) {
    if (elements instanceof ImmutableSortedMultiset) {
      @SuppressWarnings("unchecked"// immutable collections are always safe for covariant casts
      ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements;
      if (comparator.equals(multiset.comparator())) {
        if (multiset.isPartialView()) {
          return copyOfSortedEntries(comparatormultiset.entrySet().asList());
        } else {
          return multiset;
        }
      }
    }
    elements = Lists.newArrayList(elements); // defensive copy
    TreeMultiset<E> sortedCopy = TreeMultiset.create(checkNotNull(comparator));
    Iterables.addAll(sortedCopyelements);
    return copyOfSortedEntries(comparatorsortedCopy.entrySet());
  }

  
Returns an immutable sorted multiset containing the elements of a sorted multiset, sorted by the same Comparator. That behavior differs from copyOf(java.lang.Iterable), which always uses the natural ordering of the elements.

Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change.

This method is safe to use even when sortedMultiset is a synchronized or concurrent collection that is currently being modified by another thread.

Throws:
java.lang.NullPointerException if sortedMultiset or any of its elements is null
  public static <E> ImmutableSortedMultiset<E> copyOfSorted(SortedMultiset<E> sortedMultiset) {
    return copyOfSortedEntries(sortedMultiset.comparator(),
        Lists.newArrayList(sortedMultiset.entrySet()));
  }
  private static <E> ImmutableSortedMultiset<E> copyOfSortedEntries(
      Comparator<? super E> comparatorCollection<Entry<E>> entries) {
    if (entries.isEmpty()) {
      return emptyMultiset(comparator);
    }
    ImmutableList.Builder<E> elementsBuilder = new ImmutableList.Builder<E>(entries.size());
    int[] counts = new int[entries.size()];
    long[] cumulativeCounts = new long[entries.size() + 1];
    int i = 0;
    for (Entry<E> entry : entries) {
      elementsBuilder.add(entry.getElement());
      counts[i] = entry.getCount();
      cumulativeCounts[i + 1] = cumulativeCounts[i] + counts[i];
      i++;
    }
    return new RegularImmutableSortedMultiset<E>(
        new RegularImmutableSortedSet<E>(elementsBuilder.build(), comparator),
        countscumulativeCounts, 0, entries.size());
  }
  @SuppressWarnings("unchecked")
  static <E> ImmutableSortedMultiset<E> emptyMultiset(Comparator<? super E> comparator) {
    if (.equals(comparator)) {
    }
    return new EmptyImmutableSortedMultiset<E>(comparator);
  }
  public final Comparator<? super E> comparator() {
    return elementSet().comparator();
  }
  public abstract ImmutableSortedSet<E> elementSet();
    if (result == null) {
      return  = new DescendingImmutableSortedMultiset<E>(this);
    }
    return result;
  }

  

This implementation is guaranteed to throw an java.lang.UnsupportedOperationException.

Deprecated:
Unsupported operation.
Throws:
java.lang.UnsupportedOperationException always
  public final Entry<E> pollFirstEntry() {
    throw new UnsupportedOperationException();
  }

  

This implementation is guaranteed to throw an java.lang.UnsupportedOperationException.

Deprecated:
Unsupported operation.
Throws:
java.lang.UnsupportedOperationException always
  public final Entry<E> pollLastEntry() {
    throw new UnsupportedOperationException();
  }
  public abstract ImmutableSortedMultiset<E> headMultiset(E upperBoundBoundType boundType);
      E lowerBoundBoundType lowerBoundType, E upperBoundBoundType upperBoundType) {
    checkArgument(comparator().compare(lowerBoundupperBound) <= 0,
        "Expected lowerBound <= upperBound but %s > %s"lowerBoundupperBound);
    return tailMultiset(lowerBoundlowerBoundType).headMultiset(upperBoundupperBoundType);
  }
  public abstract ImmutableSortedMultiset<E> tailMultiset(E lowerBoundBoundType boundType);

  
Returns a builder that creates immutable sorted multisets with an explicit comparator. If the comparator has a more general type than the set being generated, such as creating a SortedMultiset<Integer> with a Comparator<Number>, use the ImmutableSortedMultiset.Builder constructor instead.

Throws:
java.lang.NullPointerException if comparator is null
  public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
    return new Builder<E>(comparator);
  }

  
Returns a builder that creates immutable sorted multisets whose elements are ordered by the reverse of their natural ordering.

Note: the type parameter E extends Comparable<E> rather than Comparable<? super E> as a workaround for javac bug 6468354.

  public static <E extends Comparable<E>> Builder<E> reverseOrder() {
    return new Builder<E>(Ordering.natural().reverse());
  }

  
Returns a builder that creates immutable sorted multisets whose elements are ordered by their natural ordering. The sorted multisets use Ordering.natural() as the comparator. This method provides more type-safety than ImmutableSortedMultisetFauxverideShim.builder(), as it can be called only for classes that implement java.lang.Comparable.

Note: the type parameter E extends Comparable<E> rather than Comparable<? super E> as a workaround for javac bug 6468354.

  public static <E extends Comparable<E>> Builder<E> naturalOrder() {
    return new Builder<E>(Ordering.natural());
  }

  
A builder for creating immutable multiset instances, especially public static final multisets ("constant multisets"). Example:
 public static final ImmutableSortedMultiset<Bean> BEANS =
       new ImmutableSortedMultiset.Builder<Bean>()
           .addCopies(Bean.COCOA, 4)
           .addCopies(Bean.GARDEN, 6)
           .addCopies(Bean.RED, 8)
           .addCopies(Bean.BLACK_EYED, 10)
           .build();
Builder instances can be reused; it is safe to call build() multiple times to build multiple multisets in series.

Since:
12.0
  public static class Builder<E> extends ImmutableMultiset.Builder<E> {
    private final Comparator<? super E> comparator;

    
Creates a new builder. The returned builder is equivalent to the builder generated by ImmutableSortedMultiset.orderedBy(java.util.Comparator).
    public Builder(Comparator<? super E> comparator) {
      super(TreeMultiset.<E>create(comparator));
      this. = checkNotNull(comparator);
    }

    
Adds element to the ImmutableSortedMultiset.

Parameters:
element the element to add
Returns:
this Builder object
Throws:
java.lang.NullPointerException if element is null
    @Override
    public Builder<E> add(E element) {
      super.add(element);
      return this;
    }

    
Adds a number of occurrences of an element to this ImmutableSortedMultiset.

Parameters:
element the element to add
occurrences the number of occurrences of the element to add. May be zero, in which case no change will be made.
Returns:
this Builder object
Throws:
java.lang.NullPointerException if element is null
java.lang.IllegalArgumentException if occurrences is negative, or if this operation would result in more than java.lang.Integer.MAX_VALUE occurrences of the element
    @Override
    public Builder<E> addCopies(E elementint occurrences) {
      super.addCopies(elementoccurrences);
      return this;
    }

    
Adds or removes the necessary occurrences of an element such that the element attains the desired count.

Parameters:
element the element to add or remove occurrences of
count the desired count of the element in this multiset
Returns:
this Builder object
Throws:
java.lang.NullPointerException if element is null
java.lang.IllegalArgumentException if count is negative
    @Override
    public Builder<E> setCount(E elementint count) {
      super.setCount(elementcount);
      return this;
    }

    
Adds each element of elements to the ImmutableSortedMultiset.

Parameters:
elements the elements to add
Returns:
this Builder object
Throws:
java.lang.NullPointerException if elements is null or contains a null element
    @Override
    public Builder<E> add(E... elements) {
      super.add(elements);
      return this;
    }

    
Adds each element of elements to the ImmutableSortedMultiset.

Parameters:
elements the Iterable to add to the ImmutableSortedMultiset
Returns:
this Builder object
Throws:
java.lang.NullPointerException if elements is null or contains a null element
    @Override
    public Builder<E> addAll(Iterable<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    
Adds each element of elements to the ImmutableSortedMultiset.

Parameters:
elements the elements to add to the ImmutableSortedMultiset
Returns:
this Builder object
Throws:
java.lang.NullPointerException if elements is null or contains a null element
    @Override
    public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    
Returns a newly-created ImmutableSortedMultiset based on the contents of the Builder.
    @Override
    public ImmutableSortedMultiset<E> build() {
      return copyOfSorted((SortedMultiset<E>) );
    }
  }
  private static final class SerializedForm implements Serializable {
    Object[] elements;
    int[] counts;
    SerializedForm(SortedMultiset<?> multiset) {
      this. = multiset.comparator();
      int n = multiset.entrySet().size();
       = new Object[n];
       = new int[n];
      int i = 0;
      for (Entry<?> entry : multiset.entrySet()) {
        [i] = entry.getElement();
        [i] = entry.getCount();
        i++;
      }
    }
    @SuppressWarnings("unchecked")
    Object readResolve() {
      int n = .;
      Builder<Objectbuilder = orderedBy();
      for (int i = 0; i < ni++) {
        builder.addCopies([i], [i]);
      }
      return builder.build();
    }
  }
    return new SerializedForm(this);
  }
New to GrepCode? Check out our FAQ X