com.google.common.collect.ImmutableMultiset Maven / Gradle / Ivy
/*
* Copyright (C) 2008 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.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
/**
* An immutable hash-based multiset. Does not permit null elements.
*
* Its iterator orders elements according to the first appearance of the
* element among the items passed to the factory method or builder. When the
* multiset contains multiple instances of an element, those instances are
* consecutive in the iteration order.
*
*
See the Guava User Guide article on
* immutable collections.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial") // we're overriding default serialization
// TODO(user): write an efficient asList() implementation
public abstract class ImmutableMultiset extends ImmutableCollection
implements Multiset {
/**
* Returns the empty immutable multiset.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static ImmutableMultiset of() {
return (ImmutableMultiset) EmptyImmutableMultiset.INSTANCE;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if {@code element} is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") // generic array created but never written
public static ImmutableMultiset of(E element) {
return copyOfInternal(element);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2) {
return copyOfInternal(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3) {
return copyOfInternal(e1, e2, e3);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3, E e4) {
return copyOfInternal(e1, e2, e3, e4);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3, E e4, E e5) {
return copyOfInternal(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(
E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
int size = others.length + 6;
List all = new ArrayList(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, others);
return copyOf(all);
}
/**
* Returns an immutable multiset containing the given elements.
*
* The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset
* with elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 6.0
*/
public static ImmutableMultiset copyOf(E[] elements) {
return copyOf(Arrays.asList(elements));
}
/**
* Returns an immutable multiset containing the given elements.
*
* The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields
* a multiset with elements in the order {@code 2, 3, 3, 1}.
*
*
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.
*
*
Note: Despite what the method name suggests, if {@code elements}
* is an {@code ImmutableMultiset}, no copy will actually be performed, and
* the given multiset itself will be returned.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static ImmutableMultiset copyOf(
Iterable extends E> elements) {
if (elements instanceof ImmutableMultiset) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableMultiset result = (ImmutableMultiset) elements;
if (!result.isPartialView()) {
return result;
}
}
Multiset extends E> multiset = (elements instanceof Multiset)
? Multisets.cast(elements)
: LinkedHashMultiset.create(elements);
return copyOfInternal(multiset);
}
private static ImmutableMultiset copyOfInternal(E... elements) {
return copyOf(Arrays.asList(elements));
}
private static ImmutableMultiset copyOfInternal(
Multiset extends E> multiset) {
return copyFromEntries(multiset.entrySet());
}
static ImmutableMultiset copyFromEntries(
Collection extends Entry extends E>> entries) {
long size = 0;
ImmutableMap.Builder builder = ImmutableMap.builder();
for (Entry extends E> entry : entries) {
int count = entry.getCount();
if (count > 0) {
// Since ImmutableMap.Builder throws an NPE if an element is null, no
// other null checks are needed.
builder.put(entry.getElement(), count);
size += count;
}
}
if (size == 0) {
return of();
}
return new RegularImmutableMultiset(
builder.build(), Ints.saturatedCast(size));
}
/**
* Returns an immutable multiset containing the given elements.
*
* The multiset is ordered by the first occurrence of each element. For
* example,
* {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
* yields a multiset with elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static ImmutableMultiset copyOf(
Iterator extends E> elements) {
Multiset multiset = LinkedHashMultiset.create();
Iterators.addAll(multiset, elements);
return copyOfInternal(multiset);
}
ImmutableMultiset() {}
@Override public UnmodifiableIterator iterator() {
final Iterator> entryIterator = entrySet().iterator();
return new UnmodifiableIterator() {
int remaining;
E element;
@Override
public boolean hasNext() {
return (remaining > 0) || entryIterator.hasNext();
}
@Override
public E next() {
if (remaining <= 0) {
Entry entry = entryIterator.next();
element = entry.getElement();
remaining = entry.getCount();
}
remaining--;
return element;
}
};
}
@Override
public boolean contains(@Nullable Object object) {
return count(object) > 0;
}
@Override
public boolean containsAll(Collection> targets) {
return elementSet().containsAll(targets);
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multiset) {
Multiset> that = (Multiset>) object;
if (this.size() != that.size()) {
return false;
}
for (Entry> entry : that.entrySet()) {
if (count(entry.getElement()) != entry.getCount()) {
return false;
}
}
return true;
}
return false;
}
@Override public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override public String toString() {
return entrySet().toString();
}
private transient ImmutableSet> entrySet;
@Override
public ImmutableSet> entrySet() {
ImmutableSet> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
abstract ImmutableSet> createEntrySet();
abstract class EntrySet extends ImmutableSet> {
@Override
boolean isPartialView() {
return ImmutableMultiset.this.isPartialView();
}
@Override
public boolean contains(Object o) {
if (o instanceof Entry) {
Entry> entry = (Entry>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = count(entry.getElement());
return count == entry.getCount();
}
return false;
}
/*
* TODO(hhchan): Revert once we have a separate, manual emulation of this
* class.
*/
@Override
public Object[] toArray() {
Object[] newArray = new Object[size()];
return toArray(newArray);
}
/*
* TODO(hhchan): Revert once we have a separate, manual emulation of this
* class.
*/
@Override
public T[] toArray(T[] other) {
int size = size();
if (other.length < size) {
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires
Object[] otherAsObjectArray = other;
int index = 0;
for (Entry> element : this) {
otherAsObjectArray[index++] = element;
}
return other;
}
@Override
public int hashCode() {
return ImmutableMultiset.this.hashCode();
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
// TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
Object writeReplace() {
return new EntrySetSerializedForm(ImmutableMultiset.this);
}
private static final long serialVersionUID = 0;
}
static class EntrySetSerializedForm implements Serializable {
final ImmutableMultiset multiset;
EntrySetSerializedForm(ImmutableMultiset multiset) {
this.multiset = multiset;
}
Object readResolve() {
return multiset.entrySet();
}
}
private static class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
SerializedForm(Multiset> multiset) {
int distinct = multiset.entrySet().size();
elements = new Object[distinct];
counts = new int[distinct];
int i = 0;
for (Entry> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
LinkedHashMultiset