code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import javax.annotation.Nullable;
/**
* A sorted map which forwards all its method calls to another sorted map.
* Subclasses should override one or more methods to modify the behavior of
* the backing sorted map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingSortedMap} forward
* <i>indiscriminately</i> to the methods of the delegate. For example,
* overriding {@link #put} alone <i>will not</i> change the behavior of {@link
* #putAll}, which can lead to unexpected behavior. In this case, you should
* override {@code putAll} as well, either providing your own implementation, or
* delegating to the provided {@code standardPutAll} method.
*
* <p>Each of the {@code standard} methods, where appropriate, use the
* comparator of the map to test equality for both keys and values, unlike
* {@code ForwardingMap}.
*
* <p>The {@code standard} methods and the collection views they return are not
* guaranteed to be thread-safe, even when all of the methods that they depend
* on are thread-safe.
*
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingSortedMap<K, V> extends ForwardingMap<K, V>
implements SortedMap<K, V> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingSortedMap() {}
@Override protected abstract SortedMap<K, V> delegate();
@Override
public Comparator<? super K> comparator() {
return delegate().comparator();
}
@Override
public K firstKey() {
return delegate().firstKey();
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return delegate().headMap(toKey);
}
@Override
public K lastKey() {
return delegate().lastKey();
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return delegate().subMap(fromKey, toKey);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return delegate().tailMap(fromKey);
}
// unsafe, but worst case is a CCE is thrown, which callers will be expecting
@SuppressWarnings("unchecked")
private int unsafeCompare(Object k1, Object k2) {
Comparator<? super K> comparator = comparator();
if (comparator == null) {
return ((Comparable<Object>) k1).compareTo(k2);
} else {
return ((Comparator<Object>) comparator).compare(k1, k2);
}
}
/**
* A sensible definition of {@link #containsKey} in terms of the {@code
* firstKey()} method of {@link #tailMap}. If you override {@link #tailMap},
* you may wish to override {@link #containsKey} to forward to this
* implementation.
*
* @since 7.0
*/
@Override @Beta protected boolean standardContainsKey(@Nullable Object key) {
try {
// any CCE will be caught
@SuppressWarnings("unchecked")
SortedMap<Object, V> self = (SortedMap<Object, V>) this;
Object ceilingKey = self.tailMap(key).firstKey();
return unsafeCompare(ceilingKey, key) == 0;
} catch (ClassCastException e) {
return false;
} catch (NoSuchElementException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
/**
* A sensible definition of {@link #remove} in terms of the {@code
* iterator()} of the {@code entrySet()} of {@link #tailMap}. If you override
* {@link #tailMap}, you may wish to override {@link #remove} to forward
* to this implementation.
*
* @since 7.0
*/
@Override @Beta protected V standardRemove(@Nullable Object key) {
try {
// any CCE will be caught
@SuppressWarnings("unchecked")
SortedMap<Object, V> self = (SortedMap<Object, V>) this;
Iterator<Entry<Object, V>> entryIterator =
self.tailMap(key).entrySet().iterator();
if (entryIterator.hasNext()) {
Entry<Object, V> ceilingEntry = entryIterator.next();
if (unsafeCompare(ceilingEntry.getKey(), key) == 0) {
V value = ceilingEntry.getValue();
entryIterator.remove();
return value;
}
}
} catch (ClassCastException e) {
return null;
} catch (NullPointerException e) {
return null;
}
return null;
}
/**
* A sensible default implementation of {@link #subMap(Object, Object)} in
* terms of {@link #headMap(Object)} and {@link #tailMap(Object)}. In some
* situations, you may wish to override {@link #subMap(Object, Object)} to
* forward to this implementation.
*
* @since 7.0
*/
@Beta protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
return tailMap(fromKey).headMap(toKey);
}
}
| Java |
/*
* Copyright (C) 2007 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.checkElementIndex;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
/**
* An empty immutable list.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
final class EmptyImmutableList extends ImmutableList<Object> {
static final EmptyImmutableList INSTANCE = new EmptyImmutableList();
private EmptyImmutableList() {}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override boolean isPartialView() {
return false;
}
@Override public boolean contains(@Nullable Object target) {
return false;
}
@Override public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override public UnmodifiableIterator<Object> iterator() {
return listIterator();
}
@Override public Object[] toArray() {
return ObjectArrays.EMPTY_ARRAY;
}
@Override public <T> T[] toArray(T[] a) {
if (a.length > 0) {
a[0] = null;
}
return a;
}
@Override
public Object get(int index) {
// guaranteed to fail, but at least we get a consistent message
checkElementIndex(index, 0);
throw new AssertionError("unreachable");
}
@Override public int indexOf(@Nullable Object target) {
return -1;
}
@Override public int lastIndexOf(@Nullable Object target) {
return -1;
}
@Override public ImmutableList<Object> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, 0);
return this;
}
@Override public ImmutableList<Object> reverse() {
return this;
}
@Override public UnmodifiableListIterator<Object> listIterator() {
return Iterators.EMPTY_LIST_ITERATOR;
}
@Override public UnmodifiableListIterator<Object> listIterator(int start) {
checkPositionIndex(start, 0);
return Iterators.EMPTY_LIST_ITERATOR;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof List) {
List<?> that = (List<?>) object;
return that.isEmpty();
}
return false;
}
@Override public int hashCode() {
return 1;
}
@Override public String toString() {
return "[]";
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* A constraint that an element must satisfy in order to be added to a
* collection. For example, {@link Constraints#notNull()}, which prevents a
* collection from including any null elements, could be implemented like this:
* <pre> {@code
*
* public Object checkElement(Object element) {
* if (element == null) {
* throw new NullPointerException();
* }
* return element;
* }}</pre>
*
* In order to be effective, constraints should be deterministic; that is,
* they should not depend on state that can change (such as external state,
* random variables, and time) and should only depend on the value of the
* passed-in element. A non-deterministic constraint cannot reliably enforce
* that all the collection's elements meet the constraint, since the constraint
* is only enforced when elements are added.
*
* @see Constraints
* @see MapConstraint
* @author Mike Bostock
* @since 3.0
*/
@Beta
@GwtCompatible
public interface Constraint<E> {
/**
* Throws a suitable {@code RuntimeException} if the specified element is
* illegal. Typically this is either a {@link NullPointerException}, an
* {@link IllegalArgumentException}, or a {@link ClassCastException}, though
* an application-specific exception class may be used if appropriate.
*
* @param element the element to check
* @return the provided element
*/
E checkElement(E element);
/**
* Returns a brief human readable description of this constraint, such as
* "Not null" or "Positive number".
*/
@Override
String toString();
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* A comparator, with additional methods to support common operations. This is
* an "enriched" version of {@code Comparator}, in the same sense that {@link
* FluentIterable} is an enriched {@link Iterable}). For example: <pre> {@code
*
* if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }}</pre>
*
* The {@link #from(Comparator)} method returns the equivalent {@code Ordering}
* instance for a pre-existing comparator. You can also skip the comparator step
* and extend {@code Ordering} directly: <pre> {@code
*
* Ordering<String> byLengthOrdering = new Ordering<String>() {
* public int compare(String left, String right) {
* return Ints.compare(left.length(), right.length());
* }
* };}</pre>
*
* Except as noted, the orderings returned by the factory methods of this
* class are serializable if and only if the provided instances that back them
* are. For example, if {@code ordering} and {@code function} can themselves be
* serialized, then {@code ordering.onResultOf(function)} can as well.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/OrderingExplained">
* {@code Ordering}</a>.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class Ordering<T> implements Comparator<T> {
// Natural order
/**
* Returns a serializable ordering that uses the natural order of the values.
* The ordering throws a {@link NullPointerException} when passed a null
* parameter.
*
* <p>The type specification is {@code <C extends Comparable>}, instead of
* the technically correct {@code <C extends Comparable<? super C>>}, to
* support legacy types from before Java 5.
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this??
public static <C extends Comparable> Ordering<C> natural() {
return (Ordering<C>) NaturalOrdering.INSTANCE;
}
// Static factories
/**
* Returns an ordering based on an <i>existing</i> comparator instance. Note
* that there's no need to create a <i>new</i> comparator just to pass it in
* here; simply subclass {@code Ordering} and implement its {@code compareTo}
* method directly instead.
*
* @param comparator the comparator that defines the order
* @return comparator itself if it is already an {@code Ordering}; otherwise
* an ordering that wraps that comparator
*/
@GwtCompatible(serializable = true)
public static <T> Ordering<T> from(Comparator<T> comparator) {
return (comparator instanceof Ordering)
? (Ordering<T>) comparator
: new ComparatorOrdering<T>(comparator);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
*/
@GwtCompatible(serializable = true)
@Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) {
return checkNotNull(ordering);
}
/**
* Returns an ordering that compares objects according to the order in
* which they appear in the given list. Only objects present in the list
* (according to {@link Object#equals}) may be compared. This comparator
* imposes a "partial ordering" over the type {@code T}. Subsequent changes
* to the {@code valuesInOrder} list will have no effect on the returned
* comparator. Null values in the list are not supported.
*
* <p>The returned comparator throws an {@link ClassCastException} when it
* receives an input parameter that isn't among the provided values.
*
* <p>The generated comparator is serializable if all the provided values are
* serializable.
*
* @param valuesInOrder the values that the returned comparator will be able
* to compare, in the order the comparator should induce
* @return the comparator described above
* @throws NullPointerException if any of the provided values is null
* @throws IllegalArgumentException if {@code valuesInOrder} contains any
* duplicate values (according to {@link Object#equals})
*/
@GwtCompatible(serializable = true)
public static <T> Ordering<T> explicit(List<T> valuesInOrder) {
return new ExplicitOrdering<T>(valuesInOrder);
}
/**
* Returns an ordering that compares objects according to the order in
* which they are given to this method. Only objects present in the argument
* list (according to {@link Object#equals}) may be compared. This comparator
* imposes a "partial ordering" over the type {@code T}. Null values in the
* argument list are not supported.
*
* <p>The returned comparator throws a {@link ClassCastException} when it
* receives an input parameter that isn't among the provided values.
*
* <p>The generated comparator is serializable if all the provided values are
* serializable.
*
* @param leastValue the value which the returned comparator should consider
* the "least" of all values
* @param remainingValuesInOrder the rest of the values that the returned
* comparator will be able to compare, in the order the comparator should
* follow
* @return the comparator described above
* @throws NullPointerException if any of the provided values is null
* @throws IllegalArgumentException if any duplicate values (according to
* {@link Object#equals(Object)}) are present among the method arguments
*/
@GwtCompatible(serializable = true)
public static <T> Ordering<T> explicit(
T leastValue, T... remainingValuesInOrder) {
return explicit(Lists.asList(leastValue, remainingValuesInOrder));
}
// Ordering<Object> singletons
/**
* Returns an ordering which treats all values as equal, indicating "no
* ordering." Passing this ordering to any <i>stable</i> sort algorithm
* results in no change to the order of elements. Note especially that {@link
* #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the
* returned instance these are implemented by simply copying the source list.
*
* <p>Example: <pre> {@code
*
* Ordering.allEqual().nullsLast().sortedCopy(
* asList(t, null, e, s, null, t, null))}</pre>
*
* Assuming {@code t}, {@code e} and {@code s} are non-null, this returns
* {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison
* order of those three values (which might not even implement {@link
* Comparable} at all).
*
* <p><b>Warning:</b> by definition, this comparator is not <i>consistent with
* equals</i> (as defined {@linkplain Comparator here}). Avoid its use in
* APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency
* is expected.
*
* <p>The returned comparator is serializable.
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked")
public static Ordering<Object> allEqual() {
return AllEqualOrdering.INSTANCE;
}
/**
* Returns an ordering that compares objects by the natural ordering of their
* string representations as returned by {@code toString()}. It does not
* support null values.
*
* <p>The comparator is serializable.
*/
@GwtCompatible(serializable = true)
public static Ordering<Object> usingToString() {
return UsingToStringOrdering.INSTANCE;
}
/**
* Returns an arbitrary ordering over all objects, for which {@code compare(a,
* b) == 0} implies {@code a == b} (identity equality). There is no meaning
* whatsoever to the order imposed, but it is constant for the life of the VM.
*
* <p>Because the ordering is identity-based, it is not "consistent with
* {@link Object#equals(Object)}" as defined by {@link Comparator}. Use
* caution when building a {@link SortedSet} or {@link SortedMap} from it, as
* the resulting collection will not behave exactly according to spec.
*
* <p>This ordering is not serializable, as its implementation relies on
* {@link System#identityHashCode(Object)}, so its behavior cannot be
* preserved across serialization.
*
* @since 2.0
*/
public static Ordering<Object> arbitrary() {
return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
}
private static class ArbitraryOrderingHolder {
static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
}
@VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> {
@SuppressWarnings("deprecation") // TODO(kevinb): ?
private Map<Object, Integer> uids =
Platform.tryWeakKeys(new MapMaker()).makeComputingMap(
new Function<Object, Integer>() {
final AtomicInteger counter = new AtomicInteger(0);
@Override
public Integer apply(Object from) {
return counter.getAndIncrement();
}
});
@Override public int compare(Object left, Object right) {
if (left == right) {
return 0;
} else if (left == null) {
return -1;
} else if (right == null) {
return 1;
}
int leftCode = identityHashCode(left);
int rightCode = identityHashCode(right);
if (leftCode != rightCode) {
return leftCode < rightCode ? -1 : 1;
}
// identityHashCode collision (rare, but not as rare as you'd think)
int result = uids.get(left).compareTo(uids.get(right));
if (result == 0) {
throw new AssertionError(); // extremely, extremely unlikely.
}
return result;
}
@Override public String toString() {
return "Ordering.arbitrary()";
}
/*
* We need to be able to mock identityHashCode() calls for tests, because it
* can take 1-10 seconds to find colliding objects. Mocking frameworks that
* can do magic to mock static method calls still can't do so for a system
* class, so we need the indirection. In production, Hotspot should still
* recognize that the call is 1-morphic and should still be willing to
* inline it if necessary.
*/
int identityHashCode(Object object) {
return System.identityHashCode(object);
}
}
// Constructor
/**
* Constructs a new instance of this class (only invokable by the subclass
* constructor, typically implicit).
*/
protected Ordering() {}
// Instance-based factories (and any static equivalents)
/**
* Returns the reverse of this ordering; the {@code Ordering} equivalent to
* {@link Collections#reverseOrder(Comparator)}.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
// Ordering<String> o = Ordering.<String>natural().reverse();
@GwtCompatible(serializable = true)
public <S extends T> Ordering<S> reverse() {
return new ReverseOrdering<S>(this);
}
/**
* Returns an ordering that treats {@code null} as less than all other values
* and uses {@code this} to compare non-null values.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
// Ordering<String> o = Ordering.<String>natural().nullsFirst();
@GwtCompatible(serializable = true)
public <S extends T> Ordering<S> nullsFirst() {
return new NullsFirstOrdering<S>(this);
}
/**
* Returns an ordering that treats {@code null} as greater than all other
* values and uses this ordering to compare non-null values.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
// Ordering<String> o = Ordering.<String>natural().nullsLast();
@GwtCompatible(serializable = true)
public <S extends T> Ordering<S> nullsLast() {
return new NullsLastOrdering<S>(this);
}
/**
* Returns a new ordering on {@code F} which orders elements by first applying
* a function to them, then comparing those results using {@code this}. For
* example, to compare objects by their string forms, in a case-insensitive
* manner, use: <pre> {@code
*
* Ordering.from(String.CASE_INSENSITIVE_ORDER)
* .onResultOf(Functions.toStringFunction())}</pre>
*/
@GwtCompatible(serializable = true)
public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) {
return new ByFunctionOrdering<F, T>(function, this);
}
/**
* Returns an ordering which first uses the ordering {@code this}, but which
* in the event of a "tie", then delegates to {@code secondaryComparator}.
* For example, to sort a bug list first by status and second by priority, you
* might use {@code byStatus.compound(byPriority)}. For a compound ordering
* with three or more components, simply chain multiple calls to this method.
*
* <p>An ordering produced by this method, or a chain of calls to this method,
* is equivalent to one created using {@link Ordering#compound(Iterable)} on
* the same component comparators.
*/
@GwtCompatible(serializable = true)
public <U extends T> Ordering<U> compound(
Comparator<? super U> secondaryComparator) {
return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator));
}
/**
* Returns an ordering which tries each given comparator in order until a
* non-zero result is found, returning that result, and returning zero only if
* all comparators return zero. The returned ordering is based on the state of
* the {@code comparators} iterable at the time it was provided to this
* method.
*
* <p>The returned ordering is equivalent to that produced using {@code
* Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
*
* <p><b>Warning:</b> Supplying an argument with undefined iteration order,
* such as a {@link HashSet}, will produce non-deterministic results.
*
* @param comparators the comparators to try in order
*/
@GwtCompatible(serializable = true)
public static <T> Ordering<T> compound(
Iterable<? extends Comparator<? super T>> comparators) {
return new CompoundOrdering<T>(comparators);
}
/**
* Returns a new ordering which sorts iterables by comparing corresponding
* elements pairwise until a nonzero result is found; imposes "dictionary
* order". If the end of one iterable is reached, but not the other, the
* shorter iterable is considered to be less than the longer one. For example,
* a lexicographical natural ordering over integers considers {@code
* [] < [1] < [1, 1] < [1, 2] < [2]}.
*
* <p>Note that {@code ordering.lexicographical().reverse()} is not
* equivalent to {@code ordering.reverse().lexicographical()} (consider how
* each would order {@code [1]} and {@code [1, 1]}).
*
* @since 2.0
*/
@GwtCompatible(serializable = true)
// type parameter <S> lets us avoid the extra <String> in statements like:
// Ordering<Iterable<String>> o =
// Ordering.<String>natural().lexicographical();
public <S extends T> Ordering<Iterable<S>> lexicographical() {
/*
* Note that technically the returned ordering should be capable of
* handling not just {@code Iterable<S>} instances, but also any {@code
* Iterable<? extends S>}. However, the need for this comes up so rarely
* that it doesn't justify making everyone else deal with the very ugly
* wildcard.
*/
return new LexicographicalOrdering<S>(this);
}
// Regular instance methods
// Override to add @Nullable
@Override public abstract int compare(@Nullable T left, @Nullable T right);
/**
* Returns the least of the specified values according to this ordering. If
* there are multiple least values, the first of those is returned. The
* iterator will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*
* @param iterator the iterator whose minimum element is to be determined
* @throws NoSuchElementException if {@code iterator} is empty
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*
* @since 11.0
*/
@Beta
public <E extends T> E min(Iterator<E> iterator) {
// let this throw NoSuchElementException as necessary
E minSoFar = iterator.next();
while (iterator.hasNext()) {
minSoFar = min(minSoFar, iterator.next());
}
return minSoFar;
}
/**
* Returns the least of the specified values according to this ordering. If
* there are multiple least values, the first of those is returned.
*
* @param iterable the iterable whose minimum element is to be determined
* @throws NoSuchElementException if {@code iterable} is empty
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*/
public <E extends T> E min(Iterable<E> iterable) {
return min(iterable.iterator());
}
/**
* Returns the lesser of the two values according to this ordering. If the
* values compare as 0, the first is returned.
*
* <p><b>Implementation note:</b> this method is invoked by the default
* implementations of the other {@code min} overloads, so overriding it will
* affect their behavior.
*
* @param a value to compare, returned if less than or equal to b.
* @param b value to compare.
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*/
public <E extends T> E min(@Nullable E a, @Nullable E b) {
return compare(a, b) <= 0 ? a : b;
}
/**
* Returns the least of the specified values according to this ordering. If
* there are multiple least values, the first of those is returned.
*
* @param a value to compare, returned if less than or equal to the rest.
* @param b value to compare
* @param c value to compare
* @param rest values to compare
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*/
public <E extends T> E min(
@Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
E minSoFar = min(min(a, b), c);
for (E r : rest) {
minSoFar = min(minSoFar, r);
}
return minSoFar;
}
/**
* Returns the greatest of the specified values according to this ordering. If
* there are multiple greatest values, the first of those is returned. The
* iterator will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*
* @param iterator the iterator whose maximum element is to be determined
* @throws NoSuchElementException if {@code iterator} is empty
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*
* @since 11.0
*/
@Beta
public <E extends T> E max(Iterator<E> iterator) {
// let this throw NoSuchElementException as necessary
E maxSoFar = iterator.next();
while (iterator.hasNext()) {
maxSoFar = max(maxSoFar, iterator.next());
}
return maxSoFar;
}
/**
* Returns the greatest of the specified values according to this ordering. If
* there are multiple greatest values, the first of those is returned.
*
* @param iterable the iterable whose maximum element is to be determined
* @throws NoSuchElementException if {@code iterable} is empty
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*/
public <E extends T> E max(Iterable<E> iterable) {
return max(iterable.iterator());
}
/**
* Returns the greater of the two values according to this ordering. If the
* values compare as 0, the first is returned.
*
* <p><b>Implementation note:</b> this method is invoked by the default
* implementations of the other {@code max} overloads, so overriding it will
* affect their behavior.
*
* @param a value to compare, returned if greater than or equal to b.
* @param b value to compare.
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*/
public <E extends T> E max(@Nullable E a, @Nullable E b) {
return compare(a, b) >= 0 ? a : b;
}
/**
* Returns the greatest of the specified values according to this ordering. If
* there are multiple greatest values, the first of those is returned.
*
* @param a value to compare, returned if greater than or equal to the rest.
* @param b value to compare
* @param c value to compare
* @param rest values to compare
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i> under this ordering.
*/
public <E extends T> E max(
@Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
E maxSoFar = max(max(a, b), c);
for (E r : rest) {
maxSoFar = max(maxSoFar, r);
}
return maxSoFar;
}
/**
* Returns the {@code k} least elements of the given iterable according to
* this ordering, in order from least to greatest. If there are fewer than
* {@code k} elements present, all will be included.
*
* <p>The implementation does not necessarily use a <i>stable</i> sorting
* algorithm; when multiple elements are equivalent, it is undefined which
* will come first.
*
* <p>The implementation requires that all elements of the underlying iterator
* fit into memory at once. If this is not possible, consider using a
* {@link java.util.PriorityQueue} instead.
*
* @return an immutable {@code RandomAccess} list of the {@code k} least
* elements in ascending order
* @throws IllegalArgumentException if {@code k} is negative
* @since 8.0
*/
@Beta
public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) {
checkArgument(k >= 0, "%d is negative", k);
// values is not an E[], but we use it as such for readability. Hack.
@SuppressWarnings("unchecked")
E[] values = (E[]) Iterables.toArray(iterable);
// TODO(nshupe): also sort whole list if k is *near* values.length?
// TODO(kevinb): benchmark this impl against hand-coded heap
E[] resultArray;
if (values.length <= k) {
Arrays.sort(values, this);
resultArray = values;
} else {
quicksortLeastK(values, 0, values.length - 1, k);
// this is not an E[], but we use it as such for readability. Hack.
@SuppressWarnings("unchecked")
E[] tmp = (E[]) new Object[k];
resultArray = tmp;
System.arraycopy(values, 0, resultArray, 0, k);
}
// We can't use ImmutableList since we want to support null elements.
return Collections.unmodifiableList(Arrays.asList(resultArray));
}
/**
* Returns the {@code k} greatest elements of the given iterable according to
* this ordering, in order from greatest to least. If there are fewer than
* {@code k} elements present, all will be included.
*
* <p>The implementation does not necessarily use a <i>stable</i> sorting
* algorithm; when multiple elements are equivalent, it is undefined which
* will come first.
*
* <p>The implementation requires that all elements of the underlying iterator
* fit into memory at once. If this is not possible, consider using a
* {@link java.util.PriorityQueue} instead.
*
* @return an immutable {@code RandomAccess} list of the {@code k} greatest
* elements in <i>descending order</i>
* @throws IllegalArgumentException if {@code k} is negative
* @since 8.0
*/
@Beta
public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
// TODO(kevinb): see if delegation is hurting performance noticeably
// TODO(kevinb): if we change this implementation, add full unit tests.
return reverse().leastOf(iterable, k);
}
private <E extends T> void quicksortLeastK(
E[] values, int left, int right, int k) {
if (right > left) {
int pivotIndex = (left + right) >>> 1; // left + ((right - left) / 2)
int pivotNewIndex = partition(values, left, right, pivotIndex);
quicksortLeastK(values, left, pivotNewIndex - 1, k);
if (pivotNewIndex < k) {
quicksortLeastK(values, pivotNewIndex + 1, right, k);
}
}
}
private <E extends T> int partition(
E[] values, int left, int right, int pivotIndex) {
E pivotValue = values[pivotIndex];
values[pivotIndex] = values[right];
values[right] = pivotValue;
int storeIndex = left;
for (int i = left; i < right; i++) {
if (compare(values[i], pivotValue) < 0) {
ObjectArrays.swap(values, storeIndex, i);
storeIndex++;
}
}
ObjectArrays.swap(values, right, storeIndex);
return storeIndex;
}
/**
* Returns a copy of the given iterable sorted by this ordering. The input is
* not modified. The returned list is modifiable, serializable, and has random
* access.
*
* <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
* elements that are duplicates according to the comparator. The sort
* performed is <i>stable</i>, meaning that such elements will appear in the
* resulting list in the same order they appeared in the input.
*
* @param iterable the elements to be copied and sorted
* @return a new list containing the given elements in sorted order
*/
public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
@SuppressWarnings("unchecked") // does not escape, and contains only E's
E[] array = (E[]) Iterables.toArray(iterable);
Arrays.sort(array, this);
return Lists.newArrayList(Arrays.asList(array));
}
/**
* Returns an <i>immutable</i> copy of the given iterable sorted by this
* ordering. The input is not modified.
*
* <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
* elements that are duplicates according to the comparator. The sort
* performed is <i>stable</i>, meaning that such elements will appear in the
* resulting list in the same order they appeared in the input.
*
* @param iterable the elements to be copied and sorted
* @return a new immutable list containing the given elements in sorted order
* @throws NullPointerException if {@code iterable} or any of its elements is
* null
* @since 3.0
*/
public <E extends T> ImmutableList<E> immutableSortedCopy(
Iterable<E> iterable) {
@SuppressWarnings("unchecked") // we'll only ever have E's in here
E[] elements = (E[]) Iterables.toArray(iterable);
for (E e : elements) {
checkNotNull(e);
}
Arrays.sort(elements, this);
return ImmutableList.asImmutableList(elements);
}
/**
* Returns {@code true} if each element in {@code iterable} after the first is
* greater than or equal to the element that preceded it, according to this
* ordering. Note that this is always true when the iterable has fewer than
* two elements.
*/
public boolean isOrdered(Iterable<? extends T> iterable) {
Iterator<? extends T> it = iterable.iterator();
if (it.hasNext()) {
T prev = it.next();
while (it.hasNext()) {
T next = it.next();
if (compare(prev, next) > 0) {
return false;
}
prev = next;
}
}
return true;
}
/**
* Returns {@code true} if each element in {@code iterable} after the first is
* <i>strictly</i> greater than the element that preceded it, according to
* this ordering. Note that this is always true when the iterable has fewer
* than two elements.
*/
public boolean isStrictlyOrdered(Iterable<? extends T> iterable) {
Iterator<? extends T> it = iterable.iterator();
if (it.hasNext()) {
T prev = it.next();
while (it.hasNext()) {
T next = it.next();
if (compare(prev, next) >= 0) {
return false;
}
prev = next;
}
}
return true;
}
/**
* {@link Collections#binarySearch(List, Object, Comparator) Searches}
* {@code sortedList} for {@code key} using the binary search algorithm. The
* list must be sorted using this ordering.
*
* @param sortedList the list to be searched
* @param key the key to be searched for
*/
public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
return Collections.binarySearch(sortedList, key, this);
}
/**
* Exception thrown by a {@link Ordering#explicit(List)} or {@link
* Ordering#explicit(Object, Object[])} comparator when comparing a value
* outside the set of values it can compare. Extending {@link
* ClassCastException} may seem odd, but it is required.
*/
// TODO(kevinb): make this public, document it right
@VisibleForTesting
static class IncomparableValueException extends ClassCastException {
final Object value;
IncomparableValueException(Object value) {
super("Cannot compare value: " + value);
this.value = value;
}
private static final long serialVersionUID = 0;
}
// Never make these public
static final int LEFT_IS_GREATER = 1;
static final int RIGHT_IS_GREATER = -1;
}
| Java |
/*
* 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.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* A mapping from keys to values that efficiently supports mapping entire ranges at once. This
* implementation does not support null values.
*
* @author Louis Wasserman
*/
@GwtIncompatible("NavigableMap") final class RangeMap<K extends Comparable, V>
implements Function<K, V>, Serializable {
private final NavigableMap<Cut<K>, RangeValue<K, V>> map;
/**
* Creates a new, empty {@code RangeMap}.
*/
public static <K extends Comparable, V> RangeMap<K, V> create() {
return new RangeMap<K, V>(new TreeMap<Cut<K>, RangeValue<K, V>>());
}
private RangeMap(NavigableMap<Cut<K>, RangeValue<K, V>> map) {
this.map = map;
}
/**
* Equivalent to {@link #get(Comparable) get(K)}, provided only to satisfy the {@link Function}
* interface. When using a reference of type {@code RangeMap}, always invoke
* {@link #get(Comparable) get(K)} directly instead.
*/
@Override
public V apply(K input) {
return get(input);
}
/**
* Returns the value associated with {@code key}, or {@code null} if there is no such value.
*/
@Nullable
public V get(K key) {
Entry<Cut<K>, RangeValue<K, V>> lowerEntry = map.lowerEntry(Cut.aboveValue(key));
if (lowerEntry != null && lowerEntry.getValue().getKey().contains(key)) {
return lowerEntry.getValue().getValue();
}
return null;
}
/**
* Associates {@code value} with every key {@linkplain Range#contains contained} in {@code
* keyRange}.
*
* <p>This method takes amortized <i>O(log n)</i> time.
*/
public void put(Range<K> keyRange, V value) {
checkNotNull(keyRange);
checkNotNull(value);
if (keyRange.isEmpty()) {
return;
}
clear(keyRange);
putRange(new RangeValue<K, V>(keyRange, value));
}
/**
* Puts all the associations from the specified {@code RangeMap} into this {@code RangeMap}.
*/
public void putAll(RangeMap<K, V> rangeMap) {
checkNotNull(rangeMap);
for (RangeValue<K, V> rangeValue : rangeMap.map.values()) {
put(rangeValue.getKey(), rangeValue.getValue());
}
}
/**
* Clears all associations from this {@code RangeMap}.
*/
public void clear() {
map.clear();
}
/**
* Removes all associations to keys {@linkplain Range#contains contained} in {@code
* rangeToClear}.
*/
public void clear(Range<K> rangeToClear) {
checkNotNull(rangeToClear);
if (rangeToClear.isEmpty()) {
return;
}
Entry<Cut<K>, RangeValue<K, V>> lowerThanLB = map.lowerEntry(rangeToClear.lowerBound);
// We will use { } to denote the ends of rangeToClear, and < > to denote the ends of
// other ranges currently in the map. For example, < { > indicates that we know that
// rangeToClear.lowerBound is between the bounds of some range already in the map.
if (lowerThanLB != null) {
RangeValue<K, V> lowerRangeValue = lowerThanLB.getValue();
Cut<K> upperCut = lowerRangeValue.getUpperBound();
if (upperCut.compareTo(rangeToClear.lowerBound) >= 0) { // < { >
RangeValue<K, V> replacement = lowerRangeValue.withUpperBound(rangeToClear.lowerBound);
if (replacement == null) {
removeRange(lowerRangeValue);
} else {
putRange(replacement); // overwrites old range
}
if (upperCut.compareTo(rangeToClear.upperBound) >= 0) { // < { } >
putRange(lowerRangeValue.withLowerBound(rangeToClear.upperBound));
return; // we must be done
}
}
}
Entry<Cut<K>, RangeValue<K, V>> lowerThanUB = map.lowerEntry(rangeToClear.upperBound);
if (lowerThanUB != null) {
RangeValue<K, V> lowerRangeValue = lowerThanUB.getValue();
Cut<K> upperCut = lowerRangeValue.getUpperBound();
if (upperCut.compareTo(rangeToClear.upperBound) >= 0) { // < } >
// we can't have < { } >, we already dealt with that
removeRange(lowerRangeValue);
putRange(lowerRangeValue.withLowerBound(rangeToClear.upperBound));
}
}
// everything left with { < } is a { < > }, so we clear it indiscriminately
map.subMap(rangeToClear.lowerBound, rangeToClear.upperBound).clear();
}
private void removeRange(RangeValue<K, V> rangeValue) {
RangeValue<K, V> removed = map.remove(rangeValue.getLowerBound());
assert removed == rangeValue;
}
private void putRange(@Nullable RangeValue<K, V> rangeValue) {
if (rangeValue != null && !rangeValue.getKey().isEmpty()) {
map.put(rangeValue.getLowerBound(), rangeValue);
}
}
private static final class RangeValue<K extends Comparable, V> extends AbstractMap.SimpleEntry<
Range<K>, V> {
RangeValue(Range<K> key, V value) {
super(checkNotNull(key), checkNotNull(value));
assert !key.isEmpty();
}
Cut<K> getLowerBound() {
return getKey().lowerBound;
}
Cut<K> getUpperBound() {
return getKey().upperBound;
}
@Nullable
RangeValue<K, V> withLowerBound(Cut<K> newLowerBound) {
Range<K> newRange = new Range<K>(newLowerBound, getUpperBound());
return newRange.isEmpty() ? null : new RangeValue<K, V>(newRange, getValue());
}
@Nullable
RangeValue<K, V> withUpperBound(Cut<K> newUpperBound) {
Range<K> newRange = new Range<K>(getLowerBound(), newUpperBound);
return newRange.isEmpty() ? null : new RangeValue<K, V>(newRange, getValue());
}
private static final long serialVersionUID = 0L;
}
/**
* Compares the specified object with this {@code RangeMap} for equality. It is guaranteed that:
* <ul>
* <li>The relation defined by this method is reflexive, symmetric, and transitive, as required
* by the contract of {@link Object#equals(Object)}.
* <li>Two empty range maps are always equal.
* <li>If two range maps are equal, and the same operation is performed on each, the resulting
* range maps are also equal.
* <li>If {@code rangeMap1.equals(rangeMap2)}, it is guaranteed that {@code rangeMap1.get(k)}
* is equal to {@code rangeMap2.get(k)}.
* </ul>
*/
@Override
public boolean equals(@Nullable Object o) {
return o instanceof RangeMap && map.equals(((RangeMap) o).map);
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public String toString() {
return map.toString();
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.ListIterator;
/**
* An iterator that transforms a backing list iterator; for internal use. This
* avoids the object overhead of constructing a {@link Function} for internal
* methods.
*
* @author Louis Wasserman
*/
@GwtCompatible
abstract class TransformedListIterator<F, T> extends TransformedIterator<F, T>
implements ListIterator<T> {
TransformedListIterator(ListIterator<? extends F> backingIterator) {
super(backingIterator);
}
private ListIterator<? extends F> backingIterator() {
return Iterators.cast(backingIterator);
}
@Override
public final boolean hasPrevious() {
return backingIterator().hasPrevious();
}
@Override
public final T previous() {
return transform(backingIterator().previous());
}
@Override
public final int nextIndex() {
return backingIterator().nextIndex();
}
@Override
public final int previousIndex() {
return backingIterator().previousIndex();
}
@Override
public void set(T element) {
throw new UnsupportedOperationException();
}
@Override
public void add(T element) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
/**
* {@code values()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class ImmutableMapValues<K, V> extends ImmutableCollection<V> {
ImmutableMapValues() {}
abstract ImmutableMap<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public UnmodifiableIterator<V> iterator() {
return Maps.valueIterator(map().entrySet().iterator());
}
@Override
public boolean contains(Object object) {
return map().containsValue(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
ImmutableList<V> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map().entrySet().asList();
return new ImmutableAsList<V>() {
@Override
public V get(int index) {
return entryList.get(index).getValue();
}
@Override
ImmutableCollection<V> delegateCollection() {
return ImmutableMapValues.this;
}
};
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new SerializedForm<V>(map());
}
@GwtIncompatible("serialization")
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
SerializedForm(ImmutableMap<?, V> map) {
this.map = map;
}
Object readResolve() {
return map.values();
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
/**
* An iterator which forwards all its method calls to another iterator.
* Subclasses should override one or more methods to modify the behavior of the
* backing iterator as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingIterator<T>
extends ForwardingObject implements Iterator<T> {
/** Constructor for use by subclasses. */
protected ForwardingIterator() {}
@Override protected abstract Iterator<T> delegate();
@Override
public boolean hasNext() {
return delegate().hasNext();
}
@Override
public T next() {
return delegate().next();
}
@Override
public void remove() {
delegate().remove();
}
}
| Java |
/*
* 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 java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
/**
* Provides static methods for serializing collection classes.
*
* <p>This class assists the implementation of collection classes. Do not use
* this class to serialize collections that are defined elsewhere.
*
* @author Jared Levy
*/
final class Serialization {
private Serialization() {}
/**
* Reads a count corresponding to a serialized map, multiset, or multimap. It
* returns the size of a map serialized by {@link
* #writeMap(Map, ObjectOutputStream)}, the number of distinct elements in a
* multiset serialized by {@link
* #writeMultiset(Multiset, ObjectOutputStream)}, or the number of distinct
* keys in a multimap serialized by {@link
* #writeMultimap(Multimap, ObjectOutputStream)}.
*
* <p>The returned count may be used to construct an empty collection of the
* appropriate capacity before calling any of the {@code populate} methods.
*/
static int readCount(ObjectInputStream stream) throws IOException {
return stream.readInt();
}
/**
* Stores the contents of a map in an output stream, as part of serialization.
* It does not support concurrent maps whose content may change while the
* method is running.
*
* <p>The serialized output consists of the number of entries, first key,
* first value, second key, second value, and so on.
*/
static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream)
throws IOException {
stream.writeInt(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
/**
* Populates a map by reading an input stream, as part of deserialization.
* See {@link #writeMap} for the data format.
*/
static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream)
throws IOException, ClassNotFoundException {
int size = stream.readInt();
populateMap(map, stream, size);
}
/**
* Populates a map by reading an input stream, as part of deserialization.
* See {@link #writeMap} for the data format. The size is determined by a
* prior call to {@link #readCount}.
*/
static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream,
int size) throws IOException, ClassNotFoundException {
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeMap
K key = (K) stream.readObject();
@SuppressWarnings("unchecked") // reading data stored by writeMap
V value = (V) stream.readObject();
map.put(key, value);
}
}
/**
* Stores the contents of a multiset in an output stream, as part of
* serialization. It does not support concurrent multisets whose content may
* change while the method is running.
*
* <p>The serialized output consists of the number of distinct elements, the
* first element, its count, the second element, its count, and so on.
*/
static <E> void writeMultiset(
Multiset<E> multiset, ObjectOutputStream stream) throws IOException {
int entryCount = multiset.entrySet().size();
stream.writeInt(entryCount);
for (Multiset.Entry<E> entry : multiset.entrySet()) {
stream.writeObject(entry.getElement());
stream.writeInt(entry.getCount());
}
}
/**
* Populates a multiset by reading an input stream, as part of
* deserialization. See {@link #writeMultiset} for the data format.
*/
static <E> void populateMultiset(
Multiset<E> multiset, ObjectInputStream stream)
throws IOException, ClassNotFoundException {
int distinctElements = stream.readInt();
populateMultiset(multiset, stream, distinctElements);
}
/**
* Populates a multiset by reading an input stream, as part of
* deserialization. See {@link #writeMultiset} for the data format. The number
* of distinct elements is determined by a prior call to {@link #readCount}.
*/
static <E> void populateMultiset(
Multiset<E> multiset, ObjectInputStream stream, int distinctElements)
throws IOException, ClassNotFoundException {
for (int i = 0; i < distinctElements; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeMultiset
E element = (E) stream.readObject();
int count = stream.readInt();
multiset.add(element, count);
}
}
/**
* Stores the contents of a multimap in an output stream, as part of
* serialization. It does not support concurrent multimaps whose content may
* change while the method is running. The {@link Multimap#asMap} view
* determines the ordering in which data is written to the stream.
*
* <p>The serialized output consists of the number of distinct keys, and then
* for each distinct key: the key, the number of values for that key, and the
* key's values.
*/
static <K, V> void writeMultimap(
Multimap<K, V> multimap, ObjectOutputStream stream) throws IOException {
stream.writeInt(multimap.asMap().size());
for (Map.Entry<K, Collection<V>> entry : multimap.asMap().entrySet()) {
stream.writeObject(entry.getKey());
stream.writeInt(entry.getValue().size());
for (V value : entry.getValue()) {
stream.writeObject(value);
}
}
}
/**
* Populates a multimap by reading an input stream, as part of
* deserialization. See {@link #writeMultimap} for the data format.
*/
static <K, V> void populateMultimap(
Multimap<K, V> multimap, ObjectInputStream stream)
throws IOException, ClassNotFoundException {
int distinctKeys = stream.readInt();
populateMultimap(multimap, stream, distinctKeys);
}
/**
* Populates a multimap by reading an input stream, as part of
* deserialization. See {@link #writeMultimap} for the data format. The number
* of distinct keys is determined by a prior call to {@link #readCount}.
*/
static <K, V> void populateMultimap(
Multimap<K, V> multimap, ObjectInputStream stream, int distinctKeys)
throws IOException, ClassNotFoundException {
for (int i = 0; i < distinctKeys; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeMultimap
K key = (K) stream.readObject();
Collection<V> values = multimap.get(key);
int valueCount = stream.readInt();
for (int j = 0; j < valueCount; j++) {
@SuppressWarnings("unchecked") // reading data stored by writeMultimap
V value = (V) stream.readObject();
values.add(value);
}
}
}
// Secret sauce for setting final fields; don't make it public.
static <T> FieldSetter<T> getFieldSetter(
final Class<T> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
return new FieldSetter<T>(field);
} catch (NoSuchFieldException e) {
throw new AssertionError(e); // programmer error
}
}
// Secret sauce for setting final fields; don't make it public.
static final class FieldSetter<T> {
private final Field field;
private FieldSetter(Field field) {
this.field = field;
field.setAccessible(true);
}
void set(T instance, Object value) {
try {
field.set(instance, value);
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
void set(T instance, int value) {
try {
field.set(instance, value);
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Collection;
import java.util.EnumSet;
/**
* Implementation of {@link ImmutableSet} backed by a non-empty {@link
* java.util.EnumSet}.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
/*
* Notes on EnumSet and <E extends Enum<E>>:
*
* This class isn't an arbitrary ForwardingImmutableSet because we need to
* know that calling {@code clone()} during deserialization will return an
* object that no one else has a reference to, allowing us to guarantee
* immutability. Hence, we support only {@link EnumSet}.
*/
private final transient EnumSet<E> delegate;
ImmutableEnumSet(EnumSet<E> delegate) {
this.delegate = delegate;
}
@Override boolean isPartialView() {
return false;
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override
public int size() {
return delegate.size();
}
@Override public boolean contains(Object object) {
return delegate.contains(object);
}
@Override public boolean containsAll(Collection<?> collection) {
return delegate.containsAll(collection);
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public Object[] toArray() {
return delegate.toArray();
}
@Override public <T> T[] toArray(T[] array) {
return delegate.toArray(array);
}
@Override public boolean equals(Object object) {
return object == this || delegate.equals(object);
}
private transient int hashCode;
@Override public int hashCode() {
int result = hashCode;
return (result == 0) ? hashCode = delegate.hashCode() : result;
}
@Override public String toString() {
return delegate.toString();
}
// All callers of the constructor are restricted to <E extends Enum<E>>.
@Override Object writeReplace() {
return new EnumSerializedForm<E>(delegate);
}
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
private static class EnumSerializedForm<E extends Enum<E>>
implements Serializable {
final EnumSet<E> delegate;
EnumSerializedForm(EnumSet<E> delegate) {
this.delegate = delegate;
}
Object readResolve() {
// EJ2 #76: Write readObject() methods defensively.
return new ImmutableEnumSet<E>(delegate.clone());
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An immutable {@link BiMap} with reliable user-specified iteration order. Does
* not permit null keys or values. An {@code ImmutableBiMap} and its inverse
* have the same iteration ordering.
*
* <p>An instance of {@code ImmutableBiMap} contains its own data and will
* <i>never</i> change. {@code ImmutableBiMap} is convenient for
* {@code public static final} maps ("constant maps") and also lets you easily
* make a "defensive copy" of a bimap provided to your class by a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class are
* guaranteed to be immutable.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V>
implements BiMap<K, V> {
/**
* Returns the empty bimap.
*/
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableBiMap<K, V> of() {
return (ImmutableBiMap<K, V>) EmptyImmutableBiMap.INSTANCE;
}
/**
* Returns an immutable bimap containing a single entry.
*/
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(k1, v1));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(k1, v1, k2, v2));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(
k1, v1, k2, v2, k3, v3));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(
k1, v1, k2, v2, k3, v3, k4, v4));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(
k1, v1, k2, v2, k3, v3, k4, v4, k5, v5));
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* A builder for creating immutable bimap instances, especially {@code public
* static final} bimaps ("constant bimaps"). Example: <pre> {@code
*
* static final ImmutableBiMap<String, Integer> WORD_TO_INT =
* new ImmutableBiMap.Builder<String, Integer>()
* .put("one", 1)
* .put("two", 2)
* .put("three", 3)
* .build();}</pre>
*
* For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods
* are even more convenient.
*
* <p>Builder instances can be reused - it is safe to call {@link #build}
* multiple times to build multiple bimaps in series. Each bimap is a superset
* of the bimaps created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableBiMap#builder}.
*/
public Builder() {}
/**
* Associates {@code key} with {@code value} in the built bimap. Duplicate
* keys or values are not allowed, and will cause {@link #build} to fail.
*/
@Override public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
/**
* Associates all of the given map's keys and values in the built bimap.
* Duplicate keys or values are not allowed, and will cause {@link #build}
* to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
@Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
super.putAll(map);
return this;
}
/**
* Returns a newly-created immutable bimap.
*
* @throws IllegalArgumentException if duplicate keys or values were added
*/
@Override public ImmutableBiMap<K, V> build() {
ImmutableMap<K, V> map = super.build();
if (map.isEmpty()) {
return of();
}
return new RegularImmutableBiMap<K, V>(map);
}
}
/**
* Returns an immutable bimap containing the same entries as {@code map}. If
* {@code map} somehow contains entries with duplicate keys (for example, if
* it is a {@code SortedMap} whose comparator is not <i>consistent with
* equals</i>), the results of this method are undefined.
*
* <p>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 IllegalArgumentException if two keys have the same value
* @throws NullPointerException if any key or value in {@code map} is null
*/
public static <K, V> ImmutableBiMap<K, V> copyOf(
Map<? extends K, ? extends V> map) {
if (map instanceof ImmutableBiMap) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
// TODO(user): if we need to make a copy of a BiMap because the
// forward map is a view, don't make a copy of the non-view delegate map
if (!bimap.isPartialView()) {
return bimap;
}
}
if (map.isEmpty()) {
return of();
}
ImmutableMap<K, V> immutableMap = ImmutableMap.copyOf(map);
return new RegularImmutableBiMap<K, V>(immutableMap);
}
ImmutableBiMap() {}
abstract ImmutableMap<K, V> delegate();
/**
* {@inheritDoc}
*
* <p>The inverse of an {@code ImmutableBiMap} is another
* {@code ImmutableBiMap}.
*/
@Override
public abstract ImmutableBiMap<V, K> inverse();
@Override public boolean containsKey(@Nullable Object key) {
return delegate().containsKey(key);
}
@Override public boolean containsValue(@Nullable Object value) {
return inverse().containsKey(value);
}
@Override ImmutableSet<Entry<K, V>> createEntrySet() {
return delegate().entrySet();
}
@Override public V get(@Nullable Object key) {
return delegate().get(key);
}
@Override public ImmutableSet<K> keySet() {
return delegate().keySet();
}
/**
* Returns an immutable set of the values in this map. The values are in the
* same order as the parameters used to build this map.
*/
@Override public ImmutableSet<V> values() {
return inverse().keySet();
}
/**
* Guaranteed to throw an exception and leave the bimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
@Override public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public int size() {
return delegate().size();
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
@Override public String toString() {
return delegate().toString();
}
/**
* Serialized type for all ImmutableBiMap instances. It captures the logical
* contents and they are reconstructed using public factory methods. This
* ensures that the implementation types remain as implementation details.
*
* Since the bimap is immutable, ImmutableBiMap doesn't require special logic
* for keeping the bimap and its inverse in sync during serialization, the way
* AbstractBiMap does.
*/
private static class SerializedForm extends ImmutableMap.SerializedForm {
SerializedForm(ImmutableBiMap<?, ?> bimap) {
super(bimap);
}
@Override Object readResolve() {
Builder<Object, Object> builder = new Builder<Object, Object>();
return createMap(builder);
}
private static final long serialVersionUID = 0;
}
@Override Object writeReplace() {
return new SerializedForm(this);
}
}
| Java |
/*
* 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.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Predicate;
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some
* {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not
* possible to <i>iterate</i> over these contained values unless an appropriate {@link
* DiscreteDomain} can be provided to the {@link #asSet asSet} method.
*
* <h3>Types of ranges</h3>
*
* <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated
* <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the
* endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each
* side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket
* ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means
* it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all
* <i>x</i> such that <i>statement</i>.")
*
* <blockquote><table>
* <tr><td><b>Notation</b> <td><b>Definition</b> <td><b>Factory method</b>
* <tr><td>{@code (a..b)} <td>{@code {x | a < x < b}} <td>{@link Range#open open}
* <tr><td>{@code [a..b]} <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed}
* <tr><td>{@code (a..b]} <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed}
* <tr><td>{@code [a..b)} <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen}
* <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}} <td>{@link Range#greaterThan greaterThan}
* <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}} <td>{@link Range#atLeast atLeast}
* <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}} <td>{@link Range#lessThan lessThan}
* <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}} <td>{@link Range#atMost atMost}
* <tr><td>{@code (-∞..+∞)}<td>{@code {x}} <td>{@link Range#all all}
* </table></blockquote>
*
* <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints
* may be equal only if at least one of the bounds is closed:
*
* <ul>
* <li>{@code [a..a]} : a singleton range
* <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid
* <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown
* </ul>
*
* <h3>Warnings</h3>
*
* <ul>
* <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do
* not</b> allow the endpoint instances to mutate after the range is created!
* <li>Your value type's comparison method should be {@linkplain Comparable consistent with equals}
* if at all possible. Otherwise, be aware that concepts used throughout this documentation such
* as "equal", "same", "unique" and so on actually refer to whether {@link Comparable#compareTo
* compareTo} returns zero, not whether {@link Object#equals equals} returns {@code true}.
* <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause
* undefined horrible things to happen in {@code Range}. For now, the Range API does not prevent
* its use, because this would also rule out all ungenerified (pre-JDK1.5) data types. <b>This
* may change in the future.</b>
* </ul>
*
* <h3>Other notes</h3>
*
* <ul>
* <li>Instances of this type are obtained using the static factory methods in this class.
* <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them must
* also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C}, {@code
* r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a {@code
* Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from 1 to
* 100."
* <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link
* #contains}.
* <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property
* <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}.
* Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having
* property <i>P</i>. See, for example, the definition of {@link #intersection intersection}.
* </ul>
*
* <h3>Further reading</h3>
*
* <p>See the Guava User Guide article on
* <a href="http://code.google.com/p/guava-libraries/wiki/RangesExplained">{@code Range}</a>.
*
* @author Kevin Bourrillion
* @author Gregory Kick
* @since 10.0
*/
@Beta
@GwtCompatible
@SuppressWarnings("rawtypes")
public final class Range<C extends Comparable> implements Predicate<C>, Serializable {
static <C extends Comparable<?>> Range<C> create(
Cut<C> lowerBound, Cut<C> upperBound) {
return new Range<C>(lowerBound, upperBound);
}
/**
* Returns a range that contains all values strictly greater than {@code
* lower} and strictly less than {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than <i>or
* equal to</i> {@code upper}
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> open(C lower, C upper) {
return create(Cut.aboveValue(lower), Cut.belowValue(upper));
}
/**
* Returns a range that contains all values greater than or equal to
* {@code lower} and less than or equal to {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) {
return create(Cut.belowValue(lower), Cut.aboveValue(upper));
}
/**
* Returns a range that contains all values greater than or equal to
* {@code lower} and strictly less than {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> closedOpen(
C lower, C upper) {
return create(Cut.belowValue(lower), Cut.belowValue(upper));
}
/**
* Returns a range that contains all values strictly greater than {@code
* lower} and less than or equal to {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> openClosed(
C lower, C upper) {
return create(Cut.aboveValue(lower), Cut.aboveValue(upper));
}
/**
* Returns a range that contains any value from {@code lower} to {@code
* upper}, where each endpoint may be either inclusive (closed) or exclusive
* (open).
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> range(
C lower, BoundType lowerType, C upper, BoundType upperType) {
checkNotNull(lowerType);
checkNotNull(upperType);
Cut<C> lowerBound = (lowerType == BoundType.OPEN)
? Cut.aboveValue(lower)
: Cut.belowValue(lower);
Cut<C> upperBound = (upperType == BoundType.OPEN)
? Cut.belowValue(upper)
: Cut.aboveValue(upper);
return create(lowerBound, upperBound);
}
/**
* Returns a range that contains all values strictly less than {@code
* endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) {
return create(Cut.<C>belowAll(), Cut.belowValue(endpoint));
}
/**
* Returns a range that contains all values less than or equal to
* {@code endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> atMost(C endpoint) {
return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint));
}
/**
* Returns a range with no lower bound up to the given endpoint, which may be
* either inclusive (closed) or exclusive (open).
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> upTo(
C endpoint, BoundType boundType) {
switch (boundType) {
case OPEN:
return lessThan(endpoint);
case CLOSED:
return atMost(endpoint);
default:
throw new AssertionError();
}
}
/**
* Returns a range that contains all values strictly greater than {@code
* endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) {
return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll());
}
/**
* Returns a range that contains all values greater than or equal to
* {@code endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) {
return create(Cut.belowValue(endpoint), Cut.<C>aboveAll());
}
/**
* Returns a range from the given endpoint, which may be either inclusive
* (closed) or exclusive (open), with no upper bound.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> downTo(
C endpoint, BoundType boundType) {
switch (boundType) {
case OPEN:
return greaterThan(endpoint);
case CLOSED:
return atLeast(endpoint);
default:
throw new AssertionError();
}
}
/**
* Returns a range that contains every value of type {@code C}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> all() {
return create(Cut.<C>belowAll(), Cut.<C>aboveAll());
}
/**
* Returns a range that {@linkplain Range#contains(Comparable) contains} only
* the given value. The returned range is {@linkplain BoundType#CLOSED closed}
* on both ends.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> singleton(C value) {
return closed(value, value);
}
/**
* Returns the minimal range that
* {@linkplain Range#contains(Comparable) contains} all of the given values.
* The returned range is {@linkplain BoundType#CLOSED closed} on both ends.
*
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i>
* @throws NoSuchElementException if {@code values} is empty
* @throws NullPointerException if any of {@code values} is null
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> encloseAll(
Iterable<C> values) {
checkNotNull(values);
if (values instanceof ContiguousSet) {
return ((ContiguousSet<C>) values).range();
}
Iterator<C> valueIterator = values.iterator();
C min = checkNotNull(valueIterator.next());
C max = min;
while (valueIterator.hasNext()) {
C value = checkNotNull(valueIterator.next());
min = Ordering.natural().min(min, value);
max = Ordering.natural().max(max, value);
}
return closed(min, max);
}
final Cut<C> lowerBound;
final Cut<C> upperBound;
Range(Cut<C> lowerBound, Cut<C> upperBound) {
if (lowerBound.compareTo(upperBound) > 0) {
throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound));
}
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
/**
* Returns {@code true} if this range has a lower endpoint.
*/
public boolean hasLowerBound() {
return lowerBound != Cut.belowAll();
}
/**
* Returns the lower endpoint of this range.
*
* @throws IllegalStateException if this range is unbounded below (that is, {@link
* #hasLowerBound()} returns {@code false})
*/
public C lowerEndpoint() {
return lowerBound.endpoint();
}
/**
* Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes
* its lower endpoint, {@link BoundType#OPEN} if it does not.
*
* @throws IllegalStateException if this range is unbounded below (that is, {@link
* #hasLowerBound()} returns {@code false})
*/
public BoundType lowerBoundType() {
return lowerBound.typeAsLowerBound();
}
/**
* Returns {@code true} if this range has an upper endpoint.
*/
public boolean hasUpperBound() {
return upperBound != Cut.aboveAll();
}
/**
* Returns the upper endpoint of this range.
*
* @throws IllegalStateException if this range is unbounded above (that is, {@link
* #hasUpperBound()} returns {@code false})
*/
public C upperEndpoint() {
return upperBound.endpoint();
}
/**
* Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes
* its upper endpoint, {@link BoundType#OPEN} if it does not.
*
* @throws IllegalStateException if this range is unbounded above (that is, {@link
* #hasUpperBound()} returns {@code false})
*/
public BoundType upperBoundType() {
return upperBound.typeAsUpperBound();
}
/**
* Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does
* not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and
* can't be constructed at all.)
*
* <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b>
* considered empty, even though they contain no actual values.
*/
public boolean isEmpty() {
return lowerBound.equals(upperBound);
}
/**
* Returns {@code true} if {@code value} is within the bounds of this range. For example, on the
* range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)}
* returns {@code false}.
*/
public boolean contains(C value) {
checkNotNull(value);
// let this throw CCE if there is some trickery going on
return lowerBound.isLessThan(value) && !upperBound.isLessThan(value);
}
/**
* Equivalent to {@link #contains}; provided only to satisfy the {@link Predicate} interface. When
* using a reference of type {@code Range}, always invoke {@link #contains} directly instead.
*/
@Override public boolean apply(C input) {
return contains(input);
}
/**
* Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in
* this range.
*/
public boolean containsAll(Iterable<? extends C> values) {
if (Iterables.isEmpty(values)) {
return true;
}
// this optimizes testing equality of two range-backed sets
if (values instanceof SortedSet) {
SortedSet<? extends C> set = cast(values);
Comparator<?> comparator = set.comparator();
if (Ordering.natural().equals(comparator) || comparator == null) {
return contains(set.first()) && contains(set.last());
}
}
for (C value : values) {
if (!contains(value)) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this
* range. Examples:
*
* <ul>
* <li>{@code [3..6]} encloses {@code [4..5]}
* <li>{@code (3..6)} encloses {@code (3..6)}
* <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty)
* <li>{@code (3..6]} does not enclose {@code [3..6]}
* <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value
* contained by the latter range)
* <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value
* contained by the latter range)
* </ul>
*
* Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies {@code a.contains(v)},
* but as the last two examples illustrate, the converse is not always true.
*
* <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a
* <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range
* according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure
* also implies {@linkplain #isConnected connectedness}.
*/
public boolean encloses(Range<C> other) {
return lowerBound.compareTo(other.lowerBound) <= 0
&& upperBound.compareTo(other.upperBound) >= 0;
}
/**
* Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses
* enclosed} by both this range and {@code other}.
*
* <p>For example,
* <ul>
* <li>{@code [2, 4)} and {@code [5, 7)} are not connected
* <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)}
* <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range
* {@code [4, 4)}
* </ul>
*
* <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and
* {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this
* method returns {@code true}.
*
* <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain
* Equivalence equivalence relation} as it is not transitive.
*/
public boolean isConnected(Range<C> other) {
return lowerBound.compareTo(other.upperBound) <= 0
&& other.lowerBound.compareTo(upperBound) <= 0;
}
/**
* Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code
* connectedRange}, if such a range exists.
*
* <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The
* resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)}
* yields the empty range {@code [5..5)}.
*
* <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected
* connected}.
*
* <p>The intersection operation is commutative, associative and idempotent, and its identity
* element is {@link Range#all}).
*
* @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false}
*/
public Range<C> intersection(Range<C> connectedRange) {
Cut<C> newLower = Ordering.natural().max(lowerBound, connectedRange.lowerBound);
Cut<C> newUpper = Ordering.natural().min(upperBound, connectedRange.upperBound);
return create(newLower, newUpper);
}
/**
* Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code
* other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}.
*
* <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can
* also be called their <i>union</i>. If they are not, note that the span might contain values
* that are not contained in either input range.
*
* <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative
* and idempotent. Unlike it, it is always well-defined for any two input ranges.
*/
public Range<C> span(Range<C> other) {
Cut<C> newLower = Ordering.natural().min(lowerBound, other.lowerBound);
Cut<C> newUpper = Ordering.natural().max(upperBound, other.upperBound);
return create(newLower, newUpper);
}
/**
* Returns an {@link ContiguousSet} containing the same values in the given domain
* {@linkplain Range#contains contained} by this range.
*
* <p><b>Note:</b> {@code a.asSet(d).equals(b.asSet(d))} does not imply {@code a.equals(b)}! For
* example, {@code a} and {@code b} could be {@code [2..4]} and {@code (1..5)}, or the empty
* ranges {@code [3..3)} and {@code [4..4)}.
*
* <p><b>Warning:</b> Be extremely careful what you do with the {@code asSet} view of a large
* range (such as {@code Range.greaterThan(0)}). Certain operations on such a set can be
* performed efficiently, but others (such as {@link Set#hashCode} or {@link
* Collections#frequency}) can cause major performance problems.
*
* <p>The returned set's {@link Object#toString} method returns a short-hand form of the set's
* contents, such as {@code "[1..100]}"}.
*
* @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if
* neither has an upper bound
*/
// TODO(kevinb): commit in spec to which methods are efficient?
@GwtCompatible(serializable = false)
public ContiguousSet<C> asSet(DiscreteDomain<C> domain) {
return ContiguousSet.create(this, domain);
}
/**
* Returns the canonical form of this range in the given domain. The canonical form has the
* following properties:
*
* <ul>
* <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in other
* words, {@code a.canonical(domain).asSet(domain).equals(a.asSet(domain))}
* <li>uniqueness: unless {@code a.isEmpty()}, {@code a.asSet(domain).equals(b.asSet(domain))}
* implies {@code a.canonical(domain).equals(b.canonical(domain))}
* <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))}
* </ul>
*
* Furthermore, this method guarantees that the range returned will be one of the following
* canonical forms:
*
* <ul>
* <li>[start..end)
* <li>[start..+∞)
* <li>(-∞..end) (only if type {@code C} is unbounded below)
* <li>(-∞..+∞) (only if type {@code C} is unbounded below)
* </ul>
*/
public Range<C> canonical(DiscreteDomain<C> domain) {
checkNotNull(domain);
Cut<C> lower = lowerBound.canonical(domain);
Cut<C> upper = upperBound.canonical(domain);
return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper);
}
/**
* Returns {@code true} if {@code object} is a range having the same endpoints and bound types as
* this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b>
* equal to one another, despite the fact that they each contain precisely the same set of values.
* Similarly, empty ranges are not equal unless they have exactly the same representation, so
* {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal.
*/
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Range) {
Range<?> other = (Range<?>) object;
return lowerBound.equals(other.lowerBound)
&& upperBound.equals(other.upperBound);
}
return false;
}
/** Returns a hash code for this range. */
@Override public int hashCode() {
return lowerBound.hashCode() * 31 + upperBound.hashCode();
}
/**
* Returns a string representation of this range, such as {@code "[3..5)"} (other examples are
* listed in the class documentation).
*/
@Override public String toString() {
return toString(lowerBound, upperBound);
}
private static String toString(Cut<?> lowerBound, Cut<?> upperBound) {
StringBuilder sb = new StringBuilder(16);
lowerBound.describeAsLowerBound(sb);
sb.append('\u2025');
upperBound.describeAsUpperBound(sb);
return sb.toString();
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
private static <T> SortedSet<T> cast(Iterable<T> iterable) {
return (SortedSet<T>) iterable;
}
@SuppressWarnings("unchecked") // this method may throw CCE
static int compareOrThrow(Comparable left, Comparable right) {
return left.compareTo(right);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2012 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 java.util.Iterator;
/**
* An iterator that transforms a backing iterator; for internal use. This avoids
* the object overhead of constructing a {@link Function} for internal methods.
*
* @author Louis Wasserman
*/
@GwtCompatible
abstract class TransformedIterator<F, T> implements Iterator<T> {
final Iterator<? extends F> backingIterator;
TransformedIterator(Iterator<? extends F> backingIterator) {
this.backingIterator = checkNotNull(backingIterator);
}
abstract T transform(F from);
@Override
public final boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public final T next() {
return transform(backingIterator.next());
}
@Override
public final void remove() {
backingIterator.remove();
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An empty contiguous set.
*
* @author Gregory Kick
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("unchecked") // allow ungenerified Comparable types
final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> {
EmptyContiguousSet(DiscreteDomain<C> domain) {
super(domain);
}
@Override public C first() {
throw new NoSuchElementException();
}
@Override public C last() {
throw new NoSuchElementException();
}
@Override public int size() {
return 0;
}
@Override public ContiguousSet<C> intersection(ContiguousSet<C> other) {
return this;
}
@Override public Range<C> range() {
throw new NoSuchElementException();
}
@Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) {
throw new NoSuchElementException();
}
@Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) {
return this;
}
@Override ContiguousSet<C> subSetImpl(
C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) {
return this;
}
@Override ContiguousSet<C> tailSetImpl(C fromElement, boolean fromInclusive) {
return this;
}
@GwtIncompatible("not used by GWT emulation")
@Override int indexOf(Object target) {
return -1;
}
@Override public UnmodifiableIterator<C> iterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
@Override public boolean isEmpty() {
return true;
}
@Override public ImmutableList<C> asList() {
return ImmutableList.of();
}
@Override public String toString() {
return "[]";
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.isEmpty();
}
return false;
}
@Override public int hashCode() {
return 0;
}
@GwtIncompatible("serialization")
private static final class SerializedForm<C extends Comparable> implements Serializable {
private final DiscreteDomain<C> domain;
private SerializedForm(DiscreteDomain<C> domain) {
this.domain = domain;
}
private Object readResolve() {
return new EmptyContiguousSet<C>(domain);
}
private static final long serialVersionUID = 0;
}
@GwtIncompatible("serialization")
@Override
Object writeReplace() {
return new SerializedForm<C>(domain);
}
@GwtIncompatible("NavigableSet")
ImmutableSortedSet<C> createDescendingSet() {
return new EmptyImmutableSortedSet<C>(Ordering.natural().reverse());
}
}
| Java |
/*
* Copyright (C) 2007 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 static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Multisets.checkNonnegative;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Serialization.FieldSetter;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* A multiset that supports concurrent modifications and that provides atomic versions of most
* {@code Multiset} operations (exceptions where noted). Null elements are not supported.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Cliff L. Biffle
* @author mike nonemacher
* @since 2.0 (imported from Google Collections Library)
*/
public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable {
/*
* The ConcurrentHashMultiset's atomic operations are implemented primarily in terms of
* AtomicInteger's atomic operations, with some help from ConcurrentMap's atomic operations on
* creation and removal (including automatic removal of zeroes). If the modification of an
* AtomicInteger results in zero, we compareAndSet the value to zero; if that succeeds, we remove
* the entry from the Map. If another operation sees a zero in the map, it knows that the entry is
* about to be removed, so this operation may remove it (often by replacing it with a new
* AtomicInteger).
*/
/** The number of occurrences of each element. */
private final transient ConcurrentMap<E, AtomicInteger> countMap;
// This constant allows the deserialization code to set a final field. This holder class
// makes sure it is not initialized unless an instance is deserialized.
private static class FieldSettersHolder {
static final FieldSetter<ConcurrentHashMultiset> COUNT_MAP_FIELD_SETTER =
Serialization.getFieldSetter(ConcurrentHashMultiset.class, "countMap");
}
/**
* Creates a new, empty {@code ConcurrentHashMultiset} using the default
* initial capacity, load factor, and concurrency settings.
*/
public static <E> ConcurrentHashMultiset<E> create() {
// TODO(schmoe): provide a way to use this class with other (possibly arbitrary)
// ConcurrentMap implementors. One possibility is to extract most of this class into
// an AbstractConcurrentMapMultiset.
return new ConcurrentHashMultiset<E>(new ConcurrentHashMap<E, AtomicInteger>());
}
/**
* Creates a new {@code ConcurrentHashMultiset} containing the specified elements, using
* the default initial capacity, load factor, and concurrency settings.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
*/
public static <E> ConcurrentHashMultiset<E> create(Iterable<? extends E> elements) {
ConcurrentHashMultiset<E> multiset = ConcurrentHashMultiset.create();
Iterables.addAll(multiset, elements);
return multiset;
}
/**
* Creates a new, empty {@code ConcurrentHashMultiset} using {@code mapMaker}
* to construct the internal backing map.
*
* <p>If this {@link MapMaker} is configured to use entry eviction of any kind, this eviction
* applies to all occurrences of a given element as a single unit. However, most updates to the
* multiset do not count as map updates at all, since we're usually just mutating the value
* stored in the map, so {@link MapMaker#expireAfterAccess} makes sense (evict the entry that
* was queried or updated longest ago), but {@link MapMaker#expireAfterWrite} doesn't, because
* the eviction time is measured from when we saw the first occurrence of the object.
*
* <p>The returned multiset is serializable but any serialization caveats
* given in {@code MapMaker} apply.
*
* <p>Finally, soft/weak values can be used but are not very useful: the values are created
* internally and not exposed externally, so no one else will have a strong reference to the
* values. Weak keys on the other hand can be useful in some scenarios.
*
* @since 7.0
*/
@Beta
public static <E> ConcurrentHashMultiset<E> create(
GenericMapMaker<? super E, ? super Number> mapMaker) {
return new ConcurrentHashMultiset<E>(mapMaker.<E, AtomicInteger>makeMap());
}
/**
* Creates an instance using {@code countMap} to store elements and their counts.
*
* <p>This instance will assume ownership of {@code countMap}, and other code
* should not maintain references to the map or modify it in any way.
*
* @param countMap backing map for storing the elements in the multiset and
* their counts. It must be empty.
* @throws IllegalArgumentException if {@code countMap} is not empty
*/
@VisibleForTesting ConcurrentHashMultiset(ConcurrentMap<E, AtomicInteger> countMap) {
checkArgument(countMap.isEmpty());
this.countMap = countMap;
}
// Query Operations
/**
* Returns the number of occurrences of {@code element} in this multiset.
*
* @param element the element to look for
* @return the nonnegative number of occurrences of the element
*/
@Override public int count(@Nullable Object element) {
AtomicInteger existingCounter = safeGet(element);
return (existingCounter == null) ? 0 : existingCounter.get();
}
/**
* Depending on the type of the underlying map, map.get may throw NullPointerException or
* ClassCastException, if the object is null or of the wrong type. We usually just want to treat
* those cases as if the element isn't in the map, by catching the exceptions and returning null.
*/
private AtomicInteger safeGet(Object element) {
try {
return countMap.get(element);
} catch (NullPointerException e) {
return null;
} catch (ClassCastException e) {
return null;
}
}
/**
* {@inheritDoc}
*
* <p>If the data in the multiset is modified by any other threads during this method,
* it is undefined which (if any) of these modifications will be reflected in the result.
*/
@Override public int size() {
long sum = 0L;
for (AtomicInteger value : countMap.values()) {
sum += value.get();
}
return Ints.saturatedCast(sum);
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override public Object[] toArray() {
return snapshot().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
/*
* We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but
* either of these would recurse back to us again!
*/
private List<E> snapshot() {
List<E> list = Lists.newArrayListWithExpectedSize(size());
for (Multiset.Entry<E> entry : entrySet()) {
E element = entry.getElement();
for (int i = entry.getCount(); i > 0; i--) {
list.add(element);
}
}
return list;
}
// Modification Operations
/**
* Adds a number of occurrences of the specified element to this multiset.
*
* @param element the element to add
* @param occurrences the number of occurrences to add
* @return the previous count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative, or if
* the resulting amount would exceed {@link Integer#MAX_VALUE}
*/
@Override public int add(E element, int occurrences) {
checkNotNull(element);
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
AtomicInteger existingCounter = safeGet(element);
if (existingCounter == null) {
existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences));
if (existingCounter == null) {
return 0;
}
// existingCounter != null: fall through to operate against the existing AtomicInteger
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue != 0) {
try {
int newValue = IntMath.checkedAdd(oldValue, occurrences);
if (existingCounter.compareAndSet(oldValue, newValue)) {
// newValue can't == 0, so no need to check & remove
return oldValue;
}
} catch (ArithmeticException overflow) {
throw new IllegalArgumentException("Overflow adding " + occurrences
+ " occurrences to a count of " + oldValue);
}
} else {
// In the case of a concurrent remove, we might observe a zero value, which means another
// thread is about to remove (element, existingCounter) from the map. Rather than wait,
// we can just do that work here.
AtomicInteger newCounter = new AtomicInteger(occurrences);
if ((countMap.putIfAbsent(element, newCounter) == null)
|| countMap.replace(element, existingCounter, newCounter)) {
return 0;
}
break;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Removes a number of occurrences of the specified element from this multiset. If the multiset
* contains fewer than this number of occurrences to begin with, all occurrences will be removed.
*
* @param element the element whose occurrences should be removed
* @param occurrences the number of occurrences of the element to remove
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
/*
* TODO(cpovirk): remove and removeExactly currently accept null inputs only
* if occurrences == 0. This satisfies both NullPointerTester and
* CollectionRemoveTester.testRemove_nullAllowed, but it's not clear that it's
* a good policy, especially because, in order for the test to pass, the
* parameter must be misleadingly annotated as @Nullable. I suspect that
* we'll want to remove @Nullable, add an eager checkNotNull, and loosen up
* testRemove_nullAllowed.
*/
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
AtomicInteger existingCounter = safeGet(element);
if (existingCounter == null) {
return 0;
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue != 0) {
int newValue = Math.max(0, oldValue - occurrences);
if (existingCounter.compareAndSet(oldValue, newValue)) {
if (newValue == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return oldValue;
}
} else {
return 0;
}
}
}
/**
* Removes exactly the specified number of occurrences of {@code element}, or makes no
* change if this is not possible.
*
* <p>This method, in contrast to {@link #remove(Object, int)}, has no effect when the
* element count is smaller than {@code occurrences}.
*
* @param element the element to remove
* @param occurrences the number of occurrences of {@code element} to remove
* @return {@code true} if the removal was possible (including if {@code occurrences} is zero)
*/
public boolean removeExactly(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return true;
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
AtomicInteger existingCounter = safeGet(element);
if (existingCounter == null) {
return false;
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue < occurrences) {
return false;
}
int newValue = oldValue - occurrences;
if (existingCounter.compareAndSet(oldValue, newValue)) {
if (newValue == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return true;
}
}
}
/**
* Adds or removes occurrences of {@code element} such that the {@link #count} of the
* element becomes {@code count}.
*
* @return the count of {@code element} in the multiset before this call
* @throws IllegalArgumentException if {@code count} is negative
*/
@Override public int setCount(E element, int count) {
checkNotNull(element);
checkNonnegative(count, "count");
while (true) {
AtomicInteger existingCounter = safeGet(element);
if (existingCounter == null) {
if (count == 0) {
return 0;
} else {
existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count));
if (existingCounter == null) {
return 0;
}
// existingCounter != null: fall through
}
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue == 0) {
if (count == 0) {
return 0;
} else {
AtomicInteger newCounter = new AtomicInteger(count);
if ((countMap.putIfAbsent(element, newCounter) == null)
|| countMap.replace(element, existingCounter, newCounter)) {
return 0;
}
}
break;
} else {
if (existingCounter.compareAndSet(oldValue, count)) {
if (count == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return oldValue;
}
}
}
}
}
/**
* Sets the number of occurrences of {@code element} to {@code newCount}, but only if
* the count is currently {@code expectedOldCount}. If {@code element} does not appear
* in the multiset exactly {@code expectedOldCount} times, no changes will be made.
*
* @return {@code true} if the change was successful. This usually indicates
* that the multiset has been modified, but not always: in the case that
* {@code expectedOldCount == newCount}, the method will return {@code true} if
* the condition was met.
* @throws IllegalArgumentException if {@code expectedOldCount} or {@code newCount} is negative
*/
@Override public boolean setCount(E element, int expectedOldCount, int newCount) {
checkNotNull(element);
checkNonnegative(expectedOldCount, "oldCount");
checkNonnegative(newCount, "newCount");
AtomicInteger existingCounter = safeGet(element);
if (existingCounter == null) {
if (expectedOldCount != 0) {
return false;
} else if (newCount == 0) {
return true;
} else {
// if our write lost the race, it must have lost to a nonzero value, so we can stop
return countMap.putIfAbsent(element, new AtomicInteger(newCount)) == null;
}
}
int oldValue = existingCounter.get();
if (oldValue == expectedOldCount) {
if (oldValue == 0) {
if (newCount == 0) {
// Just observed a 0; try to remove the entry to clean up the map
countMap.remove(element, existingCounter);
return true;
} else {
AtomicInteger newCounter = new AtomicInteger(newCount);
return (countMap.putIfAbsent(element, newCounter) == null)
|| countMap.replace(element, existingCounter, newCounter);
}
} else {
if (existingCounter.compareAndSet(oldValue, newCount)) {
if (newCount == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return true;
}
}
}
return false;
}
// Views
@Override Set<E> createElementSet() {
final Set<E> delegate = countMap.keySet();
return new ForwardingSet<E>() {
@Override protected Set<E> delegate() {
return delegate;
}
@Override public boolean remove(Object object) {
try {
return delegate.remove(object);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
};
}
private transient EntrySet entrySet;
@Override public Set<Multiset.Entry<E>> entrySet() {
EntrySet result = entrySet;
if (result == null) {
entrySet = result = new EntrySet();
}
return result;
}
@Override int distinctElements() {
return countMap.size();
}
@Override public boolean isEmpty() {
return countMap.isEmpty();
}
@Override Iterator<Entry<E>> entryIterator() {
// AbstractIterator makes this fairly clean, but it doesn't support remove(). To support
// remove(), we create an AbstractIterator, and then use ForwardingIterator to delegate to it.
final Iterator<Entry<E>> readOnlyIterator =
new AbstractIterator<Entry<E>>() {
private Iterator<Map.Entry<E, AtomicInteger>> mapEntries = countMap.entrySet().iterator();
@Override protected Entry<E> computeNext() {
while (true) {
if (!mapEntries.hasNext()) {
return endOfData();
}
Map.Entry<E, AtomicInteger> mapEntry = mapEntries.next();
int count = mapEntry.getValue().get();
if (count != 0) {
return Multisets.immutableEntry(mapEntry.getKey(), count);
}
}
}
};
return new ForwardingIterator<Entry<E>>() {
private Entry<E> last;
@Override protected Iterator<Entry<E>> delegate() {
return readOnlyIterator;
}
@Override public Entry<E> next() {
last = super.next();
return last;
}
@Override public void remove() {
checkState(last != null);
ConcurrentHashMultiset.this.setCount(last.getElement(), 0);
last = null;
}
};
}
@Override public void clear() {
countMap.clear();
}
private class EntrySet extends AbstractMultiset<E>.EntrySet {
@Override ConcurrentHashMultiset<E> multiset() {
return ConcurrentHashMultiset.this;
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override public Object[] toArray() {
return snapshot().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
private List<Multiset.Entry<E>> snapshot() {
List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size());
// Not Iterables.addAll(list, this), because that'll forward right back here.
Iterators.addAll(list, iterator());
return list;
}
@Override public boolean remove(Object object) {
if (object instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) object;
Object element = entry.getElement();
int entryCount = entry.getCount();
if (entryCount != 0) {
// Safe as long as we never add a new entry, which we won't.
@SuppressWarnings("unchecked")
Multiset<Object> multiset = (Multiset) multiset();
return multiset.setCount(element, entryCount, 0);
}
}
return false;
}
}
/**
* @serialData the ConcurrentMap of elements and their counts.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(countMap);
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
ConcurrentMap<E, Integer> deserializedCountMap =
(ConcurrentMap<E, Integer>) stream.readObject();
FieldSettersHolder.COUNT_MAP_FIELD_SETTER.set(this, deserializedCountMap);
}
private static final long serialVersionUID = 1;
}
| Java |
/*
* Copyright (C) 2007 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.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.primitives.Ints;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* A multiset which maintains the ordering of its elements, according to either their natural order
* or an explicit {@link Comparator}. In all cases, this implementation uses
* {@link Comparable#compareTo} or {@link Comparator#compare} instead of {@link Object#equals} to
* determine equivalence of instances.
*
* <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as explained by the
* {@link Comparable} class specification. Otherwise, the resulting multiset will violate the
* {@link java.util.Collection} contract, which is specified in terms of {@link Object#equals}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Louis Wasserman
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class TreeMultiset<E> extends AbstractSortedMultiset<E> implements Serializable {
/**
* Creates a new, empty multiset, sorted according to the elements' natural order. All elements
* inserted into the multiset must implement the {@code Comparable} interface. Furthermore, all
* such elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the
* user attempts to add an element to the multiset that violates this constraint (for example,
* the user attempts to add a string element to a set whose elements are integers), the
* {@code add(Object)} call will throw a {@code ClassCastException}.
*
* <p>The type specification is {@code <E extends Comparable>}, instead of the more specific
* {@code <E extends Comparable<? super E>>}, to support classes defined without generics.
*/
public static <E extends Comparable> TreeMultiset<E> create() {
return new TreeMultiset<E>(Ordering.natural());
}
/**
* Creates a new, empty multiset, sorted according to the specified comparator. All elements
* inserted into the multiset must be <i>mutually comparable</i> by the specified comparator:
* {@code comparator.compare(e1,
* e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in
* the multiset. If the user attempts to add an element to the multiset that violates this
* constraint, the {@code add(Object)} call will throw a {@code ClassCastException}.
*
* @param comparator
* the comparator that will be used to sort this multiset. A null value indicates that
* the elements' <i>natural ordering</i> should be used.
*/
@SuppressWarnings("unchecked")
public static <E> TreeMultiset<E> create(@Nullable Comparator<? super E> comparator) {
return (comparator == null)
? new TreeMultiset<E>((Comparator) Ordering.natural())
: new TreeMultiset<E>(comparator);
}
/**
* Creates an empty multiset containing the given initial elements, sorted according to the
* elements' natural order.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
*
* <p>The type specification is {@code <E extends Comparable>}, instead of the more specific
* {@code <E extends Comparable<? super E>>}, to support classes defined without generics.
*/
public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) {
TreeMultiset<E> multiset = create();
Iterables.addAll(multiset, elements);
return multiset;
}
private final transient Reference<AvlNode<E>> rootReference;
private final transient GeneralRange<E> range;
private final transient AvlNode<E> header;
TreeMultiset(Reference<AvlNode<E>> rootReference, GeneralRange<E> range, AvlNode<E> endLink) {
super(range.comparator());
this.rootReference = rootReference;
this.range = range;
this.header = endLink;
}
TreeMultiset(Comparator<? super E> comparator) {
super(comparator);
this.range = GeneralRange.all(comparator);
this.header = new AvlNode<E>(null, 1);
successor(header, header);
this.rootReference = new Reference<AvlNode<E>>();
}
/**
* A function which can be summed across a subtree.
*/
private enum Aggregate {
SIZE {
@Override
int nodeAggregate(AvlNode<?> node) {
return node.elemCount;
}
@Override
long treeAggregate(@Nullable AvlNode<?> root) {
return (root == null) ? 0 : root.totalCount;
}
},
DISTINCT {
@Override
int nodeAggregate(AvlNode<?> node) {
return 1;
}
@Override
long treeAggregate(@Nullable AvlNode<?> root) {
return (root == null) ? 0 : root.distinctElements;
}
};
abstract int nodeAggregate(AvlNode<?> node);
abstract long treeAggregate(@Nullable AvlNode<?> root);
}
private long aggregateForEntries(Aggregate aggr) {
AvlNode<E> root = rootReference.get();
long total = aggr.treeAggregate(root);
if (range.hasLowerBound()) {
total -= aggregateBelowRange(aggr, root);
}
if (range.hasUpperBound()) {
total -= aggregateAboveRange(aggr, root);
}
return total;
}
private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode<E> node) {
if (node == null) {
return 0;
}
int cmp = comparator().compare(range.getLowerEndpoint(), node.elem);
if (cmp < 0) {
return aggregateBelowRange(aggr, node.left);
} else if (cmp == 0) {
switch (range.getLowerBoundType()) {
case OPEN:
return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left);
case CLOSED:
return aggr.treeAggregate(node.left);
default:
throw new AssertionError();
}
} else {
return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node)
+ aggregateBelowRange(aggr, node.right);
}
}
private long aggregateAboveRange(Aggregate aggr, @Nullable AvlNode<E> node) {
if (node == null) {
return 0;
}
int cmp = comparator().compare(range.getUpperEndpoint(), node.elem);
if (cmp > 0) {
return aggregateAboveRange(aggr, node.right);
} else if (cmp == 0) {
switch (range.getUpperBoundType()) {
case OPEN:
return aggr.nodeAggregate(node) + aggr.treeAggregate(node.right);
case CLOSED:
return aggr.treeAggregate(node.right);
default:
throw new AssertionError();
}
} else {
return aggr.treeAggregate(node.right) + aggr.nodeAggregate(node)
+ aggregateAboveRange(aggr, node.left);
}
}
@Override
public int size() {
return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE));
}
@Override
int distinctElements() {
return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT));
}
@Override
public int count(@Nullable Object element) {
try {
@SuppressWarnings("unchecked")
E e = (E) element;
AvlNode<E> root = rootReference.get();
if (!range.contains(e) || root == null) {
return 0;
}
return root.count(comparator(), e);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
@Override
public int add(@Nullable E element, int occurrences) {
checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences);
if (occurrences == 0) {
return count(element);
}
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
comparator().compare(element, element);
AvlNode<E> newRoot = new AvlNode<E>(element, occurrences);
successor(header, newRoot, header);
rootReference.checkAndSet(root, newRoot);
return 0;
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.add(comparator(), element, occurrences, result);
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences);
if (occurrences == 0) {
return count(element);
}
AvlNode<E> root = rootReference.get();
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot;
try {
@SuppressWarnings("unchecked")
E e = (E) element;
if (!range.contains(e) || root == null) {
return 0;
}
newRoot = root.remove(comparator(), e, occurrences, result);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public int setCount(@Nullable E element, int count) {
checkArgument(count >= 0);
if (!range.contains(element)) {
checkArgument(count == 0);
return 0;
}
AvlNode<E> root = rootReference.get();
if (root == null) {
if (count > 0) {
add(element, count);
}
return 0;
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.setCount(comparator(), element, count, result);
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public boolean setCount(@Nullable E element, int oldCount, int newCount) {
checkArgument(newCount >= 0);
checkArgument(oldCount >= 0);
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
if (oldCount == 0) {
if (newCount > 0) {
add(element, newCount);
}
return true;
} else {
return false;
}
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.setCount(comparator(), element, oldCount, newCount, result);
rootReference.checkAndSet(root, newRoot);
return result[0] == oldCount;
}
private Entry<E> wrapEntry(final AvlNode<E> baseEntry) {
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return baseEntry.getElement();
}
@Override
public int getCount() {
int result = baseEntry.getCount();
if (result == 0) {
return count(getElement());
} else {
return result;
}
}
};
}
/**
* Returns the first node in the tree that is in range.
*/
@Nullable private AvlNode<E> firstNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasLowerBound()) {
E endpoint = range.getLowerEndpoint();
node = rootReference.get().ceiling(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getLowerBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.succ;
}
} else {
node = header.succ;
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
@Nullable private AvlNode<E> lastNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasUpperBound()) {
E endpoint = range.getUpperEndpoint();
node = rootReference.get().floor(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getUpperBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.pred;
}
} else {
node = header.pred;
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
@Override
Iterator<Entry<E>> entryIterator() {
return new Iterator<Entry<E>>() {
AvlNode<E> current = firstNode();
Entry<E> prevEntry;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else if (range.tooHigh(current.getElement())) {
current = null;
return false;
} else {
return true;
}
}
@Override
public Entry<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<E> result = wrapEntry(current);
prevEntry = result;
if (current.succ == header) {
current = null;
} else {
current = current.succ;
}
return result;
}
@Override
public void remove() {
checkState(prevEntry != null);
setCount(prevEntry.getElement(), 0);
prevEntry = null;
}
};
}
@Override
Iterator<Entry<E>> descendingEntryIterator() {
return new Iterator<Entry<E>>() {
AvlNode<E> current = lastNode();
Entry<E> prevEntry = null;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else if (range.tooLow(current.getElement())) {
current = null;
return false;
} else {
return true;
}
}
@Override
public Entry<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<E> result = wrapEntry(current);
prevEntry = result;
if (current.pred == header) {
current = null;
} else {
current = current.pred;
}
return result;
}
@Override
public void remove() {
checkState(prevEntry != null);
setCount(prevEntry.getElement(), 0);
prevEntry = null;
}
};
}
@Override
public SortedMultiset<E> headMultiset(@Nullable E upperBound, BoundType boundType) {
return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.upTo(
comparator(),
upperBound,
boundType)), header);
}
@Override
public SortedMultiset<E> tailMultiset(@Nullable E lowerBound, BoundType boundType) {
return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.downTo(
comparator(),
lowerBound,
boundType)), header);
}
static int distinctElements(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.distinctElements;
}
private static final class Reference<T> {
@Nullable private T value;
@Nullable public T get() {
return value;
}
public void checkAndSet(@Nullable T expected, T newValue) {
if (value != expected) {
throw new ConcurrentModificationException();
}
value = newValue;
}
}
private static final class AvlNode<E> extends Multisets.AbstractEntry<E> {
@Nullable private final E elem;
// elemCount is 0 iff this node has been deleted.
private int elemCount;
private int distinctElements;
private long totalCount;
private int height;
private AvlNode<E> left;
private AvlNode<E> right;
private AvlNode<E> pred;
private AvlNode<E> succ;
AvlNode(@Nullable E elem, int elemCount) {
checkArgument(elemCount > 0);
this.elem = elem;
this.elemCount = elemCount;
this.totalCount = elemCount;
this.distinctElements = 1;
this.height = 1;
this.left = null;
this.right = null;
}
public int count(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
return (left == null) ? 0 : left.count(comparator, e);
} else if (cmp > 0) {
return (right == null) ? 0 : right.count(comparator, e);
} else {
return elemCount;
}
}
private AvlNode<E> addRightChild(E e, int count) {
right = new AvlNode<E>(e, count);
successor(this, right, succ);
height = Math.max(2, height);
distinctElements++;
totalCount += count;
return this;
}
private AvlNode<E> addLeftChild(E e, int count) {
left = new AvlNode<E>(e, count);
successor(pred, left, this);
height = Math.max(2, height);
distinctElements++;
totalCount += count;
return this;
}
AvlNode<E> add(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
/*
* It speeds things up considerably to unconditionally add count to totalCount here,
* but that destroys failure atomicity in the case of count overflow. =(
*/
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return addLeftChild(e, count);
}
int initHeight = initLeft.height;
left = initLeft.add(comparator, e, count, result);
if (result[0] == 0) {
distinctElements++;
}
this.totalCount += count;
return (left.height == initHeight) ? this : rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return addRightChild(e, count);
}
int initHeight = initRight.height;
right = initRight.add(comparator, e, count, result);
if (result[0] == 0) {
distinctElements++;
}
this.totalCount += count;
return (right.height == initHeight) ? this : rebalance();
}
// adding count to me! No rebalance possible.
result[0] = elemCount;
long resultCount = (long) elemCount + count;
checkArgument(resultCount <= Integer.MAX_VALUE);
this.elemCount += count;
this.totalCount += count;
return this;
}
AvlNode<E> remove(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return this;
}
left = initLeft.remove(comparator, e, count, result);
if (result[0] > 0) {
if (count >= result[0]) {
this.distinctElements--;
this.totalCount -= result[0];
} else {
this.totalCount -= count;
}
}
return (result[0] == 0) ? this : rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return this;
}
right = initRight.remove(comparator, e, count, result);
if (result[0] > 0) {
if (count >= result[0]) {
this.distinctElements--;
this.totalCount -= result[0];
} else {
this.totalCount -= count;
}
}
return rebalance();
}
// removing count from me!
result[0] = elemCount;
if (count >= elemCount) {
return deleteMe();
} else {
this.elemCount -= count;
this.totalCount -= count;
return this;
}
}
AvlNode<E> setCount(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return (count > 0) ? addLeftChild(e, count) : this;
}
left = initLeft.setCount(comparator, e, count, result);
if (count == 0 && result[0] != 0) {
this.distinctElements--;
} else if (count > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += count - result[0];
return rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return (count > 0) ? addRightChild(e, count) : this;
}
right = initRight.setCount(comparator, e, count, result);
if (count == 0 && result[0] != 0) {
this.distinctElements--;
} else if (count > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += count - result[0];
return rebalance();
}
// setting my count
result[0] = elemCount;
if (count == 0) {
return deleteMe();
}
this.totalCount += count - elemCount;
this.elemCount = count;
return this;
}
AvlNode<E> setCount(
Comparator<? super E> comparator,
@Nullable E e,
int expectedCount,
int newCount,
int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
if (expectedCount == 0 && newCount > 0) {
return addLeftChild(e, newCount);
}
return this;
}
left = initLeft.setCount(comparator, e, expectedCount, newCount, result);
if (result[0] == expectedCount) {
if (newCount == 0 && result[0] != 0) {
this.distinctElements--;
} else if (newCount > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += newCount - result[0];
}
return rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
if (expectedCount == 0 && newCount > 0) {
return addRightChild(e, newCount);
}
return this;
}
right = initRight.setCount(comparator, e, expectedCount, newCount, result);
if (result[0] == expectedCount) {
if (newCount == 0 && result[0] != 0) {
this.distinctElements--;
} else if (newCount > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += newCount - result[0];
}
return rebalance();
}
// setting my count
result[0] = elemCount;
if (expectedCount == elemCount) {
if (newCount == 0) {
return deleteMe();
}
this.totalCount += newCount - elemCount;
this.elemCount = newCount;
}
return this;
}
private AvlNode<E> deleteMe() {
int oldElemCount = this.elemCount;
this.elemCount = 0;
successor(pred, succ);
if (left == null) {
return right;
} else if (right == null) {
return left;
} else if (left.height >= right.height) {
AvlNode<E> newTop = pred;
// newTop is the maximum node in my left subtree
newTop.left = left.removeMax(newTop);
newTop.right = right;
newTop.distinctElements = distinctElements - 1;
newTop.totalCount = totalCount - oldElemCount;
return newTop.rebalance();
} else {
AvlNode<E> newTop = succ;
newTop.right = right.removeMin(newTop);
newTop.left = left;
newTop.distinctElements = distinctElements - 1;
newTop.totalCount = totalCount - oldElemCount;
return newTop.rebalance();
}
}
// Removes the minimum node from this subtree to be reused elsewhere
private AvlNode<E> removeMin(AvlNode<E> node) {
if (left == null) {
return right;
} else {
left = left.removeMin(node);
distinctElements--;
totalCount -= node.elemCount;
return rebalance();
}
}
// Removes the maximum node from this subtree to be reused elsewhere
private AvlNode<E> removeMax(AvlNode<E> node) {
if (right == null) {
return left;
} else {
right = right.removeMax(node);
distinctElements--;
totalCount -= node.elemCount;
return rebalance();
}
}
private void recomputeMultiset() {
this.distinctElements = 1 + TreeMultiset.distinctElements(left)
+ TreeMultiset.distinctElements(right);
this.totalCount = elemCount + totalCount(left) + totalCount(right);
}
private void recomputeHeight() {
this.height = 1 + Math.max(height(left), height(right));
}
private void recompute() {
recomputeMultiset();
recomputeHeight();
}
private AvlNode<E> rebalance() {
switch (balanceFactor()) {
case -2:
if (right.balanceFactor() > 0) {
right = right.rotateRight();
}
return rotateLeft();
case 2:
if (left.balanceFactor() < 0) {
left = left.rotateLeft();
}
return rotateRight();
default:
recomputeHeight();
return this;
}
}
private int balanceFactor() {
return height(left) - height(right);
}
private AvlNode<E> rotateLeft() {
checkState(right != null);
AvlNode<E> newTop = right;
this.right = newTop.left;
newTop.left = this;
newTop.totalCount = this.totalCount;
newTop.distinctElements = this.distinctElements;
this.recompute();
newTop.recomputeHeight();
return newTop;
}
private AvlNode<E> rotateRight() {
checkState(left != null);
AvlNode<E> newTop = left;
this.left = newTop.right;
newTop.right = this;
newTop.totalCount = this.totalCount;
newTop.distinctElements = this.distinctElements;
this.recompute();
newTop.recomputeHeight();
return newTop;
}
private static long totalCount(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.totalCount;
}
private static int height(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.height;
}
@Nullable private AvlNode<E> ceiling(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this);
} else if (cmp == 0) {
return this;
} else {
return (right == null) ? null : right.ceiling(comparator, e);
}
}
@Nullable private AvlNode<E> floor(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp > 0) {
return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this);
} else if (cmp == 0) {
return this;
} else {
return (left == null) ? null : left.floor(comparator, e);
}
}
@Override
public E getElement() {
return elem;
}
@Override
public int getCount() {
return elemCount;
}
@Override
public String toString() {
return Multisets.immutableEntry(getElement(), getCount()).toString();
}
}
private static <T> void successor(AvlNode<T> a, AvlNode<T> b) {
a.succ = b;
b.pred = a;
}
private static <T> void successor(AvlNode<T> a, AvlNode<T> b, AvlNode<T> c) {
successor(a, b);
successor(b, c);
}
/*
* TODO(jlevy): Decide whether entrySet() should return entries with an equals() method that
* calls the comparator to compare the two keys. If that change is made,
* AbstractMultiset.equals() can simply check whether two multisets have equal entry sets.
*/
/**
* @serialData the comparator, the number of distinct elements, the first element, its count, the
* second element, its count, and so on
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(elementSet().comparator());
Serialization.writeMultiset(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked")
// reading data stored by writeObject
Comparator<? super E> comparator = (Comparator<? super E>) stream.readObject();
Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator);
Serialization.getFieldSetter(TreeMultiset.class, "range").set(
this,
GeneralRange.all(comparator));
Serialization.getFieldSetter(TreeMultiset.class, "rootReference").set(
this,
new Reference<AvlNode<E>>());
AvlNode<E> header = new AvlNode<E>(null, 1);
Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header);
successor(header, header);
Serialization.populateMultiset(this, stream);
}
@GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 1;
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* An implementation of {@link ImmutableTable} holding an arbitrary number of
* cells.
*
* @author Gregory Kick
*/
@GwtCompatible
abstract class RegularImmutableTable<R, C, V> extends ImmutableTable<R, C, V> {
// TODO(user): split DenseImmutableTable, SparseImmutableTable into their own classes
private final ImmutableSet<Cell<R, C, V>> cellSet;
private RegularImmutableTable(ImmutableSet<Cell<R, C, V>> cellSet) {
this.cellSet = cellSet;
}
private static final Function<Cell<Object, Object, Object>, Object>
GET_VALUE_FUNCTION =
new Function<Cell<Object, Object, Object>, Object>() {
@Override public Object apply(Cell<Object, Object, Object> from) {
return from.getValue();
}
};
@SuppressWarnings("unchecked")
private Function<Cell<R, C, V>, V> getValueFunction() {
return (Function) GET_VALUE_FUNCTION;
}
@Nullable private transient volatile ImmutableList<V> valueList;
@Override public final ImmutableCollection<V> values() {
ImmutableList<V> result = valueList;
if (result == null) {
valueList = result = ImmutableList.copyOf(
Iterables.transform(cellSet(), getValueFunction()));
}
return result;
}
@Override public final int size() {
return cellSet().size();
}
@Override public final boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
@Override public final boolean isEmpty() {
return false;
}
@Override public final ImmutableSet<Cell<R, C, V>> cellSet() {
return cellSet;
}
static final <R, C, V> RegularImmutableTable<R, C, V> forCells(
List<Cell<R, C, V>> cells,
@Nullable final Comparator<? super R> rowComparator,
@Nullable final Comparator<? super C> columnComparator) {
checkNotNull(cells);
if (rowComparator != null || columnComparator != null) {
/*
* This sorting logic leads to a cellSet() ordering that may not be
* expected and that isn't documented in the Javadoc. If a row Comparator
* is provided, cellSet() iterates across the columns in the first row,
* the columns in the second row, etc. If a column Comparator is provided
* but a row Comparator isn't, cellSet() iterates across the rows in the
* first column, the rows in the second column, etc.
*/
Comparator<Cell<R, C, V>> comparator = new Comparator<Cell<R, C, V>>() {
@Override public int compare(Cell<R, C, V> cell1, Cell<R, C, V> cell2) {
int rowCompare = (rowComparator == null) ? 0
: rowComparator.compare(cell1.getRowKey(), cell2.getRowKey());
if (rowCompare != 0) {
return rowCompare;
}
return (columnComparator == null) ? 0
: columnComparator.compare(
cell1.getColumnKey(), cell2.getColumnKey());
}
};
Collections.sort(cells, comparator);
}
return forCellsInternal(cells, rowComparator, columnComparator);
}
static final <R, C, V> RegularImmutableTable<R, C, V> forCells(
Iterable<Cell<R, C, V>> cells) {
return forCellsInternal(cells, null, null);
}
/**
* A factory that chooses the most space-efficient representation of the
* table.
*/
private static final <R, C, V> RegularImmutableTable<R, C, V>
forCellsInternal(Iterable<Cell<R, C, V>> cells,
@Nullable Comparator<? super R> rowComparator,
@Nullable Comparator<? super C> columnComparator) {
ImmutableSet.Builder<Cell<R, C, V>> cellSetBuilder = ImmutableSet.builder();
ImmutableSet.Builder<R> rowSpaceBuilder = ImmutableSet.builder();
ImmutableSet.Builder<C> columnSpaceBuilder = ImmutableSet.builder();
for (Cell<R, C, V> cell : cells) {
cellSetBuilder.add(cell);
rowSpaceBuilder.add(cell.getRowKey());
columnSpaceBuilder.add(cell.getColumnKey());
}
ImmutableSet<Cell<R, C, V>> cellSet = cellSetBuilder.build();
ImmutableSet<R> rowSpace = rowSpaceBuilder.build();
if (rowComparator != null) {
List<R> rowList = Lists.newArrayList(rowSpace);
Collections.sort(rowList, rowComparator);
rowSpace = ImmutableSet.copyOf(rowList);
}
ImmutableSet<C> columnSpace = columnSpaceBuilder.build();
if (columnComparator != null) {
List<C> columnList = Lists.newArrayList(columnSpace);
Collections.sort(columnList, columnComparator);
columnSpace = ImmutableSet.copyOf(columnList);
}
// use a dense table if more than half of the cells have values
// TODO(gak): tune this condition based on empirical evidence
return (cellSet.size() > ((rowSpace.size() * columnSpace.size()) / 2 )) ?
new DenseImmutableTable<R, C, V>(cellSet, rowSpace, columnSpace) :
new SparseImmutableTable<R, C, V>(cellSet, rowSpace, columnSpace);
}
/**
* A {@code RegularImmutableTable} optimized for sparse data.
*/
@Immutable
@VisibleForTesting
static final class SparseImmutableTable<R, C, V>
extends RegularImmutableTable<R, C, V> {
private final ImmutableMap<R, Map<C, V>> rowMap;
private final ImmutableMap<C, Map<R, V>> columnMap;
/**
* Creates a {@link Map} over the key space with
* {@link ImmutableMap.Builder}s ready for values.
*/
private static final <A, B, V> Map<A, ImmutableMap.Builder<B, V>>
makeIndexBuilder(ImmutableSet<A> keySpace) {
Map<A, ImmutableMap.Builder<B, V>> indexBuilder = Maps.newLinkedHashMap();
for (A key : keySpace) {
indexBuilder.put(key, ImmutableMap.<B, V>builder());
}
return indexBuilder;
}
/**
* Builds the value maps of the index and creates an immutable copy of the
* map.
*/
private static final <A, B, V> ImmutableMap<A, Map<B, V>> buildIndex(
Map<A, ImmutableMap.Builder<B, V>> indexBuilder) {
return ImmutableMap.copyOf(Maps.transformValues(indexBuilder,
new Function<ImmutableMap.Builder<B, V>, Map<B, V>>() {
@Override public Map<B, V> apply(ImmutableMap.Builder<B, V> from) {
return from.build();
}
}));
}
SparseImmutableTable(ImmutableSet<Cell<R, C, V>> cellSet,
ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) {
super(cellSet);
Map<R, ImmutableMap.Builder<C, V>> rowIndexBuilder
= makeIndexBuilder(rowSpace);
Map<C, ImmutableMap.Builder<R, V>> columnIndexBuilder
= makeIndexBuilder(columnSpace);
for (Cell<R, C, V> cell : cellSet) {
R rowKey = cell.getRowKey();
C columnKey = cell.getColumnKey();
V value = cell.getValue();
rowIndexBuilder.get(rowKey).put(columnKey, value);
columnIndexBuilder.get(columnKey).put(rowKey, value);
}
this.rowMap = buildIndex(rowIndexBuilder);
this.columnMap = buildIndex(columnIndexBuilder);
}
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
// value maps are guaranteed to be immutable maps
return Objects.firstNonNull((ImmutableMap<R, V>) columnMap.get(columnKey),
ImmutableMap.<R, V>of());
}
@Override public ImmutableSet<C> columnKeySet() {
return columnMap.keySet();
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
return columnMap;
}
@Override public ImmutableMap<C, V> row(R rowKey) {
checkNotNull(rowKey);
// value maps are guaranteed to be immutable maps
return Objects.firstNonNull((ImmutableMap<C, V>) rowMap.get(rowKey),
ImmutableMap.<C, V>of());
}
@Override public ImmutableSet<R> rowKeySet() {
return rowMap.keySet();
}
@Override public ImmutableMap<R, Map<C, V>> rowMap() {
return rowMap;
}
@Override public boolean contains(@Nullable Object rowKey,
@Nullable Object columnKey) {
Map<C, V> row = rowMap.get(rowKey);
return (row != null) && row.containsKey(columnKey);
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return columnMap.containsKey(columnKey);
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return rowMap.containsKey(rowKey);
}
@Override public V get(@Nullable Object rowKey,
@Nullable Object columnKey) {
Map<C, V> row = rowMap.get(rowKey);
return (row == null) ? null : row.get(columnKey);
}
}
/**
* An immutable map implementation backed by an indexed nullable array, used in
* DenseImmutableTable.
*/
private abstract static class ImmutableArrayMap<K, V> extends ImmutableMap<K, V> {
private final int size;
ImmutableArrayMap(int size) {
this.size = size;
}
abstract ImmutableMap<K, Integer> keyToIndex();
// True if getValue never returns null.
private boolean isFull() {
return size == keyToIndex().size();
}
K getKey(int index) {
return keyToIndex().keySet().asList().get(index);
}
@Nullable abstract V getValue(int keyIndex);
@Override
ImmutableSet<K> createKeySet() {
return isFull() ? keyToIndex().keySet() : super.createKeySet();
}
@Override
public int size() {
return size;
}
@Override
public V get(@Nullable Object key) {
Integer keyIndex = keyToIndex().get(key);
return (keyIndex == null) ? null : getValue(keyIndex);
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
if (isFull()) {
return new ImmutableMapEntrySet<K, V>() {
@Override ImmutableMap<K, V> map() {
return ImmutableArrayMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
@Override
protected Entry<K, V> get(int index) {
return Maps.immutableEntry(getKey(index), getValue(index));
}
};
}
};
} else {
return new ImmutableMapEntrySet<K, V>() {
@Override ImmutableMap<K, V> map() {
return ImmutableArrayMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return new AbstractIterator<Entry<K, V>>() {
private int index = -1;
private final int maxIndex = keyToIndex().size();
@Override
protected Entry<K, V> computeNext() {
for (index++; index < maxIndex; index++) {
V value = getValue(index);
if (value != null) {
return Maps.immutableEntry(getKey(index), value);
}
}
return endOfData();
}
};
}
};
}
}
}
/**
* A {@code RegularImmutableTable} optimized for dense data.
*/
@Immutable @VisibleForTesting
static final class DenseImmutableTable<R, C, V>
extends RegularImmutableTable<R, C, V> {
private final ImmutableMap<R, Integer> rowKeyToIndex;
private final ImmutableMap<C, Integer> columnKeyToIndex;
private final ImmutableMap<R, Map<C, V>> rowMap;
private final ImmutableMap<C, Map<R, V>> columnMap;
private final int[] rowCounts;
private final int[] columnCounts;
private final V[][] values;
private static <E> ImmutableMap<E, Integer> makeIndex(
ImmutableSet<E> set) {
ImmutableMap.Builder<E, Integer> indexBuilder =
ImmutableMap.builder();
int i = 0;
for (E key : set) {
indexBuilder.put(key, i);
i++;
}
return indexBuilder.build();
}
DenseImmutableTable(ImmutableSet<Cell<R, C, V>> cellSet,
ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) {
super(cellSet);
@SuppressWarnings("unchecked")
V[][] array = (V[][]) new Object[rowSpace.size()][columnSpace.size()];
this.values = array;
this.rowKeyToIndex = makeIndex(rowSpace);
this.columnKeyToIndex = makeIndex(columnSpace);
rowCounts = new int[rowKeyToIndex.size()];
columnCounts = new int[columnKeyToIndex.size()];
for (Cell<R, C, V> cell : cellSet) {
R rowKey = cell.getRowKey();
C columnKey = cell.getColumnKey();
int rowIndex = rowKeyToIndex.get(rowKey);
int columnIndex = columnKeyToIndex.get(columnKey);
V existingValue = values[rowIndex][columnIndex];
checkArgument(existingValue == null, "duplicate key: (%s, %s)", rowKey,
columnKey);
values[rowIndex][columnIndex] = cell.getValue();
rowCounts[rowIndex]++;
columnCounts[columnIndex]++;
}
this.rowMap = new RowMap();
this.columnMap = new ColumnMap();
}
private final class Row extends ImmutableArrayMap<C, V> {
private final int rowIndex;
Row(int rowIndex) {
super(rowCounts[rowIndex]);
this.rowIndex = rowIndex;
}
@Override
ImmutableMap<C, Integer> keyToIndex() {
return columnKeyToIndex;
}
@Override
V getValue(int keyIndex) {
return values[rowIndex][keyIndex];
}
@Override
boolean isPartialView() {
return true;
}
}
private final class Column extends ImmutableArrayMap<R, V> {
private final int columnIndex;
Column(int columnIndex) {
super(columnCounts[columnIndex]);
this.columnIndex = columnIndex;
}
@Override
ImmutableMap<R, Integer> keyToIndex() {
return rowKeyToIndex;
}
@Override
V getValue(int keyIndex) {
return values[keyIndex][columnIndex];
}
@Override
boolean isPartialView() {
return true;
}
}
private final class RowMap extends ImmutableArrayMap<R, Map<C, V>> {
private RowMap() {
super(rowCounts.length);
}
@Override
ImmutableMap<R, Integer> keyToIndex() {
return rowKeyToIndex;
}
@Override
Map<C, V> getValue(int keyIndex) {
return new Row(keyIndex);
}
@Override
boolean isPartialView() {
return false;
}
}
private final class ColumnMap extends ImmutableArrayMap<C, Map<R, V>> {
private ColumnMap() {
super(columnCounts.length);
}
@Override
ImmutableMap<C, Integer> keyToIndex() {
return columnKeyToIndex;
}
@Override
Map<R, V> getValue(int keyIndex) {
return new Column(keyIndex);
}
@Override
boolean isPartialView() {
return false;
}
}
@Override public ImmutableMap<R, V> column(C columnKey) {
Integer columnIndex = columnKeyToIndex.get(checkNotNull(columnKey));
if (columnIndex == null) {
return ImmutableMap.of();
} else {
return new Column(columnIndex);
}
}
@Override public ImmutableSet<C> columnKeySet() {
return columnKeyToIndex.keySet();
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
return columnMap;
}
@Override public boolean contains(@Nullable Object rowKey,
@Nullable Object columnKey) {
return (get(rowKey, columnKey) != null);
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return columnKeyToIndex.containsKey(columnKey);
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return rowKeyToIndex.containsKey(rowKey);
}
@Override public V get(@Nullable Object rowKey,
@Nullable Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return ((rowIndex == null) || (columnIndex == null)) ? null
: values[rowIndex][columnIndex];
}
@Override public ImmutableMap<C, V> row(R rowKey) {
checkNotNull(rowKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
if (rowIndex == null) {
return ImmutableMap.of();
} else {
return new Row(rowIndex);
}
}
@Override public ImmutableSet<R> rowKeySet() {
return rowKeyToIndex.keySet();
}
@Override
public ImmutableMap<R, Map<C, V>> rowMap() {
return rowMap;
}
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import java.util.List;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableList} with one or more elements.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class RegularImmutableList<E> extends ImmutableList<E> {
private final transient int offset;
private final transient int size;
private final transient Object[] array;
RegularImmutableList(Object[] array, int offset, int size) {
this.offset = offset;
this.size = size;
this.array = array;
}
RegularImmutableList(Object[] array) {
this(array, 0, array.length);
}
@Override
public int size() {
return size;
}
@Override public boolean isEmpty() {
return false;
}
@Override boolean isPartialView() {
return offset != 0 || size != array.length;
}
@Override public Object[] toArray() {
Object[] newArray = new Object[size()];
System.arraycopy(array, offset, newArray, 0, size);
return newArray;
}
@Override public <T> T[] toArray(T[] other) {
if (other.length < size) {
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
System.arraycopy(array, offset, other, 0, size);
return other;
}
// The fake cast to E is safe because the creation methods only allow E's
@Override
@SuppressWarnings("unchecked")
public E get(int index) {
Preconditions.checkElementIndex(index, size);
return (E) array[index + offset];
}
@Override
ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
return new RegularImmutableList<E>(
array, offset + fromIndex, toIndex - fromIndex);
}
@SuppressWarnings("unchecked")
@Override
public UnmodifiableListIterator<E> listIterator(int index) {
// for performance
// The fake cast to E is safe because the creation methods only allow E's
return (UnmodifiableListIterator<E>)
Iterators.forArray(array, offset, size, index);
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (!(object instanceof List)) {
return false;
}
List<?> that = (List<?>) object;
if (this.size() != that.size()) {
return false;
}
int index = offset;
if (object instanceof RegularImmutableList) {
RegularImmutableList<?> other = (RegularImmutableList<?>) object;
for (int i = other.offset; i < other.offset + other.size; i++) {
if (!array[index++].equals(other.array[i])) {
return false;
}
}
} else {
for (Object element : that) {
if (!array[index++].equals(element)) {
return false;
}
}
}
return true;
}
@Override public String toString() {
StringBuilder sb = Collections2.newStringBuilderForCollection(size())
.append('[').append(array[offset]);
for (int i = offset + 1; i < offset + size; i++) {
sb.append(", ").append(array[i]);
}
return sb.append(']').toString();
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of {@code Multimap} that uses an {@code ArrayList} to store
* the values for a given key. A {@link HashMap} associates each key with an
* {@link ArrayList} of values.
*
* <p>When iterating through the collections supplied by this class, the
* ordering of values for a given key agrees with the order in which the values
* were added.
*
* <p>This multimap allows duplicate key-value pairs. After adding a new
* key-value pair equal to an existing key-value pair, the {@code
* ArrayListMultimap} will contain entries for both the new value and the old
* value.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link
* #replaceValues} all implement {@link java.util.RandomAccess}.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedListMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> {
// Default from ArrayList
private static final int DEFAULT_VALUES_PER_KEY = 3;
@VisibleForTesting transient int expectedValuesPerKey;
/**
* Creates a new, empty {@code ArrayListMultimap} with the default initial
* capacities.
*/
public static <K, V> ArrayListMultimap<K, V> create() {
return new ArrayListMultimap<K, V>();
}
/**
* Constructs an empty {@code ArrayListMultimap} with enough capacity to hold
* the specified numbers of keys and values without resizing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> ArrayListMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey);
}
/**
* Constructs an {@code ArrayListMultimap} with the same mappings as the
* specified multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> ArrayListMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new ArrayListMultimap<K, V>(multimap);
}
private ArrayListMultimap() {
super(new HashMap<K, Collection<V>>());
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
}
private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
checkArgument(expectedValuesPerKey >= 0);
this.expectedValuesPerKey = expectedValuesPerKey;
}
private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size(),
(multimap instanceof ArrayListMultimap) ?
((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey :
DEFAULT_VALUES_PER_KEY);
putAll(multimap);
}
/**
* Creates a new, empty {@code ArrayList} to hold the collection of values for
* an arbitrary key.
*/
@Override List<V> createCollection() {
return new ArrayList<V>(expectedValuesPerKey);
}
/**
* Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
*/
public void trimToSize() {
for (Collection<V> collection : backingMap().values()) {
ArrayList<V> arrayList = (ArrayList<V>) collection;
arrayList.trimToSize();
}
}
/**
* @serialData expectedValuesPerKey, number of distinct keys, and then for
* each distinct key: the key, number of values for that key, and the
* key's values
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(expectedValuesPerKey);
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible("java.io.ObjectOutputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = stream.readInt();
int distinctKeys = Serialization.readCount(stream);
Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys);
setMap(map);
Serialization.populateMultimap(this, stream, distinctKeys);
}
@GwtIncompatible("Not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
/**
* Bimap with no mappings.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class EmptyImmutableBiMap extends ImmutableBiMap<Object, Object> {
static final EmptyImmutableBiMap INSTANCE = new EmptyImmutableBiMap();
private EmptyImmutableBiMap() {}
@Override ImmutableMap<Object, Object> delegate() {
return ImmutableMap.of();
}
@Override public ImmutableBiMap<Object, Object> inverse() {
return this;
}
@Override boolean isPartialView() {
return false;
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
}
| Java |
/*
* Copyright (C) 2010 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A sorted set of contiguous values in a given {@link DiscreteDomain}.
*
* <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as
* {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomains.integers()}). Certain
* operations on such a set can be performed efficiently, but others (such as {@link Set#hashCode}
* or {@link Collections#frequency}) can cause major performance problems.
*
* @author Gregory Kick
* @since 10.0
*/
@Beta
@GwtCompatible(emulated = true)
@SuppressWarnings("rawtypes") // allow ungenerified Comparable types
public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
/**
* Returns a {@code ContiguousSet} containing the same values in the given domain
* {@linkplain Range#contains contained} by the range.
*
* @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if
* neither has an upper bound
*
* @since 13.0
*/
public static <C extends Comparable> ContiguousSet<C> create(
Range<C> range, DiscreteDomain<C> domain) {
checkNotNull(range);
checkNotNull(domain);
Range<C> effectiveRange = range;
try {
if (!range.hasLowerBound()) {
effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue()));
}
if (!range.hasUpperBound()) {
effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue()));
}
} catch (NoSuchElementException e) {
throw new IllegalArgumentException(e);
}
// Per class spec, we are allowed to throw CCE if necessary
boolean empty = effectiveRange.isEmpty()
|| Range.compareOrThrow(
range.lowerBound.leastValueAbove(domain),
range.upperBound.greatestValueBelow(domain)) > 0;
return empty
? new EmptyContiguousSet<C>(domain)
: new RegularContiguousSet<C>(effectiveRange, domain);
}
final DiscreteDomain<C> domain;
ContiguousSet(DiscreteDomain<C> domain) {
super(Ordering.natural());
this.domain = domain;
}
@Override public ContiguousSet<C> headSet(C toElement) {
return headSetImpl(checkNotNull(toElement), false);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override public ContiguousSet<C> headSet(C toElement, boolean inclusive) {
return headSetImpl(checkNotNull(toElement), inclusive);
}
@Override public ContiguousSet<C> subSet(C fromElement, C toElement) {
checkNotNull(fromElement);
checkNotNull(toElement);
checkArgument(comparator().compare(fromElement, toElement) <= 0);
return subSetImpl(fromElement, true, toElement, false);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override public ContiguousSet<C> subSet(C fromElement, boolean fromInclusive, C toElement,
boolean toInclusive) {
checkNotNull(fromElement);
checkNotNull(toElement);
checkArgument(comparator().compare(fromElement, toElement) <= 0);
return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
}
@Override public ContiguousSet<C> tailSet(C fromElement) {
return tailSetImpl(checkNotNull(fromElement), true);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) {
return tailSetImpl(checkNotNull(fromElement), inclusive);
}
/*
* These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
*/
/*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
/*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive,
C toElement, boolean toInclusive);
/*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
/**
* Returns the set of values that are contained in both this set and the other.
*
* <p>This method should always be used instead of
* {@link Sets#intersection} for {@link ContiguousSet} instances.
*/
public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
/**
* Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
* contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}.
*
* @throws NoSuchElementException if this set is empty
*/
public abstract Range<C> range();
/**
* Returns the minimal range with the given boundary types for which all values in this set are
* {@linkplain Range#contains(Comparable) contained} within the range.
*
* <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
* is requested for a domain minimum or maximum. For example, if {@code set} was created from the
* range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
* {@code [1..∞)}.
*
* @throws NoSuchElementException if this set is empty
*/
public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
/** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
@Override public String toString() {
return range().toString();
}
}
| Java |
/*
* Copyright (C) 2007 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.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Synchronized collection views. The returned synchronized collection views are
* serializable if the backing collection and the mutex are serializable.
*
* <p>If {@code null} is passed as the {@code mutex} parameter to any of this
* class's top-level methods or inner class constructors, the created object
* uses itself as the synchronization mutex.
*
* <p>This class should be used by other collection classes only.
*
* @author Mike Bostock
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
final class Synchronized {
private Synchronized() {}
static class SynchronizedObject implements Serializable {
final Object delegate;
final Object mutex;
SynchronizedObject(Object delegate, @Nullable Object mutex) {
this.delegate = checkNotNull(delegate);
this.mutex = (mutex == null) ? this : mutex;
}
Object delegate() {
return delegate;
}
// No equals and hashCode; see ForwardingObject for details.
@Override public String toString() {
synchronized (mutex) {
return delegate.toString();
}
}
// Serialization invokes writeObject only when it's private.
// The SynchronizedObject subclasses don't need a writeObject method since
// they don't contain any non-transient member variables, while the
// following writeObject() handles the SynchronizedObject members.
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
synchronized (mutex) {
stream.defaultWriteObject();
}
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
private static <E> Collection<E> collection(
Collection<E> collection, @Nullable Object mutex) {
return new SynchronizedCollection<E>(collection, mutex);
}
@VisibleForTesting static class SynchronizedCollection<E>
extends SynchronizedObject implements Collection<E> {
private SynchronizedCollection(
Collection<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked")
@Override Collection<E> delegate() {
return (Collection<E>) super.delegate();
}
@Override
public boolean add(E e) {
synchronized (mutex) {
return delegate().add(e);
}
}
@Override
public boolean addAll(Collection<? extends E> c) {
synchronized (mutex) {
return delegate().addAll(c);
}
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public boolean contains(Object o) {
synchronized (mutex) {
return delegate().contains(o);
}
}
@Override
public boolean containsAll(Collection<?> c) {
synchronized (mutex) {
return delegate().containsAll(c);
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public Iterator<E> iterator() {
return delegate().iterator(); // manually synchronized
}
@Override
public boolean remove(Object o) {
synchronized (mutex) {
return delegate().remove(o);
}
}
@Override
public boolean removeAll(Collection<?> c) {
synchronized (mutex) {
return delegate().removeAll(c);
}
}
@Override
public boolean retainAll(Collection<?> c) {
synchronized (mutex) {
return delegate().retainAll(c);
}
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public Object[] toArray() {
synchronized (mutex) {
return delegate().toArray();
}
}
@Override
public <T> T[] toArray(T[] a) {
synchronized (mutex) {
return delegate().toArray(a);
}
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) {
return new SynchronizedSet<E>(set, mutex);
}
static class SynchronizedSet<E>
extends SynchronizedCollection<E> implements Set<E> {
SynchronizedSet(Set<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Set<E> delegate() {
return (Set<E>) super.delegate();
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
private static <E> SortedSet<E> sortedSet(
SortedSet<E> set, @Nullable Object mutex) {
return new SynchronizedSortedSet<E>(set, mutex);
}
static class SynchronizedSortedSet<E> extends SynchronizedSet<E>
implements SortedSet<E> {
SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedSet<E> delegate() {
return (SortedSet<E>) super.delegate();
}
@Override
public Comparator<? super E> comparator() {
synchronized (mutex) {
return delegate().comparator();
}
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
synchronized (mutex) {
return sortedSet(delegate().subSet(fromElement, toElement), mutex);
}
}
@Override
public SortedSet<E> headSet(E toElement) {
synchronized (mutex) {
return sortedSet(delegate().headSet(toElement), mutex);
}
}
@Override
public SortedSet<E> tailSet(E fromElement) {
synchronized (mutex) {
return sortedSet(delegate().tailSet(fromElement), mutex);
}
}
@Override
public E first() {
synchronized (mutex) {
return delegate().first();
}
}
@Override
public E last() {
synchronized (mutex) {
return delegate().last();
}
}
private static final long serialVersionUID = 0;
}
private static <E> List<E> list(List<E> list, @Nullable Object mutex) {
return (list instanceof RandomAccess)
? new SynchronizedRandomAccessList<E>(list, mutex)
: new SynchronizedList<E>(list, mutex);
}
private static class SynchronizedList<E> extends SynchronizedCollection<E>
implements List<E> {
SynchronizedList(List<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override List<E> delegate() {
return (List<E>) super.delegate();
}
@Override
public void add(int index, E element) {
synchronized (mutex) {
delegate().add(index, element);
}
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
synchronized (mutex) {
return delegate().addAll(index, c);
}
}
@Override
public E get(int index) {
synchronized (mutex) {
return delegate().get(index);
}
}
@Override
public int indexOf(Object o) {
synchronized (mutex) {
return delegate().indexOf(o);
}
}
@Override
public int lastIndexOf(Object o) {
synchronized (mutex) {
return delegate().lastIndexOf(o);
}
}
@Override
public ListIterator<E> listIterator() {
return delegate().listIterator(); // manually synchronized
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate().listIterator(index); // manually synchronized
}
@Override
public E remove(int index) {
synchronized (mutex) {
return delegate().remove(index);
}
}
@Override
public E set(int index, E element) {
synchronized (mutex) {
return delegate().set(index, element);
}
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) {
return list(delegate().subList(fromIndex, toIndex), mutex);
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedRandomAccessList<E>
extends SynchronizedList<E> implements RandomAccess {
SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) {
super(list, mutex);
}
private static final long serialVersionUID = 0;
}
static <E> Multiset<E> multiset(
Multiset<E> multiset, @Nullable Object mutex) {
if (multiset instanceof SynchronizedMultiset ||
multiset instanceof ImmutableMultiset) {
return multiset;
}
return new SynchronizedMultiset<E>(multiset, mutex);
}
private static class SynchronizedMultiset<E> extends SynchronizedCollection<E>
implements Multiset<E> {
transient Set<E> elementSet;
transient Set<Entry<E>> entrySet;
SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Multiset<E> delegate() {
return (Multiset<E>) super.delegate();
}
@Override
public int count(Object o) {
synchronized (mutex) {
return delegate().count(o);
}
}
@Override
public int add(E e, int n) {
synchronized (mutex) {
return delegate().add(e, n);
}
}
@Override
public int remove(Object o, int n) {
synchronized (mutex) {
return delegate().remove(o, n);
}
}
@Override
public int setCount(E element, int count) {
synchronized (mutex) {
return delegate().setCount(element, count);
}
}
@Override
public boolean setCount(E element, int oldCount, int newCount) {
synchronized (mutex) {
return delegate().setCount(element, oldCount, newCount);
}
}
@Override
public Set<E> elementSet() {
synchronized (mutex) {
if (elementSet == null) {
elementSet = typePreservingSet(delegate().elementSet(), mutex);
}
return elementSet;
}
}
@Override
public Set<Entry<E>> entrySet() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = typePreservingSet(delegate().entrySet(), mutex);
}
return entrySet;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> Multimap<K, V> multimap(
Multimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedMultimap ||
multimap instanceof ImmutableMultimap) {
return multimap;
}
return new SynchronizedMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedMultimap<K, V> extends SynchronizedObject
implements Multimap<K, V> {
transient Set<K> keySet;
transient Collection<V> valuesCollection;
transient Collection<Map.Entry<K, V>> entries;
transient Map<K, Collection<V>> asMap;
transient Multiset<K> keys;
@SuppressWarnings("unchecked")
@Override Multimap<K, V> delegate() {
return (Multimap<K, V>) super.delegate();
}
SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public boolean containsKey(Object key) {
synchronized (mutex) {
return delegate().containsKey(key);
}
}
@Override
public boolean containsValue(Object value) {
synchronized (mutex) {
return delegate().containsValue(value);
}
}
@Override
public boolean containsEntry(Object key, Object value) {
synchronized (mutex) {
return delegate().containsEntry(key, value);
}
}
@Override
public Collection<V> get(K key) {
synchronized (mutex) {
return typePreservingCollection(delegate().get(key), mutex);
}
}
@Override
public boolean put(K key, V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().putAll(key, values);
}
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
synchronized (mutex) {
return delegate().putAll(multimap);
}
}
@Override
public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override
public boolean remove(Object key, Object value) {
synchronized (mutex) {
return delegate().remove(key, value);
}
}
@Override
public Collection<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public Set<K> keySet() {
synchronized (mutex) {
if (keySet == null) {
keySet = typePreservingSet(delegate().keySet(), mutex);
}
return keySet;
}
}
@Override
public Collection<V> values() {
synchronized (mutex) {
if (valuesCollection == null) {
valuesCollection = collection(delegate().values(), mutex);
}
return valuesCollection;
}
}
@Override
public Collection<Map.Entry<K, V>> entries() {
synchronized (mutex) {
if (entries == null) {
entries = typePreservingCollection(delegate().entries(), mutex);
}
return entries;
}
}
@Override
public Map<K, Collection<V>> asMap() {
synchronized (mutex) {
if (asMap == null) {
asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex);
}
return asMap;
}
}
@Override
public Multiset<K> keys() {
synchronized (mutex) {
if (keys == null) {
keys = multiset(delegate().keys(), mutex);
}
return keys;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> ListMultimap<K, V> listMultimap(
ListMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedListMultimap ||
multimap instanceof ImmutableListMultimap) {
return multimap;
}
return new SynchronizedListMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedListMultimap<K, V>
extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> {
SynchronizedListMultimap(
ListMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
synchronized (mutex) {
return list(delegate().get(key), mutex);
}
}
@Override public List<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SetMultimap<K, V> setMultimap(
SetMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedSetMultimap ||
multimap instanceof ImmutableSetMultimap) {
return multimap;
}
return new SynchronizedSetMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedSetMultimap<K, V>
extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> {
transient Set<Map.Entry<K, V>> entrySet;
SynchronizedSetMultimap(
SetMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
synchronized (mutex) {
return set(delegate().get(key), mutex);
}
}
@Override public Set<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override public Set<Map.Entry<K, V>> entries() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = set(delegate().entries(), mutex);
}
return entrySet;
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SortedSetMultimap<K, V> sortedSetMultimap(
SortedSetMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedSortedSetMultimap) {
return multimap;
}
return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedSortedSetMultimap<K, V>
extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> {
SynchronizedSortedSetMultimap(
SortedSetMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
synchronized (mutex) {
return sortedSet(delegate().get(key), mutex);
}
}
@Override public SortedSet<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override
public Comparator<? super V> valueComparator() {
synchronized (mutex) {
return delegate().valueComparator();
}
}
private static final long serialVersionUID = 0;
}
private static <E> Collection<E> typePreservingCollection(
Collection<E> collection, @Nullable Object mutex) {
if (collection instanceof SortedSet) {
return sortedSet((SortedSet<E>) collection, mutex);
}
if (collection instanceof Set) {
return set((Set<E>) collection, mutex);
}
if (collection instanceof List) {
return list((List<E>) collection, mutex);
}
return collection(collection, mutex);
}
private static <E> Set<E> typePreservingSet(
Set<E> set, @Nullable Object mutex) {
if (set instanceof SortedSet) {
return sortedSet((SortedSet<E>) set, mutex);
} else {
return set(set, mutex);
}
}
private static class SynchronizedAsMapEntries<K, V>
extends SynchronizedSet<Map.Entry<K, Collection<V>>> {
SynchronizedAsMapEntries(
Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
// Must be manually synchronized.
final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator();
return new ForwardingIterator<Map.Entry<K, Collection<V>>>() {
@Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() {
return iterator;
}
@Override public Map.Entry<K, Collection<V>> next() {
final Map.Entry<K, Collection<V>> entry = super.next();
return new ForwardingMapEntry<K, Collection<V>>() {
@Override protected Map.Entry<K, Collection<V>> delegate() {
return entry;
}
@Override public Collection<V> getValue() {
return typePreservingCollection(entry.getValue(), mutex);
}
};
}
};
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
synchronized (mutex) {
return ObjectArrays.toArrayImpl(delegate());
}
}
@Override public <T> T[] toArray(T[] array) {
synchronized (mutex) {
return ObjectArrays.toArrayImpl(delegate(), array);
}
}
@Override public boolean contains(Object o) {
synchronized (mutex) {
return Maps.containsEntryImpl(delegate(), o);
}
}
@Override public boolean containsAll(Collection<?> c) {
synchronized (mutex) {
return Collections2.containsAllImpl(delegate(), c);
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return Sets.equalsImpl(delegate(), o);
}
}
@Override public boolean remove(Object o) {
synchronized (mutex) {
return Maps.removeEntryImpl(delegate(), o);
}
}
@Override public boolean removeAll(Collection<?> c) {
synchronized (mutex) {
return Iterators.removeAll(delegate().iterator(), c);
}
}
@Override public boolean retainAll(Collection<?> c) {
synchronized (mutex) {
return Iterators.retainAll(delegate().iterator(), c);
}
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting
static <K, V> Map<K, V> map(Map<K, V> map, @Nullable Object mutex) {
return new SynchronizedMap<K, V>(map, mutex);
}
private static class SynchronizedMap<K, V> extends SynchronizedObject
implements Map<K, V> {
transient Set<K> keySet;
transient Collection<V> values;
transient Set<Map.Entry<K, V>> entrySet;
SynchronizedMap(Map<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked")
@Override Map<K, V> delegate() {
return (Map<K, V>) super.delegate();
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public boolean containsKey(Object key) {
synchronized (mutex) {
return delegate().containsKey(key);
}
}
@Override
public boolean containsValue(Object value) {
synchronized (mutex) {
return delegate().containsValue(value);
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = set(delegate().entrySet(), mutex);
}
return entrySet;
}
}
@Override
public V get(Object key) {
synchronized (mutex) {
return delegate().get(key);
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public Set<K> keySet() {
synchronized (mutex) {
if (keySet == null) {
keySet = set(delegate().keySet(), mutex);
}
return keySet;
}
}
@Override
public V put(K key, V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
synchronized (mutex) {
delegate().putAll(map);
}
}
@Override
public V remove(Object key) {
synchronized (mutex) {
return delegate().remove(key);
}
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public Collection<V> values() {
synchronized (mutex) {
if (values == null) {
values = collection(delegate().values(), mutex);
}
return values;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SortedMap<K, V> sortedMap(
SortedMap<K, V> sortedMap, @Nullable Object mutex) {
return new SynchronizedSortedMap<K, V>(sortedMap, mutex);
}
static class SynchronizedSortedMap<K, V> extends SynchronizedMap<K, V>
implements SortedMap<K, V> {
SynchronizedSortedMap(SortedMap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedMap<K, V> delegate() {
return (SortedMap<K, V>) super.delegate();
}
@Override public Comparator<? super K> comparator() {
synchronized (mutex) {
return delegate().comparator();
}
}
@Override public K firstKey() {
synchronized (mutex) {
return delegate().firstKey();
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
synchronized (mutex) {
return sortedMap(delegate().headMap(toKey), mutex);
}
}
@Override public K lastKey() {
synchronized (mutex) {
return delegate().lastKey();
}
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
synchronized (mutex) {
return sortedMap(delegate().subMap(fromKey, toKey), mutex);
}
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
synchronized (mutex) {
return sortedMap(delegate().tailMap(fromKey), mutex);
}
}
private static final long serialVersionUID = 0;
}
static <K, V> BiMap<K, V> biMap(BiMap<K, V> bimap, @Nullable Object mutex) {
if (bimap instanceof SynchronizedBiMap ||
bimap instanceof ImmutableBiMap) {
return bimap;
}
return new SynchronizedBiMap<K, V>(bimap, mutex, null);
}
@VisibleForTesting static class SynchronizedBiMap<K, V>
extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable {
private transient Set<V> valueSet;
private transient BiMap<V, K> inverse;
private SynchronizedBiMap(BiMap<K, V> delegate, @Nullable Object mutex,
@Nullable BiMap<V, K> inverse) {
super(delegate, mutex);
this.inverse = inverse;
}
@Override BiMap<K, V> delegate() {
return (BiMap<K, V>) super.delegate();
}
@Override public Set<V> values() {
synchronized (mutex) {
if (valueSet == null) {
valueSet = set(delegate().values(), mutex);
}
return valueSet;
}
}
@Override
public V forcePut(K key, V value) {
synchronized (mutex) {
return delegate().forcePut(key, value);
}
}
@Override
public BiMap<V, K> inverse() {
synchronized (mutex) {
if (inverse == null) {
inverse
= new SynchronizedBiMap<V, K>(delegate().inverse(), mutex, this);
}
return inverse;
}
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedAsMap<K, V>
extends SynchronizedMap<K, Collection<V>> {
transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet;
transient Collection<Collection<V>> asMapValues;
SynchronizedAsMap(Map<K, Collection<V>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Collection<V> get(Object key) {
synchronized (mutex) {
Collection<V> collection = super.get(key);
return (collection == null) ? null
: typePreservingCollection(collection, mutex);
}
}
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
synchronized (mutex) {
if (asMapEntrySet == null) {
asMapEntrySet = new SynchronizedAsMapEntries<K, V>(
delegate().entrySet(), mutex);
}
return asMapEntrySet;
}
}
@Override public Collection<Collection<V>> values() {
synchronized (mutex) {
if (asMapValues == null) {
asMapValues
= new SynchronizedAsMapValues<V>(delegate().values(), mutex);
}
return asMapValues;
}
}
@Override public boolean containsValue(Object o) {
// values() and its contains() method are both synchronized.
return values().contains(o);
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedAsMapValues<V>
extends SynchronizedCollection<Collection<V>> {
SynchronizedAsMapValues(
Collection<Collection<V>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Iterator<Collection<V>> iterator() {
// Must be manually synchronized.
final Iterator<Collection<V>> iterator = super.iterator();
return new ForwardingIterator<Collection<V>>() {
@Override protected Iterator<Collection<V>> delegate() {
return iterator;
}
@Override public Collection<V> next() {
return typePreservingCollection(super.next(), mutex);
}
};
}
private static final long serialVersionUID = 0;
}
@GwtIncompatible("NavigableSet")
@VisibleForTesting
static class SynchronizedNavigableSet<E> extends SynchronizedSortedSet<E>
implements NavigableSet<E> {
SynchronizedNavigableSet(NavigableSet<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override NavigableSet<E> delegate() {
return (NavigableSet<E>) super.delegate();
}
@Override public E ceiling(E e) {
synchronized (mutex) {
return delegate().ceiling(e);
}
}
@Override public Iterator<E> descendingIterator() {
return delegate().descendingIterator(); // manually synchronized
}
transient NavigableSet<E> descendingSet;
@Override public NavigableSet<E> descendingSet() {
synchronized (mutex) {
if (descendingSet == null) {
NavigableSet<E> dS =
Synchronized.navigableSet(delegate().descendingSet(), mutex);
descendingSet = dS;
return dS;
}
return descendingSet;
}
}
@Override public E floor(E e) {
synchronized (mutex) {
return delegate().floor(e);
}
}
@Override public NavigableSet<E> headSet(E toElement, boolean inclusive) {
synchronized (mutex) {
return Synchronized.navigableSet(
delegate().headSet(toElement, inclusive), mutex);
}
}
@Override public E higher(E e) {
synchronized (mutex) {
return delegate().higher(e);
}
}
@Override public E lower(E e) {
synchronized (mutex) {
return delegate().lower(e);
}
}
@Override public E pollFirst() {
synchronized (mutex) {
return delegate().pollFirst();
}
}
@Override public E pollLast() {
synchronized (mutex) {
return delegate().pollLast();
}
}
@Override public NavigableSet<E> subSet(E fromElement,
boolean fromInclusive, E toElement, boolean toInclusive) {
synchronized (mutex) {
return Synchronized.navigableSet(delegate().subSet(
fromElement, fromInclusive, toElement, toInclusive), mutex);
}
}
@Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
synchronized (mutex) {
return Synchronized.navigableSet(
delegate().tailSet(fromElement, inclusive), mutex);
}
}
@Override public SortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override public SortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
private static final long serialVersionUID = 0;
}
@GwtIncompatible("NavigableSet")
static <E> NavigableSet<E> navigableSet(
NavigableSet<E> navigableSet, @Nullable Object mutex) {
return new SynchronizedNavigableSet<E>(navigableSet, mutex);
}
@GwtIncompatible("NavigableSet")
static <E> NavigableSet<E> navigableSet(NavigableSet<E> navigableSet) {
return navigableSet(navigableSet, null);
}
@GwtIncompatible("NavigableMap")
static <K, V> NavigableMap<K, V> navigableMap(
NavigableMap<K, V> navigableMap) {
return navigableMap(navigableMap, null);
}
@GwtIncompatible("NavigableMap")
static <K, V> NavigableMap<K, V> navigableMap(
NavigableMap<K, V> navigableMap, @Nullable Object mutex) {
return new SynchronizedNavigableMap<K, V>(navigableMap, mutex);
}
@GwtIncompatible("NavigableMap")
@VisibleForTesting static class SynchronizedNavigableMap<K, V>
extends SynchronizedSortedMap<K, V> implements NavigableMap<K, V> {
SynchronizedNavigableMap(
NavigableMap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override NavigableMap<K, V> delegate() {
return (NavigableMap<K, V>) super.delegate();
}
@Override public Entry<K, V> ceilingEntry(K key) {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex);
}
}
@Override public K ceilingKey(K key) {
synchronized (mutex) {
return delegate().ceilingKey(key);
}
}
transient NavigableSet<K> descendingKeySet;
@Override public NavigableSet<K> descendingKeySet() {
synchronized (mutex) {
if (descendingKeySet == null) {
return descendingKeySet =
Synchronized.navigableSet(delegate().descendingKeySet(), mutex);
}
return descendingKeySet;
}
}
transient NavigableMap<K, V> descendingMap;
@Override public NavigableMap<K, V> descendingMap() {
synchronized (mutex) {
if (descendingMap == null) {
return descendingMap =
navigableMap(delegate().descendingMap(), mutex);
}
return descendingMap;
}
}
@Override public Entry<K, V> firstEntry() {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().firstEntry(), mutex);
}
}
@Override public Entry<K, V> floorEntry(K key) {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().floorEntry(key), mutex);
}
}
@Override public K floorKey(K key) {
synchronized (mutex) {
return delegate().floorKey(key);
}
}
@Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
synchronized (mutex) {
return navigableMap(
delegate().headMap(toKey, inclusive), mutex);
}
}
@Override public Entry<K, V> higherEntry(K key) {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().higherEntry(key), mutex);
}
}
@Override public K higherKey(K key) {
synchronized (mutex) {
return delegate().higherKey(key);
}
}
@Override public Entry<K, V> lastEntry() {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().lastEntry(), mutex);
}
}
@Override public Entry<K, V> lowerEntry(K key) {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex);
}
}
@Override public K lowerKey(K key) {
synchronized (mutex) {
return delegate().lowerKey(key);
}
}
@Override public Set<K> keySet() {
return navigableKeySet();
}
transient NavigableSet<K> navigableKeySet;
@Override public NavigableSet<K> navigableKeySet() {
synchronized (mutex) {
if (navigableKeySet == null) {
return navigableKeySet =
Synchronized.navigableSet(delegate().navigableKeySet(), mutex);
}
return navigableKeySet;
}
}
@Override public Entry<K, V> pollFirstEntry() {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex);
}
}
@Override public Entry<K, V> pollLastEntry() {
synchronized (mutex) {
return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex);
}
}
@Override public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
synchronized (mutex) {
return navigableMap(
delegate().subMap(fromKey, fromInclusive, toKey, toInclusive),
mutex);
}
}
@Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
synchronized (mutex) {
return navigableMap(
delegate().tailMap(fromKey, inclusive), mutex);
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
private static final long serialVersionUID = 0;
}
@GwtIncompatible("works but is needed only for NavigableMap")
private static <K, V> Entry<K, V> nullableSynchronizedEntry(
@Nullable Entry<K, V> entry, @Nullable Object mutex) {
if (entry == null) {
return null;
}
return new SynchronizedEntry<K, V>(entry, mutex);
}
@GwtIncompatible("works but is needed only for NavigableMap")
private static class SynchronizedEntry<K, V> extends SynchronizedObject
implements Entry<K, V> {
SynchronizedEntry(Entry<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked") // guaranteed by the constructor
@Override Entry<K, V> delegate() {
return (Entry<K, V>) super.delegate();
}
@Override public boolean equals(Object obj) {
synchronized (mutex) {
return delegate().equals(obj);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
@Override public K getKey() {
synchronized (mutex) {
return delegate().getKey();
}
}
@Override public V getValue() {
synchronized (mutex) {
return delegate().getValue();
}
}
@Override public V setValue(V value) {
synchronized (mutex) {
return delegate().setValue(value);
}
}
private static final long serialVersionUID = 0;
}
static <E> Queue<E> queue(Queue<E> queue, @Nullable Object mutex) {
return (queue instanceof SynchronizedQueue)
? queue
: new SynchronizedQueue<E>(queue, mutex);
}
private static class SynchronizedQueue<E> extends SynchronizedCollection<E>
implements Queue<E> {
SynchronizedQueue(Queue<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Queue<E> delegate() {
return (Queue<E>) super.delegate();
}
@Override
public E element() {
synchronized (mutex) {
return delegate().element();
}
}
@Override
public boolean offer(E e) {
synchronized (mutex) {
return delegate().offer(e);
}
}
@Override
public E peek() {
synchronized (mutex) {
return delegate().peek();
}
}
@Override
public E poll() {
synchronized (mutex) {
return delegate().poll();
}
}
@Override
public E remove() {
synchronized (mutex) {
return delegate().remove();
}
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A {@code SetMultimap} whose set of values for a given key are kept sorted;
* that is, they comprise a {@link SortedSet}. It cannot hold duplicate
* key-value pairs; adding a key-value pair that's already in the multimap has
* no effect. This interface does not specify the ordering of the multimap's
* keys. See the {@link Multimap} documentation for information common to all
* multimaps.
*
* <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods
* each return a {@link SortedSet} of values, while {@link Multimap#entries()}
* returns a {@link Set} of map entries. Though the method signature doesn't say
* so explicitly, the map returned by {@link #asMap} has {@code SortedSet}
* values.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface SortedSetMultimap<K, V> extends SetMultimap<K, V> {
// Following Javadoc copied from Multimap.
/**
* Returns a collection view of all values associated with a key. If no
* mappings in the multimap have the provided key, an empty collection is
* returned.
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
SortedSet<V> get(@Nullable K key);
/**
* Removes all values associated with a given key.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
SortedSet<V> removeAll(@Nullable Object key);
/**
* Stores a collection of values with the same key, replacing any existing
* values for that key.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override
SortedSet<V> replaceValues(K key, Iterable<? extends V> values);
/**
* Returns a map view that associates each key with the corresponding values
* in the multimap. Changes to the returned map, such as element removal, will
* update the underlying multimap. The map does not support {@code setValue()}
* on its entries, {@code put}, or {@code putAll}.
*
* <p>When passed a key that is present in the map, {@code
* asMap().get(Object)} has the same behavior as {@link #get}, returning a
* live collection. When passed a key that is not present, however, {@code
* asMap().get(Object)} returns {@code null} instead of an empty collection.
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link SortedSet} values.
*/
@Override
Map<K, Collection<V>> asMap();
/**
* Returns the comparator that orders the multimap values, with {@code null}
* indicating that natural ordering is used.
*/
Comparator<? super V> valueComparator();
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link Multimap} interface. This class represents
* a multimap as a map that associates each key with a collection of values. All
* methods of {@link Multimap} are supported, including those specified as
* optional in the interface.
*
* <p>To implement a multimap, a subclass must define the method {@link
* #createCollection()}, which creates an empty collection of values for a key.
*
* <p>The multimap constructor takes a map that has a single entry for each
* distinct key. When you insert a key-value pair with a key that isn't already
* in the multimap, {@code AbstractMultimap} calls {@link #createCollection()}
* to create the collection of values for that key. The subclass should not call
* {@link #createCollection()} directly, and a new instance should be created
* every time the method is called.
*
* <p>For example, the subclass could pass a {@link java.util.TreeMap} during
* construction, and {@link #createCollection()} could return a {@link
* java.util.TreeSet}, in which case the multimap's iterators would propagate
* through the keys and values in sorted order.
*
* <p>Keys and values may be null, as long as the underlying collection classes
* support null elements.
*
* <p>The collections created by {@link #createCollection()} may or may not
* allow duplicates. If the collection, such as a {@link Set}, does not support
* duplicates, an added key-value pair will replace an existing pair with the
* same key and value, if such a pair is present. With collections like {@link
* List} that allow duplicates, the collection will keep the existing key-value
* pairs while adding a new pair.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap, even if the underlying map and {@link #createCollection()} method
* return threadsafe classes. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedMultimap}.
*
* <p>For serialization to work, the subclass must specify explicit
* {@code readObject} and {@code writeObject} methods.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible
abstract class AbstractMultimap<K, V> implements Multimap<K, V>, Serializable {
/*
* Here's an outline of the overall design.
*
* The map variable contains the collection of values associated with each
* key. When a key-value pair is added to a multimap that didn't previously
* contain any values for that key, a new collection generated by
* createCollection is added to the map. That same collection instance
* remains in the map as long as the multimap has any values for the key. If
* all values for the key are removed, the key and collection are removed
* from the map.
*
* The get method returns a WrappedCollection, which decorates the collection
* in the map (if the key is present) or an empty collection (if the key is
* not present). When the collection delegate in the WrappedCollection is
* empty, the multimap may contain subsequently added values for that key. To
* handle that situation, the WrappedCollection checks whether map contains
* an entry for the provided key, and if so replaces the delegate.
*/
private transient Map<K, Collection<V>> map;
private transient int totalSize;
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @throws IllegalArgumentException if {@code map} is not empty
*/
protected AbstractMultimap(Map<K, Collection<V>> map) {
checkArgument(map.isEmpty());
this.map = map;
}
/** Used during deserialization only. */
final void setMap(Map<K, Collection<V>> map) {
this.map = map;
totalSize = 0;
for (Collection<V> values : map.values()) {
checkArgument(!values.isEmpty());
totalSize += values.size();
}
}
/**
* Creates the collection of values for a single key.
*
* <p>Collections with weak, soft, or phantom references are not supported.
* Each call to {@code createCollection} should create a new instance.
*
* <p>The returned collection class determines whether duplicate key-value
* pairs are allowed.
*
* @return an empty collection of values
*/
abstract Collection<V> createCollection();
/**
* Creates the collection of values for an explicitly provided key. By
* default, it simply calls {@link #createCollection()}, which is the correct
* behavior for most implementations. The {@link LinkedHashMultimap} class
* overrides it.
*
* @param key key to associate with values in the collection
* @return an empty collection of values
*/
Collection<V> createCollection(@Nullable K key) {
return createCollection();
}
Map<K, Collection<V>> backingMap() {
return map;
}
// Query Operations
@Override
public int size() {
return totalSize;
}
@Override
public boolean isEmpty() {
return totalSize == 0;
}
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Collection<V> collection : map.values()) {
if (collection.contains(value)) {
return true;
}
}
return false;
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
Collection<V> collection = map.get(key);
return collection != null && collection.contains(value);
}
// Modification Operations
@Override
public boolean put(@Nullable K key, @Nullable V value) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
if (collection.add(value)) {
totalSize++;
map.put(key, collection);
return true;
} else {
throw new AssertionError("New Collection violated the Collection spec");
}
} else if (collection.add(value)) {
totalSize++;
return true;
} else {
return false;
}
}
private Collection<V> getOrCreateCollection(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
map.put(key, collection);
}
return collection;
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
Collection<V> collection = map.get(key);
if (collection == null) {
return false;
}
boolean changed = collection.remove(value);
if (changed) {
totalSize--;
if (collection.isEmpty()) {
map.remove(key);
}
}
return changed;
}
// Bulk Operations
@Override
public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
if (!values.iterator().hasNext()) {
return false;
}
// TODO(user): investigate atomic failure?
Collection<V> collection = getOrCreateCollection(key);
int oldSize = collection.size();
boolean changed = false;
if (values instanceof Collection) {
Collection<? extends V> c = Collections2.cast(values);
changed = collection.addAll(c);
} else {
for (V value : values) {
changed |= collection.add(value);
}
}
totalSize += (collection.size() - oldSize);
return changed;
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
boolean changed = false;
for (Map.Entry<? extends K, ? extends V> entry : multimap.entries()) {
changed |= put(entry.getKey(), entry.getValue());
}
return changed;
}
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> replaceValues(
@Nullable K key, Iterable<? extends V> values) {
Iterator<? extends V> iterator = values.iterator();
if (!iterator.hasNext()) {
return removeAll(key);
}
// TODO(user): investigate atomic failure?
Collection<V> collection = getOrCreateCollection(key);
Collection<V> oldValues = createCollection();
oldValues.addAll(collection);
totalSize -= collection.size();
collection.clear();
while (iterator.hasNext()) {
if (collection.add(iterator.next())) {
totalSize++;
}
}
return unmodifiableCollectionSubclass(oldValues);
}
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> removeAll(@Nullable Object key) {
Collection<V> collection = map.remove(key);
Collection<V> output = createCollection();
if (collection != null) {
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
}
return unmodifiableCollectionSubclass(output);
}
private Collection<V> unmodifiableCollectionSubclass(
Collection<V> collection) {
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
} else {
return Collections.unmodifiableCollection(collection);
}
}
@Override
public void clear() {
// Clear each collection, to make previously returned collections empty.
for (Collection<V> collection : map.values()) {
collection.clear();
}
map.clear();
totalSize = 0;
}
// Views
/**
* {@inheritDoc}
*
* <p>The returned collection is not serializable.
*/
@Override
public Collection<V> get(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key, collection);
}
/**
* Generates a decorated collection that remains consistent with the values in
* the multimap for the provided key. Changes to the multimap may alter the
* returned collection, and vice versa.
*/
private Collection<V> wrapCollection(
@Nullable K key, Collection<V> collection) {
if (collection instanceof SortedSet) {
return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
} else if (collection instanceof Set) {
return new WrappedSet(key, (Set<V>) collection);
} else if (collection instanceof List) {
return wrapList(key, (List<V>) collection, null);
} else {
return new WrappedCollection(key, collection, null);
}
}
private List<V> wrapList(
@Nullable K key, List<V> list, @Nullable WrappedCollection ancestor) {
return (list instanceof RandomAccess)
? new RandomAccessWrappedList(key, list, ancestor)
: new WrappedList(key, list, ancestor);
}
/**
* Collection decorator that stays in sync with the multimap values for a key.
* There are two kinds of wrapped collections: full and subcollections. Both
* have a delegate pointing to the underlying collection class.
*
* <p>Full collections, identified by a null ancestor field, contain all
* multimap values for a given key. Its delegate is a value in {@link
* AbstractMultimap#map} whenever the delegate is non-empty. The {@code
* refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure
* that the {@code WrappedCollection} and map remain consistent.
*
* <p>A subcollection, such as a sublist, contains some of the values for a
* given key. Its ancestor field points to the full wrapped collection with
* all values for the key. The subcollection {@code refreshIfEmpty}, {@code
* removeIfEmpty}, and {@code addToMap} methods call the corresponding methods
* of the full wrapped collection.
*/
private class WrappedCollection extends AbstractCollection<V> {
final K key;
Collection<V> delegate;
final WrappedCollection ancestor;
final Collection<V> ancestorDelegate;
WrappedCollection(@Nullable K key, Collection<V> delegate,
@Nullable WrappedCollection ancestor) {
this.key = key;
this.delegate = delegate;
this.ancestor = ancestor;
this.ancestorDelegate
= (ancestor == null) ? null : ancestor.getDelegate();
}
/**
* If the delegate collection is empty, but the multimap has values for the
* key, replace the delegate with the new collection for the key.
*
* <p>For a subcollection, refresh its ancestor and validate that the
* ancestor delegate hasn't changed.
*/
void refreshIfEmpty() {
if (ancestor != null) {
ancestor.refreshIfEmpty();
if (ancestor.getDelegate() != ancestorDelegate) {
throw new ConcurrentModificationException();
}
} else if (delegate.isEmpty()) {
Collection<V> newDelegate = map.get(key);
if (newDelegate != null) {
delegate = newDelegate;
}
}
}
/**
* If collection is empty, remove it from {@code AbstractMultimap.this.map}.
* For subcollections, check whether the ancestor collection is empty.
*/
void removeIfEmpty() {
if (ancestor != null) {
ancestor.removeIfEmpty();
} else if (delegate.isEmpty()) {
map.remove(key);
}
}
K getKey() {
return key;
}
/**
* Add the delegate to the map. Other {@code WrappedCollection} methods
* should call this method after adding elements to a previously empty
* collection.
*
* <p>Subcollection add the ancestor's delegate instead.
*/
void addToMap() {
if (ancestor != null) {
ancestor.addToMap();
} else {
map.put(key, delegate);
}
}
@Override public int size() {
refreshIfEmpty();
return delegate.size();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
refreshIfEmpty();
return delegate.equals(object);
}
@Override public int hashCode() {
refreshIfEmpty();
return delegate.hashCode();
}
@Override public String toString() {
refreshIfEmpty();
return delegate.toString();
}
Collection<V> getDelegate() {
return delegate;
}
@Override public Iterator<V> iterator() {
refreshIfEmpty();
return new WrappedIterator();
}
/** Collection iterator for {@code WrappedCollection}. */
class WrappedIterator implements Iterator<V> {
final Iterator<V> delegateIterator;
final Collection<V> originalDelegate = delegate;
WrappedIterator() {
delegateIterator = iteratorOrListIterator(delegate);
}
WrappedIterator(Iterator<V> delegateIterator) {
this.delegateIterator = delegateIterator;
}
/**
* If the delegate changed since the iterator was created, the iterator is
* no longer valid.
*/
void validateIterator() {
refreshIfEmpty();
if (delegate != originalDelegate) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
validateIterator();
return delegateIterator.hasNext();
}
@Override
public V next() {
validateIterator();
return delegateIterator.next();
}
@Override
public void remove() {
delegateIterator.remove();
totalSize--;
removeIfEmpty();
}
Iterator<V> getDelegateIterator() {
validateIterator();
return delegateIterator;
}
}
@Override public boolean add(V value) {
refreshIfEmpty();
boolean wasEmpty = delegate.isEmpty();
boolean changed = delegate.add(value);
if (changed) {
totalSize++;
if (wasEmpty) {
addToMap();
}
}
return changed;
}
WrappedCollection getAncestor() {
return ancestor;
}
// The following methods are provided for better performance.
@Override public boolean addAll(Collection<? extends V> collection) {
if (collection.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.addAll(collection);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override public boolean contains(Object o) {
refreshIfEmpty();
return delegate.contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
refreshIfEmpty();
return delegate.containsAll(c);
}
@Override public void clear() {
int oldSize = size(); // calls refreshIfEmpty
if (oldSize == 0) {
return;
}
delegate.clear();
totalSize -= oldSize;
removeIfEmpty(); // maybe shouldn't be removed if this is a sublist
}
@Override public boolean remove(Object o) {
refreshIfEmpty();
boolean changed = delegate.remove(o);
if (changed) {
totalSize--;
removeIfEmpty();
}
return changed;
}
@Override public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.removeAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
checkNotNull(c);
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.retainAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
private Iterator<V> iteratorOrListIterator(Collection<V> collection) {
return (collection instanceof List)
? ((List<V>) collection).listIterator()
: collection.iterator();
}
/** Set decorator that stays in sync with the multimap values for a key. */
private class WrappedSet extends WrappedCollection implements Set<V> {
WrappedSet(@Nullable K key, Set<V> delegate) {
super(key, delegate, null);
}
@Override
public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
// Guava issue 1013: AbstractSet and most JDK set implementations are
// susceptible to quadratic removeAll performance on lists;
// use a slightly smarter implementation here
boolean changed = Sets.removeAllImpl((Set<V>) delegate, c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
/**
* SortedSet decorator that stays in sync with the multimap values for a key.
*/
private class WrappedSortedSet extends WrappedCollection
implements SortedSet<V> {
WrappedSortedSet(@Nullable K key, SortedSet<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
SortedSet<V> getSortedSetDelegate() {
return (SortedSet<V>) getDelegate();
}
@Override
public Comparator<? super V> comparator() {
return getSortedSetDelegate().comparator();
}
@Override
public V first() {
refreshIfEmpty();
return getSortedSetDelegate().first();
}
@Override
public V last() {
refreshIfEmpty();
return getSortedSetDelegate().last();
}
@Override
public SortedSet<V> headSet(V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().headSet(toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> subSet(V fromElement, V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().subSet(fromElement, toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> tailSet(V fromElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().tailSet(fromElement),
(getAncestor() == null) ? this : getAncestor());
}
}
/** List decorator that stays in sync with the multimap values for a key. */
private class WrappedList extends WrappedCollection implements List<V> {
WrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
List<V> getListDelegate() {
return (List<V>) getDelegate();
}
@Override
public boolean addAll(int index, Collection<? extends V> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = getListDelegate().addAll(index, c);
if (changed) {
int newSize = getDelegate().size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override
public V get(int index) {
refreshIfEmpty();
return getListDelegate().get(index);
}
@Override
public V set(int index, V element) {
refreshIfEmpty();
return getListDelegate().set(index, element);
}
@Override
public void add(int index, V element) {
refreshIfEmpty();
boolean wasEmpty = getDelegate().isEmpty();
getListDelegate().add(index, element);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
@Override
public V remove(int index) {
refreshIfEmpty();
V value = getListDelegate().remove(index);
totalSize--;
removeIfEmpty();
return value;
}
@Override
public int indexOf(Object o) {
refreshIfEmpty();
return getListDelegate().indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
refreshIfEmpty();
return getListDelegate().lastIndexOf(o);
}
@Override
public ListIterator<V> listIterator() {
refreshIfEmpty();
return new WrappedListIterator();
}
@Override
public ListIterator<V> listIterator(int index) {
refreshIfEmpty();
return new WrappedListIterator(index);
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
refreshIfEmpty();
return wrapList(getKey(),
getListDelegate().subList(fromIndex, toIndex),
(getAncestor() == null) ? this : getAncestor());
}
/** ListIterator decorator. */
private class WrappedListIterator extends WrappedIterator
implements ListIterator<V> {
WrappedListIterator() {}
public WrappedListIterator(int index) {
super(getListDelegate().listIterator(index));
}
private ListIterator<V> getDelegateListIterator() {
return (ListIterator<V>) getDelegateIterator();
}
@Override
public boolean hasPrevious() {
return getDelegateListIterator().hasPrevious();
}
@Override
public V previous() {
return getDelegateListIterator().previous();
}
@Override
public int nextIndex() {
return getDelegateListIterator().nextIndex();
}
@Override
public int previousIndex() {
return getDelegateListIterator().previousIndex();
}
@Override
public void set(V value) {
getDelegateListIterator().set(value);
}
@Override
public void add(V value) {
boolean wasEmpty = isEmpty();
getDelegateListIterator().add(value);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
}
}
/**
* List decorator that stays in sync with the multimap values for a key and
* supports rapid random access.
*/
private class RandomAccessWrappedList extends WrappedList
implements RandomAccess {
RandomAccessWrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
}
private transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
private Set<K> createKeySet() {
return (map instanceof SortedMap)
? new SortedKeySet((SortedMap<K, Collection<V>>) map) : new KeySet(map);
}
private class KeySet extends Maps.KeySet<K, Collection<V>> {
/**
* This is usually the same as map, except when someone requests a
* subcollection of a {@link SortedKeySet}.
*/
final Map<K, Collection<V>> subMap;
KeySet(final Map<K, Collection<V>> subMap) {
this.subMap = subMap;
}
@Override
Map<K, Collection<V>> map() {
return subMap;
}
@Override public Iterator<K> iterator() {
return new Iterator<K>() {
final Iterator<Map.Entry<K, Collection<V>>> entryIterator
= subMap.entrySet().iterator();
Map.Entry<K, Collection<V>> entry;
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public K next() {
entry = entryIterator.next();
return entry.getKey();
}
@Override
public void remove() {
Iterators.checkRemove(entry != null);
Collection<V> collection = entry.getValue();
entryIterator.remove();
totalSize -= collection.size();
collection.clear();
}
};
}
// The following methods are included for better performance.
@Override public boolean remove(Object key) {
int count = 0;
Collection<V> collection = subMap.remove(key);
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count > 0;
}
@Override
public void clear() {
Iterators.clear(iterator());
}
@Override public boolean containsAll(Collection<?> c) {
return subMap.keySet().containsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return this == object || this.subMap.keySet().equals(object);
}
@Override public int hashCode() {
return subMap.keySet().hashCode();
}
}
private class SortedKeySet extends KeySet implements SortedSet<K> {
SortedKeySet(SortedMap<K, Collection<V>> subMap) {
super(subMap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) subMap;
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K first() {
return sortedMap().firstKey();
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet(sortedMap().headMap(toElement));
}
@Override
public K last() {
return sortedMap().lastKey();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet(sortedMap().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet(sortedMap().tailMap(fromElement));
}
}
private transient Multiset<K> multiset;
@Override
public Multiset<K> keys() {
Multiset<K> result = multiset;
if (result == null) {
return multiset = new Multimaps.Keys<K, V>() {
@Override Multimap<K, V> multimap() {
return AbstractMultimap.this;
}
};
}
return result;
}
/**
* Removes all values for the provided key. Unlike {@link #removeAll}, it
* returns the number of removed mappings.
*/
private int removeValuesForKey(Object key) {
Collection<V> collection;
try {
collection = map.remove(key);
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
int count = 0;
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count;
}
private transient Collection<V> valuesCollection;
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*/
@Override public Collection<V> values() {
Collection<V> result = valuesCollection;
if (result == null) {
return valuesCollection = new Multimaps.Values<K, V>() {
@Override Multimap<K, V> multimap() {
return AbstractMultimap.this;
}
};
}
return result;
}
private transient Collection<Map.Entry<K, V>> entries;
/*
* TODO(kevinb): should we copy this javadoc to each concrete class, so that
* classes like LinkedHashMultimap that need to say something different are
* still able to {@inheritDoc} all the way from Multimap?
*/
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the
* multimap, taken at the time the entry is returned by a method call to the
* collection or its iterator.
*/
@Override
public Collection<Map.Entry<K, V>> entries() {
Collection<Map.Entry<K, V>> result = entries;
return (result == null) ? entries = createEntries() : result;
}
Collection<Map.Entry<K, V>> createEntries() {
if (this instanceof SetMultimap) {
return new Multimaps.EntrySet<K, V>() {
@Override Multimap<K, V> multimap() {
return AbstractMultimap.this;
}
@Override public Iterator<Entry<K, V>> iterator() {
return createEntryIterator();
}
};
}
return new Multimaps.Entries<K, V>() {
@Override Multimap<K, V> multimap() {
return AbstractMultimap.this;
}
@Override public Iterator<Entry<K, V>> iterator() {
return createEntryIterator();
}
};
}
/**
* Returns an iterator across all key-value map entries, used by {@code
* entries().iterator()} and {@code values().iterator()}. The default
* behavior, which traverses the values for one key, the values for a second
* key, and so on, suffices for most {@code AbstractMultimap} implementations.
*
* @return an iterator across map entries
*/
Iterator<Map.Entry<K, V>> createEntryIterator() {
return new EntryIterator();
}
/** Iterator across all key-value pairs. */
private class EntryIterator implements Iterator<Map.Entry<K, V>> {
final Iterator<Map.Entry<K, Collection<V>>> keyIterator;
K key;
Collection<V> collection;
Iterator<V> valueIterator;
EntryIterator() {
keyIterator = map.entrySet().iterator();
if (keyIterator.hasNext()) {
findValueIteratorAndKey();
} else {
valueIterator = Iterators.emptyModifiableIterator();
}
}
void findValueIteratorAndKey() {
Map.Entry<K, Collection<V>> entry = keyIterator.next();
key = entry.getKey();
collection = entry.getValue();
valueIterator = collection.iterator();
}
@Override
public boolean hasNext() {
return keyIterator.hasNext() || valueIterator.hasNext();
}
@Override
public Map.Entry<K, V> next() {
if (!valueIterator.hasNext()) {
findValueIteratorAndKey();
}
return Maps.immutableEntry(key, valueIterator.next());
}
@Override
public void remove() {
valueIterator.remove();
if (collection.isEmpty()) {
keyIterator.remove();
}
totalSize--;
}
}
private transient Map<K, Collection<V>> asMap;
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
return (result == null) ? asMap = createAsMap() : result;
}
private Map<K, Collection<V>> createAsMap() {
return (map instanceof SortedMap)
? new SortedAsMap((SortedMap<K, Collection<V>>) map) : new AsMap(map);
}
private class AsMap extends AbstractMap<K, Collection<V>> {
/**
* Usually the same as map, but smaller for the headMap(), tailMap(), or
* subMap() of a SortedAsMap.
*/
final transient Map<K, Collection<V>> submap;
AsMap(Map<K, Collection<V>> submap) {
this.submap = submap;
}
transient Set<Map.Entry<K, Collection<V>>> entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
Set<Map.Entry<K, Collection<V>>> result = entrySet;
return (result == null) ? entrySet = new AsMapEntries() : result;
}
// The following methods are included for performance.
@Override public boolean containsKey(Object key) {
return Maps.safeContainsKey(submap, key);
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = Maps.safeGet(submap, key);
if (collection == null) {
return null;
}
@SuppressWarnings("unchecked")
K k = (K) key;
return wrapCollection(k, collection);
}
@Override public Set<K> keySet() {
return AbstractMultimap.this.keySet();
}
@Override
public int size() {
return submap.size();
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = submap.remove(key);
if (collection == null) {
return null;
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return output;
}
@Override public boolean equals(@Nullable Object object) {
return this == object || submap.equals(object);
}
@Override public int hashCode() {
return submap.hashCode();
}
@Override public String toString() {
return submap.toString();
}
@Override
public void clear() {
if (submap == map) {
AbstractMultimap.this.clear();
} else {
Iterators.clear(new AsMapIterator());
}
}
class AsMapEntries extends Maps.EntrySet<K, Collection<V>> {
@Override
Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return new AsMapIterator();
}
// The following methods are included for performance.
@Override public boolean contains(Object o) {
return Collections2.safeContains(submap.entrySet(), o);
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
/** Iterator across all keys and value collections. */
class AsMapIterator implements Iterator<Map.Entry<K, Collection<V>>> {
final Iterator<Map.Entry<K, Collection<V>>> delegateIterator
= submap.entrySet().iterator();
Collection<V> collection;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public Map.Entry<K, Collection<V>> next() {
Map.Entry<K, Collection<V>> entry = delegateIterator.next();
K key = entry.getKey();
collection = entry.getValue();
return Maps.immutableEntry(key, wrapCollection(key, collection));
}
@Override
public void remove() {
delegateIterator.remove();
totalSize -= collection.size();
collection.clear();
}
}
}
private class SortedAsMap extends AsMap
implements SortedMap<K, Collection<V>> {
SortedAsMap(SortedMap<K, Collection<V>> submap) {
super(submap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) submap;
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K firstKey() {
return sortedMap().firstKey();
}
@Override
public K lastKey() {
return sortedMap().lastKey();
}
@Override
public SortedMap<K, Collection<V>> headMap(K toKey) {
return new SortedAsMap(sortedMap().headMap(toKey));
}
@Override
public SortedMap<K, Collection<V>> subMap(K fromKey, K toKey) {
return new SortedAsMap(sortedMap().subMap(fromKey, toKey));
}
@Override
public SortedMap<K, Collection<V>> tailMap(K fromKey) {
return new SortedAsMap(sortedMap().tailMap(fromKey));
}
SortedSet<K> sortedKeySet;
// returns a SortedSet, even though returning a Set would be sufficient to
// satisfy the SortedMap.keySet() interface
@Override public SortedSet<K> keySet() {
SortedSet<K> result = sortedKeySet;
return (result == null)
? sortedKeySet = new SortedKeySet(sortedMap()) : result;
}
}
// Comparison and hashing
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return this.map.equals(that.asMap());
}
return false;
}
/**
* Returns the hash code for this multimap.
*
* <p>The hash code of a multimap is defined as the hash code of the map view,
* as returned by {@link Multimap#asMap}.
*
* @see Map#hashCode
*/
@Override public int hashCode() {
return map.hashCode();
}
/**
* Returns a string representation of the multimap, generated by calling
* {@code toString} on the map returned by {@link Multimap#asMap}.
*
* @return a string representation of the multimap
*/
@Override
public String toString() {
return map.toString();
}
private static final long serialVersionUID = 2447537837011683357L;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
/**
* Multiset implementation backed by a {@link HashMap}.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> {
/**
* Creates a new, empty {@code HashMultiset} using the default initial
* capacity.
*/
public static <E> HashMultiset<E> create() {
return new HashMultiset<E>();
}
/**
* Creates a new, empty {@code HashMultiset} with the specified expected
* number of distinct elements.
*
* @param distinctElements the expected number of distinct elements
* @throws IllegalArgumentException if {@code distinctElements} is negative
*/
public static <E> HashMultiset<E> create(int distinctElements) {
return new HashMultiset<E>(distinctElements);
}
/**
* Creates a new {@code HashMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself
* a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
*/
public static <E> HashMultiset<E> create(Iterable<? extends E> elements) {
HashMultiset<E> multiset =
create(Multisets.inferDistinctElements(elements));
Iterables.addAll(multiset, elements);
return multiset;
}
private HashMultiset() {
super(new HashMap<E, Count>());
}
private HashMultiset(int distinctElements) {
super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements));
}
/**
* @serialData the number of distinct elements, the first element, its count,
* the second element, its count, and so on
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultiset(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int distinctElements = Serialization.readCount(stream);
setBackingMap(
Maps.<E, Count>newHashMapWithExpectedSize(distinctElements));
Serialization.populateMultiset(this, stream, distinctElements);
}
@GwtIncompatible("Not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
/**
* Static methods for implementing hash-based collections.
*
* @author Kevin Bourrillion
* @author Jesse Wilson
*/
@GwtCompatible
final class Hashing {
private Hashing() {}
/*
* This method was written by Doug Lea with assistance from members of JCP
* JSR-166 Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*
* As of 2010/06/11, this method is identical to the (package private) hash
* method in OpenJDK 7's java.util.HashMap class.
*/
static int smear(int hashCode) {
hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
}
}
| Java |
/*
* 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 static com.google.common.collect.Iterables.getOnlyElement;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An immutable, hash-based {@link Map} with reliable user-specified iteration
* order. Does not permit null keys or values.
*
* <p>Unlike {@link Collections#unmodifiableMap}, which is a <i>view</i> of a
* separate map which can still change, an instance of {@code ImmutableMap}
* contains its own data and will <i>never</i> change. {@code ImmutableMap} is
* convenient for {@code public static final} maps ("constant maps") and also
* lets you easily make a "defensive copy" of a map provided to your class by a
* caller.
*
* <p><i>Performance notes:</i> unlike {@link HashMap}, {@code ImmutableMap} is
* not optimized for element types that have slow {@link Object#equals} or
* {@link Object#hashCode} implementations. You can get better performance by
* having your element type cache its own hash codes, and by making use of the
* cached values to short-circuit a slow {@code equals} algorithm.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
/**
* Returns the empty map. This map behaves and performs comparably to
* {@link Collections#emptyMap}, and is preferable mainly for consistency
* and maintainability of your code.
*/
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableMap<K, V> of() {
return (ImmutableMap<K, V>) EmptyImmutableMap.INSTANCE;
}
/**
* Returns an immutable map containing a single entry. This map behaves and
* performs comparably to {@link Collections#singletonMap} but will not accept
* a null key or value. It is preferable mainly for consistency and
* maintainability of your code.
*/
public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
return new SingletonImmutableMap<K, V>(
checkNotNull(k1, "null key in entry: null=%s", v1),
checkNotNull(v1, "null value in entry: %s=null", k1));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return new RegularImmutableMap<K, V>(
entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new RegularImmutableMap<K, V>(
entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new RegularImmutableMap<K, V>(entryOf(k1, v1),
entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Verifies that {@code key} and {@code value} are non-null, and returns a new
* immutable entry with those values.
*
* <p>A call to {@link Map.Entry#setValue} on the returned entry will always
* throw {@link UnsupportedOperationException}.
*/
static <K, V> Entry<K, V> entryOf(K key, V value) {
checkNotNull(key, "null key in entry: null=%s", value);
checkNotNull(value, "null value in entry: %s=null", key);
return Maps.immutableEntry(key, value);
}
/**
* A builder for creating immutable map instances, especially {@code public
* static final} maps ("constant maps"). Example: <pre> {@code
*
* static final ImmutableMap<String, Integer> WORD_TO_INT =
* new ImmutableMap.Builder<String, Integer>()
* .put("one", 1)
* .put("two", 2)
* .put("three", 3)
* .build();}</pre>
*
* For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are
* even more convenient.
*
* <p>Builder instances can be reused - it is safe to call {@link #build}
* multiple times to build multiple maps in series. Each map is a superset of
* the maps created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<K, V> {
final ArrayList<Entry<K, V>> entries = Lists.newArrayList();
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMap#builder}.
*/
public Builder() {}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys are not allowed, and will cause {@link #build} to fail.
*/
public Builder<K, V> put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
/**
* Adds the given {@code entry} to the map, making it immutable if
* necessary. Duplicate keys are not allowed, and will cause {@link #build}
* to fail.
*
* @since 11.0
*/
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
K key = entry.getKey();
V value = entry.getValue();
if (entry instanceof ImmutableEntry) {
checkNotNull(key);
checkNotNull(value);
@SuppressWarnings("unchecked") // all supported methods are covariant
Entry<K, V> immutableEntry = (Entry<K, V>) entry;
entries.add(immutableEntry);
} else {
// Directly calling entryOf(entry.getKey(), entry.getValue()) can cause
// compilation error in Eclipse.
entries.add(entryOf(key, value));
}
return this;
}
/**
* Associates all of the given map's keys and values in the built map.
* Duplicate keys are not allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
entries.ensureCapacity(entries.size() + map.size());
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
/*
* TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap
* versions throw an IllegalStateException instead?
*/
/**
* Returns a newly-created immutable map.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableMap<K, V> build() {
return fromEntryList(entries);
}
private static <K, V> ImmutableMap<K, V> fromEntryList(
List<Entry<K, V>> entries) {
int size = entries.size();
switch (size) {
case 0:
return of();
case 1:
return new SingletonImmutableMap<K, V>(getOnlyElement(entries));
default:
Entry<?, ?>[] entryArray
= entries.toArray(new Entry<?, ?>[entries.size()]);
return new RegularImmutableMap<K, V>(entryArray);
}
}
}
/**
* Returns an immutable map containing the same entries as {@code map}. If
* {@code map} somehow contains entries with duplicate keys (for example, if
* it is a {@code SortedMap} whose comparator is not <i>consistent with
* equals</i>), the results of this method are undefined.
*
* <p>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 NullPointerException if any key or value in {@code map} is null
*/
public static <K, V> ImmutableMap<K, V> copyOf(
Map<? extends K, ? extends V> map) {
if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) {
// TODO(user): Make ImmutableMap.copyOf(immutableBiMap) call copyOf()
// on the ImmutableMap delegate(), rather than the bimap itself
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
if (!kvMap.isPartialView()) {
return kvMap;
}
}
@SuppressWarnings("unchecked") // we won't write to this array
Entry<K, V>[] entries = map.entrySet().toArray(new Entry[0]);
switch (entries.length) {
case 0:
return of();
case 1:
return new SingletonImmutableMap<K, V>(entryOf(
entries[0].getKey(), entries[0].getValue()));
default:
for (int i = 0; i < entries.length; i++) {
K k = entries[i].getKey();
V v = entries[i].getValue();
entries[i] = entryOf(k, v);
}
return new RegularImmutableMap<K, V>(entries);
}
}
ImmutableMap() {}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final V put(K k, V v) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final V remove(Object o) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(@Nullable Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(@Nullable Object value) {
return value != null && Maps.containsValueImpl(this, value);
}
// Overriding to mark it Nullable
@Override
public abstract V get(@Nullable Object key);
private transient ImmutableSet<Entry<K, V>> entrySet;
/**
* Returns an immutable set of the mappings in this map. The entries are in
* the same order as the parameters used to build this map.
*/
@Override
public ImmutableSet<Entry<K, V>> entrySet() {
ImmutableSet<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
abstract ImmutableSet<Entry<K, V>> createEntrySet();
private transient ImmutableSet<K> keySet;
/**
* Returns an immutable set of the keys in this map. These keys are in
* the same order as the parameters used to build this map.
*/
@Override
public ImmutableSet<K> keySet() {
ImmutableSet<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<K, V>(entrySet()) {
@Override ImmutableMap<K, V> map() {
return ImmutableMap.this;
}
};
}
private transient ImmutableCollection<V> values;
/**
* Returns an immutable collection of the values in this map. The values are
* in the same order as the parameters used to build this map.
*/
@Override
public ImmutableCollection<V> values() {
ImmutableCollection<V> result = values;
return (result == null) ? values = createValues() : result;
}
ImmutableCollection<V> createValues() {
return new ImmutableMapValues<K, V>() {
@Override ImmutableMap<K, V> map() {
return ImmutableMap.this;
}
};
}
@Override public boolean equals(@Nullable Object object) {
return Maps.equalsImpl(this, object);
}
abstract boolean isPartialView();
@Override public int hashCode() {
// not caching hash code since it could change if map values are mutable
// in a way that modifies their hash codes
return entrySet().hashCode();
}
@Override public String toString() {
return Maps.toStringImpl(this);
}
/**
* Serialized type for all ImmutableMap instances. It captures the logical
* contents and they are reconstructed using public factory methods. This
* ensures that the implementation types remain as implementation details.
*/
static class SerializedForm implements Serializable {
private final Object[] keys;
private final Object[] values;
SerializedForm(ImmutableMap<?, ?> map) {
keys = new Object[map.size()];
values = new Object[map.size()];
int i = 0;
for (Entry<?, ?> entry : map.entrySet()) {
keys[i] = entry.getKey();
values[i] = entry.getValue();
i++;
}
}
Object readResolve() {
Builder<Object, Object> builder = new Builder<Object, Object>();
return createMap(builder);
}
Object createMap(Builder<Object, Object> builder) {
for (int i = 0; i < keys.length; i++) {
builder.put(keys[i], values[i]);
}
return builder.build();
}
private static final long serialVersionUID = 0;
}
Object writeReplace() {
return new SerializedForm(this);
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible;
/**
* Wraps an exception that occurred during a computation.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public class ComputationException extends RuntimeException {
/**
* Creates a new instance with the given cause.
*/
public ComputationException(Throwable cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
/**
* An iterator that does not support {@link #remove}.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class UnmodifiableIterator<E> implements Iterator<E> {
/** Constructor for use by subclasses. */
protected UnmodifiableIterator() {}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An iterator that supports a one-element lookahead while iterating.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionHelpersExplained#PeekingIterator">
* {@code PeekingIterator}</a>.
*
* @author Mick Killianey
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface PeekingIterator<E> extends Iterator<E> {
/**
* Returns the next element in the iteration, without advancing the iteration.
*
* <p>Calls to {@code peek()} should not change the state of the iteration,
* except that it <i>may</i> prevent removal of the most recent element via
* {@link #remove()}.
*
* @throws NoSuchElementException if the iteration has no more elements
* according to {@link #hasNext()}
*/
E peek();
/**
* {@inheritDoc}
*
* <p>The objects returned by consecutive calls to {@link #peek()} then {@link
* #next()} are guaranteed to be equal to each other.
*/
@Override
E next();
/**
* {@inheritDoc}
*
* <p>Implementations may or may not support removal when a call to {@link
* #peek()} has occurred since the most recent call to {@link #next()}.
*
* @throws IllegalStateException if there has been a call to {@link #peek()}
* since the most recent call to {@link #next()} and this implementation
* does not support this sequence of calls (optional)
*/
@Override
void remove();
}
| Java |
/*
* 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.checkNotNull;
import java.util.Collection;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* An empty immutable sorted multiset.
*
* @author Louis Wasserman
*/
@SuppressWarnings("serial") // Uses writeReplace, not default serialization
final class EmptyImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> {
private final ImmutableSortedSet<E> elementSet;
EmptyImmutableSortedMultiset(Comparator<? super E> comparator) {
this.elementSet = ImmutableSortedSet.emptySet(comparator);
}
@Override
public Entry<E> firstEntry() {
return null;
}
@Override
public Entry<E> lastEntry() {
return null;
}
@Override
public int count(@Nullable Object element) {
return 0;
}
@Override
public boolean contains(@Nullable Object object) {
return false;
}
@Override
public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override
public int size() {
return 0;
}
@Override
public ImmutableSortedSet<E> elementSet() {
return elementSet;
}
@Override
public ImmutableSet<Entry<E>> entrySet() {
return ImmutableSet.of();
}
@Override
ImmutableSet<Entry<E>> createEntrySet() {
throw new AssertionError("should never be called");
}
@Override
public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
checkNotNull(upperBound);
checkNotNull(boundType);
return this;
}
@Override
public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
checkNotNull(lowerBound);
checkNotNull(boundType);
return this;
}
@Override
public UnmodifiableIterator<E> iterator() {
return Iterators.emptyIterator();
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Multiset) {
Multiset<?> other = (Multiset<?>) object;
return other.isEmpty();
}
return false;
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return "[]";
}
@Override
boolean isPartialView() {
return false;
}
@Override
public Object[] toArray() {
return ObjectArrays.EMPTY_ARRAY;
}
@Override
public <T> T[] toArray(T[] other) {
return asList().toArray(other);
}
@Override
public ImmutableList<E> asList() {
return ImmutableList.of();
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An empty immutable sorted set.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> {
EmptyImmutableSortedSet(Comparator<? super E> comparator) {
super(comparator);
}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean contains(Object target) {
return false;
}
@Override public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
@Override public ImmutableList<E> asList() {
return ImmutableList.of();
}
@Override public Object[] toArray() {
return ObjectArrays.EMPTY_ARRAY;
}
@Override public <T> T[] toArray(T[] a) {
return asList().toArray(a);
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.isEmpty();
}
return false;
}
@Override public int hashCode() {
return 0;
}
@Override public String toString() {
return "[]";
}
@Override
public E first() {
throw new NoSuchElementException();
}
@Override
public E last() {
throw new NoSuchElementException();
}
@Override
ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) {
return this;
}
@Override
ImmutableSortedSet<E> subSetImpl(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return this;
}
@Override
ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) {
return this;
}
@Override int indexOf(@Nullable Object target) {
return -1;
}
@Override
ImmutableSortedSet<E> createDescendingSet() {
return new EmptyImmutableSortedSet<E>(Ordering.from(comparator).reverse());
}
}
| Java |
/*
* Copyright (C) 2009 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.Booleans;
import java.io.Serializable;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* Implementation detail for the internal structure of {@link Range} instances. Represents
* a unique way of "cutting" a "number line" (actually of instances of type {@code C}, not
* necessarily "numbers") into two sections; this can be done below a certain value, above
* a certain value, below all values or above all values. With this object defined in this
* way, an interval can always be represented by a pair of {@code Cut} instances.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
abstract class Cut<C extends Comparable> implements Comparable<Cut<C>>, Serializable {
final C endpoint;
Cut(@Nullable C endpoint) {
this.endpoint = endpoint;
}
abstract boolean isLessThan(C value);
abstract BoundType typeAsLowerBound();
abstract BoundType typeAsUpperBound();
abstract Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain);
abstract Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain);
abstract void describeAsLowerBound(StringBuilder sb);
abstract void describeAsUpperBound(StringBuilder sb);
abstract C leastValueAbove(DiscreteDomain<C> domain);
abstract C greatestValueBelow(DiscreteDomain<C> domain);
/*
* The canonical form is a BelowValue cut whenever possible, otherwise ABOVE_ALL, or
* (only in the case of types that are unbounded below) BELOW_ALL.
*/
Cut<C> canonical(DiscreteDomain<C> domain) {
return this;
}
// note: overriden by {BELOW,ABOVE}_ALL
@Override
public int compareTo(Cut<C> that) {
if (that == belowAll()) {
return 1;
}
if (that == aboveAll()) {
return -1;
}
int result = Range.compareOrThrow(endpoint, that.endpoint);
if (result != 0) {
return result;
}
// same value. below comes before above
return Booleans.compare(
this instanceof AboveValue, that instanceof AboveValue);
}
C endpoint() {
return endpoint;
}
@SuppressWarnings("unchecked") // catching CCE
@Override public boolean equals(Object obj) {
if (obj instanceof Cut) {
// It might not really be a Cut<C>, but we'll catch a CCE if it's not
Cut<C> that = (Cut<C>) obj;
try {
int compareResult = compareTo(that);
return compareResult == 0;
} catch (ClassCastException ignored) {
}
}
return false;
}
/*
* The implementation neither produces nor consumes any non-null instance of type C, so
* casting the type parameter is safe.
*/
@SuppressWarnings("unchecked")
static <C extends Comparable> Cut<C> belowAll() {
return (Cut<C>) BelowAll.INSTANCE;
}
private static final long serialVersionUID = 0;
private static final class BelowAll extends Cut<Comparable<?>> {
private static final BelowAll INSTANCE = new BelowAll();
private BelowAll() {
super(null);
}
@Override Comparable<?> endpoint() {
throw new IllegalStateException("range unbounded on this side");
}
@Override boolean isLessThan(Comparable<?> value) {
return true;
}
@Override BoundType typeAsLowerBound() {
throw new IllegalStateException();
}
@Override BoundType typeAsUpperBound() {
throw new AssertionError("this statement should be unreachable");
}
@Override Cut<Comparable<?>> withLowerBoundType(BoundType boundType,
DiscreteDomain<Comparable<?>> domain) {
throw new IllegalStateException();
}
@Override Cut<Comparable<?>> withUpperBoundType(BoundType boundType,
DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError("this statement should be unreachable");
}
@Override void describeAsLowerBound(StringBuilder sb) {
sb.append("(-\u221e");
}
@Override void describeAsUpperBound(StringBuilder sb) {
throw new AssertionError();
}
@Override Comparable<?> leastValueAbove(
DiscreteDomain<Comparable<?>> domain) {
return domain.minValue();
}
@Override Comparable<?> greatestValueBelow(
DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError();
}
@Override Cut<Comparable<?>> canonical(
DiscreteDomain<Comparable<?>> domain) {
try {
return Cut.<Comparable<?>>belowValue(domain.minValue());
} catch (NoSuchElementException e) {
return this;
}
}
@Override public int compareTo(Cut<Comparable<?>> o) {
return (o == this) ? 0 : -1;
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 0;
}
/*
* The implementation neither produces nor consumes any non-null instance of
* type C, so casting the type parameter is safe.
*/
@SuppressWarnings("unchecked")
static <C extends Comparable> Cut<C> aboveAll() {
return (Cut<C>) AboveAll.INSTANCE;
}
private static final class AboveAll extends Cut<Comparable<?>> {
private static final AboveAll INSTANCE = new AboveAll();
private AboveAll() {
super(null);
}
@Override Comparable<?> endpoint() {
throw new IllegalStateException("range unbounded on this side");
}
@Override boolean isLessThan(Comparable<?> value) {
return false;
}
@Override BoundType typeAsLowerBound() {
throw new AssertionError("this statement should be unreachable");
}
@Override BoundType typeAsUpperBound() {
throw new IllegalStateException();
}
@Override Cut<Comparable<?>> withLowerBoundType(BoundType boundType,
DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError("this statement should be unreachable");
}
@Override Cut<Comparable<?>> withUpperBoundType(BoundType boundType,
DiscreteDomain<Comparable<?>> domain) {
throw new IllegalStateException();
}
@Override void describeAsLowerBound(StringBuilder sb) {
throw new AssertionError();
}
@Override void describeAsUpperBound(StringBuilder sb) {
sb.append("+\u221e)");
}
@Override Comparable<?> leastValueAbove(
DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError();
}
@Override Comparable<?> greatestValueBelow(
DiscreteDomain<Comparable<?>> domain) {
return domain.maxValue();
}
@Override public int compareTo(Cut<Comparable<?>> o) {
return (o == this) ? 0 : 1;
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 0;
}
static <C extends Comparable> Cut<C> belowValue(C endpoint) {
return new BelowValue<C>(endpoint);
}
private static final class BelowValue<C extends Comparable> extends Cut<C> {
BelowValue(C endpoint) {
super(checkNotNull(endpoint));
}
@Override boolean isLessThan(C value) {
return Range.compareOrThrow(endpoint, value) <= 0;
}
@Override BoundType typeAsLowerBound() {
return BoundType.CLOSED;
}
@Override BoundType typeAsUpperBound() {
return BoundType.OPEN;
}
@Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case CLOSED:
return this;
case OPEN:
@Nullable C previous = domain.previous(endpoint);
return (previous == null) ? Cut.<C>belowAll() : new AboveValue<C>(previous);
default:
throw new AssertionError();
}
}
@Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case CLOSED:
@Nullable C previous = domain.previous(endpoint);
return (previous == null) ? Cut.<C>aboveAll() : new AboveValue<C>(previous);
case OPEN:
return this;
default:
throw new AssertionError();
}
}
@Override void describeAsLowerBound(StringBuilder sb) {
sb.append('[').append(endpoint);
}
@Override void describeAsUpperBound(StringBuilder sb) {
sb.append(endpoint).append(')');
}
@Override C leastValueAbove(DiscreteDomain<C> domain) {
return endpoint;
}
@Override C greatestValueBelow(DiscreteDomain<C> domain) {
return domain.previous(endpoint);
}
@Override public int hashCode() {
return endpoint.hashCode();
}
private static final long serialVersionUID = 0;
}
static <C extends Comparable> Cut<C> aboveValue(C endpoint) {
return new AboveValue<C>(endpoint);
}
private static final class AboveValue<C extends Comparable> extends Cut<C> {
AboveValue(C endpoint) {
super(checkNotNull(endpoint));
}
@Override boolean isLessThan(C value) {
return Range.compareOrThrow(endpoint, value) < 0;
}
@Override BoundType typeAsLowerBound() {
return BoundType.OPEN;
}
@Override BoundType typeAsUpperBound() {
return BoundType.CLOSED;
}
@Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case OPEN:
return this;
case CLOSED:
@Nullable C next = domain.next(endpoint);
return (next == null) ? Cut.<C>belowAll() : belowValue(next);
default:
throw new AssertionError();
}
}
@Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case OPEN:
@Nullable C next = domain.next(endpoint);
return (next == null) ? Cut.<C>aboveAll() : belowValue(next);
case CLOSED:
return this;
default:
throw new AssertionError();
}
}
@Override void describeAsLowerBound(StringBuilder sb) {
sb.append('(').append(endpoint);
}
@Override void describeAsUpperBound(StringBuilder sb) {
sb.append(endpoint).append(']');
}
@Override C leastValueAbove(DiscreteDomain<C> domain) {
return domain.next(endpoint);
}
@Override C greatestValueBelow(DiscreteDomain<C> domain) {
return endpoint;
}
@Override Cut<C> canonical(DiscreteDomain<C> domain) {
C next = leastValueAbove(domain);
return (next != null) ? belowValue(next) : Cut.<C>aboveAll();
}
@Override public int hashCode() {
return ~endpoint.hashCode();
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Fixed-size {@link Table} implementation backed by a two-dimensional array.
*
* <p>The allowed row and column keys must be supplied when the table is
* created. The table always contains a mapping for every row key / column pair.
* The value corresponding to a given row and column is null unless another
* value is provided.
*
* <p>The table's size is constant: the product of the number of supplied row
* keys and the number of supplied column keys. The {@code remove} and {@code
* clear} methods are not supported by the table or its views. The {@link
* #erase} and {@link #eraseAll} methods may be used instead.
*
* <p>The ordering of the row and column keys provided when the table is
* constructed determines the iteration ordering across rows and columns in the
* table's views. None of the view iterators support {@link Iterator#remove}.
* If the table is modified after an iterator is created, the iterator remains
* valid.
*
* <p>This class requires less memory than the {@link HashBasedTable} and {@link
* TreeBasedTable} implementations, except when the table is sparse.
*
* <p>Null row keys or column keys are not permitted.
*
* <p>This class provides methods involving the underlying array structure,
* where the array indices correspond to the position of a row or column in the
* lists of allowed keys and values. See the {@link #at}, {@link #set}, {@link
* #toArray}, {@link #rowKeyList}, and {@link #columnKeyList} methods for more
* details.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access the same cell of an {@code ArrayTable} concurrently and one of the
* threads modifies its value, there is no guarantee that the new value will be
* fully visible to the other threads. To guarantee that modifications are
* visible, synchronize access to the table. Unlike other {@code Table}
* implementations, synchronization is unnecessary between a thread that writes
* to one cell and a thread that reads from another.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table">
* {@code Table}</a>.
*
* @author Jared Levy
* @since 10.0
*/
@Beta
public final class ArrayTable<R, C, V> implements Table<R, C, V>, Serializable {
/**
* Creates an empty {@code ArrayTable}.
*
* @param rowKeys row keys that may be stored in the generated table
* @param columnKeys column keys that may be stored in the generated table
* @throws NullPointerException if any of the provided keys is null
* @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys}
* contains duplicates or is empty
*/
public static <R, C, V> ArrayTable<R, C, V> create(
Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
return new ArrayTable<R, C, V>(rowKeys, columnKeys);
}
/*
* TODO(jlevy): Add factory methods taking an Enum class, instead of an
* iterable, to specify the allowed row keys and/or column keys. Note that
* custom serialization logic is needed to support different enum sizes during
* serialization and deserialization.
*/
/**
* Creates an {@code ArrayTable} with the mappings in the provided table.
*
* <p>If {@code table} includes a mapping with row key {@code r} and a
* separate mapping with column key {@code c}, the returned table contains a
* mapping with row key {@code r} and column key {@code c}. If that row key /
* column key pair in not in {@code table}, the pair maps to {@code null} in
* the generated table.
*
* <p>The returned table allows subsequent {@code put} calls with the row keys
* in {@code table.rowKeySet()} and the column keys in {@code
* table.columnKeySet()}. Calling {@link #put} with other keys leads to an
* {@code IllegalArgumentException}.
*
* <p>The ordering of {@code table.rowKeySet()} and {@code
* table.columnKeySet()} determines the row and column iteration ordering of
* the returned table.
*
* @throws NullPointerException if {@code table} has a null key
* @throws IllegalArgumentException if the provided table is empty
*/
public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, V> table) {
return new ArrayTable<R, C, V>(table);
}
/**
* Creates an {@code ArrayTable} with the same mappings, allowed keys, and
* iteration ordering as the provided {@code ArrayTable}.
*/
public static <R, C, V> ArrayTable<R, C, V> create(
ArrayTable<R, C, V> table) {
return new ArrayTable<R, C, V>(table);
}
private final ImmutableList<R> rowList;
private final ImmutableList<C> columnList;
// TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
private final ImmutableMap<R, Integer> rowKeyToIndex;
private final ImmutableMap<C, Integer> columnKeyToIndex;
private final V[][] array;
private ArrayTable(Iterable<? extends R> rowKeys,
Iterable<? extends C> columnKeys) {
this.rowList = ImmutableList.copyOf(rowKeys);
this.columnList = ImmutableList.copyOf(columnKeys);
checkArgument(!rowList.isEmpty());
checkArgument(!columnList.isEmpty());
/*
* TODO(jlevy): Support empty rowKeys or columnKeys? If we do, when
* columnKeys is empty but rowKeys isn't, the table is empty but
* containsRow() can return true and rowKeySet() isn't empty.
*/
rowKeyToIndex = index(rowList);
columnKeyToIndex = index(columnList);
@SuppressWarnings("unchecked")
V[][] tmpArray
= (V[][]) new Object[rowList.size()][columnList.size()];
array = tmpArray;
}
private static <E> ImmutableMap<E, Integer> index(List<E> list) {
ImmutableMap.Builder<E, Integer> columnBuilder = ImmutableMap.builder();
for (int i = 0; i < list.size(); i++) {
columnBuilder.put(list.get(i), i);
}
return columnBuilder.build();
}
private ArrayTable(Table<R, C, V> table) {
this(table.rowKeySet(), table.columnKeySet());
putAll(table);
}
private ArrayTable(ArrayTable<R, C, V> table) {
rowList = table.rowList;
columnList = table.columnList;
rowKeyToIndex = table.rowKeyToIndex;
columnKeyToIndex = table.columnKeyToIndex;
@SuppressWarnings("unchecked")
V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()];
array = copy;
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
}
}
private abstract static class ArrayMap<K, V> extends Maps.ImprovedAbstractMap<K, V> {
private final ImmutableMap<K, Integer> keyIndex;
private ArrayMap(ImmutableMap<K, Integer> keyIndex) {
this.keyIndex = keyIndex;
}
@Override
public Set<K> keySet() {
return keyIndex.keySet();
}
K getKey(int index) {
return keyIndex.keySet().asList().get(index);
}
abstract String getKeyRole();
@Nullable abstract V getValue(int index);
@Nullable abstract V setValue(int index, V newValue);
@Override
public int size() {
return keyIndex.size();
}
@Override
public boolean isEmpty() {
return keyIndex.isEmpty();
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new Maps.EntrySet<K, V>() {
@Override
Map<K, V> map() {
return ArrayMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
@Override
protected Entry<K, V> get(final int index) {
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return ArrayMap.this.getKey(index);
}
@Override
public V getValue() {
return ArrayMap.this.getValue(index);
}
@Override
public V setValue(V value) {
return ArrayMap.this.setValue(index, value);
}
};
}
};
}
};
}
@Override
public boolean containsKey(@Nullable Object key) {
return keyIndex.containsKey(key);
}
@Override
public V get(@Nullable Object key) {
Integer index = keyIndex.get(key);
if (index == null) {
return null;
} else {
return getValue(index);
}
}
@Override
public V put(K key, V value) {
Integer index = keyIndex.get(key);
if (index == null) {
throw new IllegalArgumentException(
getKeyRole() + " " + key + " not in " + keyIndex.keySet());
}
return setValue(index, value);
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
/**
* Returns, as an immutable list, the row keys provided when the table was
* constructed, including those that are mapped to null values only.
*/
public ImmutableList<R> rowKeyList() {
return rowList;
}
/**
* Returns, as an immutable list, the column keys provided when the table was
* constructed, including those that are mapped to null values only.
*/
public ImmutableList<C> columnKeyList() {
return columnList;
}
/**
* Returns the value corresponding to the specified row and column indices.
* The same value is returned by {@code
* get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but
* this method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @return the value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code
* rowIndex} is greater then or equal to the number of allowed row keys,
* or {@code columnIndex} is greater then or equal to the number of
* allowed column keys
*/
public V at(int rowIndex, int columnIndex) {
return array[rowIndex][columnIndex];
}
/**
* Associates {@code value} with the specified row and column indices. The
* logic {@code
* put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)}
* has the same behavior, but this method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @param value value to store in the table
* @return the previous value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code
* rowIndex} is greater then or equal to the number of allowed row keys,
* or {@code columnIndex} is greater then or equal to the number of
* allowed column keys
*/
public V set(int rowIndex, int columnIndex, @Nullable V value) {
V oldValue = array[rowIndex][columnIndex];
array[rowIndex][columnIndex] = value;
return oldValue;
}
/**
* Returns a two-dimensional array with the table contents. The row and column
* indices correspond to the positions of the row and column in the iterables
* provided during table construction. If the table lacks a mapping for a
* given row and column, the corresponding array element is null.
*
* <p>Subsequent table changes will not modify the array, and vice versa.
*
* @param valueClass class of values stored in the returned array
*/
public V[][] toArray(Class<V> valueClass) {
// Can change to use varargs in JDK 1.6 if we want
@SuppressWarnings("unchecked") // TODO: safe?
V[][] copy = (V[][]) Array.newInstance(
valueClass, new int[] { rowList.size(), columnList.size() });
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
}
return copy;
}
/**
* Not supported. Use {@link #eraseAll} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #eraseAll}
*/
@Override
@Deprecated public void clear() {
throw new UnsupportedOperationException();
}
/**
* Associates the value {@code null} with every pair of allowed row and column
* keys.
*/
public void eraseAll() {
for (V[] row : array) {
Arrays.fill(row, null);
}
}
/**
* Returns {@code true} if the provided keys are among the keys provided when
* the table was constructed.
*/
@Override
public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
return containsRow(rowKey) && containsColumn(columnKey);
}
/**
* Returns {@code true} if the provided column key is among the column keys
* provided when the table was constructed.
*/
@Override
public boolean containsColumn(@Nullable Object columnKey) {
return columnKeyToIndex.containsKey(columnKey);
}
/**
* Returns {@code true} if the provided row key is among the row keys
* provided when the table was constructed.
*/
@Override
public boolean containsRow(@Nullable Object rowKey) {
return rowKeyToIndex.containsKey(rowKey);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (V[] row : array) {
for (V element : row) {
if (Objects.equal(value, element)) {
return true;
}
}
}
return false;
}
@Override
public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (rowIndex == null || columnIndex == null)
? null : array[rowIndex][columnIndex];
}
/**
* Always returns {@code false}.
*/
@Override
public boolean isEmpty() {
return false;
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if {@code rowKey} is not in {@link
* #rowKeySet()} or {@code columnKey} is not in {@link #columnKeySet()}.
*/
@Override
public V put(R rowKey, C columnKey, @Nullable V value) {
checkNotNull(rowKey);
checkNotNull(columnKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
Integer columnIndex = columnKeyToIndex.get(columnKey);
checkArgument(columnIndex != null,
"Column %s not in %s", columnKey, columnList);
return set(rowIndex, columnIndex, value);
}
/*
* TODO(jlevy): Consider creating a merge() method, similar to putAll() but
* copying non-null values only.
*/
/**
* {@inheritDoc}
*
* <p>If {@code table} is an {@code ArrayTable}, its null values will be
* stored in this table, possibly replacing values that were previously
* non-null.
*
* @throws NullPointerException if {@code table} has a null key
* @throws IllegalArgumentException if any of the provided table's row keys or
* column keys is not in {@link #rowKeySet()} or {@link #columnKeySet()}
*/
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
}
/**
* Not supported. Use {@link #erase} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #erase}
*/
@Override
@Deprecated public V remove(Object rowKey, Object columnKey) {
throw new UnsupportedOperationException();
}
/**
* Associates the value {@code null} with the specified keys, assuming both
* keys are valid. If either key is null or isn't among the keys provided
* during construction, this method has no effect.
*
* <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when
* both provided keys are valid.
*
* @param rowKey row key of mapping to be erased
* @param columnKey column key of mapping to be erased
* @return the value previously associated with the keys, or {@code null} if
* no mapping existed for the keys
*/
public V erase(@Nullable Object rowKey, @Nullable Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
if (rowIndex == null || columnIndex == null) {
return null;
}
return set(rowIndex, columnIndex, null);
}
// TODO(jlevy): Add eraseRow and eraseColumn methods?
@Override
public int size() {
return rowList.size() * columnList.size();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof Table) {
Table<?, ?, ?> other = (Table<?, ?, ?>) obj;
return cellSet().equals(other.cellSet());
}
return false;
}
@Override public int hashCode() {
return cellSet().hashCode();
}
/**
* Returns the string representation {@code rowMap().toString()}.
*/
@Override public String toString() {
return rowMap().toString();
}
private transient CellSet cellSet;
/**
* Returns an unmodifiable set of all row key / column key / value
* triplets. Changes to the table will update the returned set.
*
* <p>The returned set's iterator traverses the mappings with the first row
* key, the mappings with the second row key, and so on.
*
* <p>The value in the returned cells may change if the table subsequently
* changes.
*
* @return set of table cells consisting of row key / column key / value
* triplets
*/
@Override
public Set<Cell<R, C, V>> cellSet() {
CellSet set = cellSet;
return (set == null) ? cellSet = new CellSet() : set;
}
private class CellSet extends AbstractSet<Cell<R, C, V>> {
@Override public Iterator<Cell<R, C, V>> iterator() {
return new AbstractIndexedListIterator<Cell<R, C, V>>(size()) {
@Override protected Cell<R, C, V> get(final int index) {
return new Tables.AbstractCell<R, C, V>() {
final int rowIndex = index / columnList.size();
final int columnIndex = index % columnList.size();
@Override
public R getRowKey() {
return rowList.get(rowIndex);
}
@Override
public C getColumnKey() {
return columnList.get(columnIndex);
}
@Override
public V getValue() {
return array[rowIndex][columnIndex];
}
};
}
};
}
@Override public int size() {
return ArrayTable.this.size();
}
@Override public boolean contains(Object obj) {
if (obj instanceof Cell) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
Integer rowIndex = rowKeyToIndex.get(cell.getRowKey());
Integer columnIndex = columnKeyToIndex.get(cell.getColumnKey());
return rowIndex != null
&& columnIndex != null
&& Objects.equal(array[rowIndex][columnIndex], cell.getValue());
}
return false;
}
}
/**
* Returns a view of all mappings that have the given column key. If the
* column key isn't in {@link #columnKeySet()}, an empty immutable map is
* returned.
*
* <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map
* associates the row key with the corresponding value in the table. Changes
* to the returned map will update the underlying table, and vice versa.
*
* @param columnKey key of column to search for in the table
* @return the corresponding map from row keys to values
*/
@Override
public Map<R, V> column(C columnKey) {
checkNotNull(columnKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (columnIndex == null)
? ImmutableMap.<R, V>of() : new Column(columnIndex);
}
private class Column extends ArrayMap<R, V> {
final int columnIndex;
Column(int columnIndex) {
super(rowKeyToIndex);
this.columnIndex = columnIndex;
}
@Override
String getKeyRole() {
return "Row";
}
@Override
V getValue(int index) {
return at(index, columnIndex);
}
@Override
V setValue(int index, V newValue) {
return set(index, columnIndex, newValue);
}
}
/**
* Returns an immutable set of the valid column keys, including those that
* are associated with null values only.
*
* @return immutable set of column keys
*/
@Override
public ImmutableSet<C> columnKeySet() {
return columnKeyToIndex.keySet();
}
private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, V>> columnMap() {
ColumnMap map = columnMap;
return (map == null) ? columnMap = new ColumnMap() : map;
}
private class ColumnMap extends ArrayMap<C, Map<R, V>> {
private ColumnMap() {
super(columnKeyToIndex);
}
@Override
String getKeyRole() {
return "Column";
}
@Override
Map<R, V> getValue(int index) {
return new Column(index);
}
@Override
Map<R, V> setValue(int index, Map<R, V> newValue) {
throw new UnsupportedOperationException();
}
@Override
public Map<R, V> put(C key, Map<R, V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a view of all mappings that have the given row key. If the
* row key isn't in {@link #rowKeySet()}, an empty immutable map is
* returned.
*
* <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned
* map associates the column key with the corresponding value in the
* table. Changes to the returned map will update the underlying table, and
* vice versa.
*
* @param rowKey key of row to search for in the table
* @return the corresponding map from column keys to values
*/
@Override
public Map<C, V> row(R rowKey) {
checkNotNull(rowKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
return (rowIndex == null) ? ImmutableMap.<C, V>of() : new Row(rowIndex);
}
private class Row extends ArrayMap<C, V> {
final int rowIndex;
Row(int rowIndex) {
super(columnKeyToIndex);
this.rowIndex = rowIndex;
}
@Override
String getKeyRole() {
return "Column";
}
@Override
V getValue(int index) {
return at(rowIndex, index);
}
@Override
V setValue(int index, V newValue) {
return set(rowIndex, index, newValue);
}
}
/**
* Returns an immutable set of the valid row keys, including those that are
* associated with null values only.
*
* @return immutable set of row keys
*/
@Override
public ImmutableSet<R> rowKeySet() {
return rowKeyToIndex.keySet();
}
private transient RowMap rowMap;
@Override
public Map<R, Map<C, V>> rowMap() {
RowMap map = rowMap;
return (map == null) ? rowMap = new RowMap() : map;
}
private class RowMap extends ArrayMap<R, Map<C, V>> {
private RowMap() {
super(rowKeyToIndex);
}
@Override
String getKeyRole() {
return "Row";
}
@Override
Map<C, V> getValue(int index) {
return new Row(index);
}
@Override
Map<C, V> setValue(int index, Map<C, V> newValue) {
throw new UnsupportedOperationException();
}
@Override
public Map<C, V> put(R key, Map<C, V> value) {
throw new UnsupportedOperationException();
}
}
private transient Collection<V> values;
/**
* Returns an unmodifiable collection of all values, which may contain
* duplicates. Changes to the table will update the returned collection.
*
* <p>The returned collection's iterator traverses the values of the first row
* key, the values of the second row key, and so on.
*
* @return collection of values
*/
@Override
public Collection<V> values() {
Collection<V> v = values;
return (v == null) ? values = new Values() : v;
}
private class Values extends AbstractCollection<V> {
@Override public Iterator<V> iterator() {
return new TransformedIterator<Cell<R, C, V>, V>(cellSet().iterator()) {
@Override
V transform(Cell<R, C, V> cell) {
return cell.getValue();
}
};
}
@Override public int size() {
return ArrayTable.this.size();
}
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 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.checkPositionIndex;
import com.google.common.annotations.GwtCompatible;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* This class provides a skeletal implementation of the {@link ListIterator}
* interface across a fixed number of elements that may be retrieved by
* position. It does not support {@link #remove}, {@link #set}, or {@link #add}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractIndexedListIterator<E>
extends UnmodifiableListIterator<E> {
private final int size;
private int position;
/**
* Returns the element with the specified index. This method is called by
* {@link #next()}.
*/
protected abstract E get(int index);
/**
* Constructs an iterator across a sequence of the given size whose initial
* position is 0. That is, the first call to {@link #next()} will return the
* first element (or throw {@link NoSuchElementException} if {@code size} is
* zero).
*
* @throws IllegalArgumentException if {@code size} is negative
*/
protected AbstractIndexedListIterator(int size) {
this(size, 0);
}
/**
* Constructs an iterator across a sequence of the given size with the given
* initial position. That is, the first call to {@link #nextIndex()} will
* return {@code position}, and the first call to {@link #next()} will return
* the element at that index, if available. Calls to {@link #previous()} can
* retrieve the preceding {@code position} elements.
*
* @throws IndexOutOfBoundsException if {@code position} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
protected AbstractIndexedListIterator(int size, int position) {
checkPositionIndex(position, size);
this.size = size;
this.position = position;
}
@Override
public final boolean hasNext() {
return position < size;
}
@Override
public final E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return get(position++);
}
@Override
public final int nextIndex() {
return position;
}
@Override
public final boolean hasPrevious() {
return position > 0;
}
@Override
public final E previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
return get(--position);
}
@Override
public final int previousIndex() {
return position - 1;
}
}
| Java |
/*
* 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 javax.annotation.Nullable;
/**
* A descending wrapper around an {@code ImmutableSortedMultiset}
*
* @author Louis Wasserman
*/
@SuppressWarnings("serial") // uses writeReplace, not default serialization
final class DescendingImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> {
private final transient ImmutableSortedMultiset<E> forward;
DescendingImmutableSortedMultiset(ImmutableSortedMultiset<E> forward) {
this.forward = forward;
}
@Override
public int count(@Nullable Object element) {
return forward.count(element);
}
@Override
public Entry<E> firstEntry() {
return forward.lastEntry();
}
@Override
public Entry<E> lastEntry() {
return forward.firstEntry();
}
@Override
public int size() {
return forward.size();
}
@Override
public ImmutableSortedSet<E> elementSet() {
return forward.elementSet().descendingSet();
}
@Override
ImmutableSet<Entry<E>> createEntrySet() {
final ImmutableSet<Entry<E>> forwardEntrySet = forward.entrySet();
return new EntrySet() {
@Override
public int size() {
return forwardEntrySet.size();
}
@Override
public UnmodifiableIterator<Entry<E>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<E>> createAsList() {
return forwardEntrySet.asList().reverse();
}
};
}
@Override
public ImmutableSortedMultiset<E> descendingMultiset() {
return forward;
}
@Override
public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
return forward.tailMultiset(upperBound, boundType).descendingMultiset();
}
@Override
public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
return forward.headMultiset(lowerBound, boundType).descendingMultiset();
}
@Override
boolean isPartialView() {
return forward.isPartialView();
}
}
| Java |
/*
* 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.base.Supplier;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Implementation of {@code Table} whose iteration ordering across row keys is
* sorted by their natural ordering or by a supplied comparator. Note that
* iterations across the columns keys for a single row key may or may not be
* ordered, depending on the implementation. When rows and columns are both
* sorted, it's easier to use the {@link TreeBasedTable} subclass.
*
* <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link
* #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and
* {@link Map} specified by the {@link Table} interface.
*
* <p>Null keys and values are not supported.
*
* <p>See the {@link StandardTable} superclass for more information about the
* behavior of this class.
*
* @author Jared Levy
*/
@GwtCompatible
class StandardRowSortedTable<R, C, V> extends StandardTable<R, C, V>
implements RowSortedTable<R, C, V> {
/*
* TODO(jlevy): Consider adding headTable, tailTable, and subTable methods,
* which return a Table view with rows keys in a given range. Create a
* RowSortedTable subinterface with the revised methods?
*/
StandardRowSortedTable(SortedMap<R, Map<C, V>> backingMap,
Supplier<? extends Map<C, V>> factory) {
super(backingMap, factory);
}
private SortedMap<R, Map<C, V>> sortedBackingMap() {
return (SortedMap<R, Map<C, V>>) backingMap;
}
private transient SortedSet<R> rowKeySet;
/**
* {@inheritDoc}
*
* <p>This method returns a {@link SortedSet}, instead of the {@code Set}
* specified in the {@link Table} interface.
*/
@Override public SortedSet<R> rowKeySet() {
SortedSet<R> result = rowKeySet;
return (result == null) ? rowKeySet = new RowKeySortedSet() : result;
}
private class RowKeySortedSet extends RowKeySet implements SortedSet<R> {
@Override
public Comparator<? super R> comparator() {
return sortedBackingMap().comparator();
}
@Override
public R first() {
return sortedBackingMap().firstKey();
}
@Override
public R last() {
return sortedBackingMap().lastKey();
}
@Override
public SortedSet<R> headSet(R toElement) {
checkNotNull(toElement);
return new StandardRowSortedTable<R, C, V>(
sortedBackingMap().headMap(toElement), factory).rowKeySet();
}
@Override
public SortedSet<R> subSet(R fromElement, R toElement) {
checkNotNull(fromElement);
checkNotNull(toElement);
return new StandardRowSortedTable<R, C, V>(
sortedBackingMap().subMap(fromElement, toElement), factory)
.rowKeySet();
}
@Override
public SortedSet<R> tailSet(R fromElement) {
checkNotNull(fromElement);
return new StandardRowSortedTable<R, C, V>(
sortedBackingMap().tailMap(fromElement), factory).rowKeySet();
}
}
private transient RowSortedMap rowMap;
/**
* {@inheritDoc}
*
* <p>This method returns a {@link SortedMap}, instead of the {@code Map}
* specified in the {@link Table} interface.
*/
@Override public SortedMap<R, Map<C, V>> rowMap() {
RowSortedMap result = rowMap;
return (result == null) ? rowMap = new RowSortedMap() : result;
}
private class RowSortedMap extends RowMap implements SortedMap<R, Map<C, V>> {
@Override
public Comparator<? super R> comparator() {
return sortedBackingMap().comparator();
}
@Override
public R firstKey() {
return sortedBackingMap().firstKey();
}
@Override
public R lastKey() {
return sortedBackingMap().lastKey();
}
@Override
public SortedMap<R, Map<C, V>> headMap(R toKey) {
checkNotNull(toKey);
return new StandardRowSortedTable<R, C, V>(
sortedBackingMap().headMap(toKey), factory).rowMap();
}
@Override
public SortedMap<R, Map<C, V>> subMap(R fromKey, R toKey) {
checkNotNull(fromKey);
checkNotNull(toKey);
return new StandardRowSortedTable<R, C, V>(
sortedBackingMap().subMap(fromKey, toKey), factory).rowMap();
}
@Override
public SortedMap<R, Map<C, V>> tailMap(R fromKey) {
checkNotNull(fromKey);
return new StandardRowSortedTable<R, C, V>(
sortedBackingMap().tailMap(fromKey), factory).rowMap();
}
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
/**
* An {@code Iterable} whose elements are sorted relative to a {@code Comparator}, typically
* provided at creation time.
*
* @author Louis Wasserman
*/
@GwtCompatible
interface SortedIterable<T> extends Iterable<T> {
/**
* Returns the {@code Comparator} by which the elements of this iterable are ordered, or {@code
* Ordering.natural()} if the elements are ordered by their natural ordering.
*/
Comparator<? super T> comparator();
/**
* Returns an iterator over elements of type {@code T}. The elements are returned in
* nondecreasing order according to the associated {@link #comparator}.
*/
@Override
Iterator<T> iterator();
}
| Java |
/*
* Copyright (C) 2009 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 static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Ticker;
import com.google.common.collect.GenericMapMaker.NullListener;
import com.google.common.collect.MapMaker.RemovalCause;
import com.google.common.collect.MapMaker.RemovalListener;
import com.google.common.collect.MapMaker.RemovalNotification;
import com.google.common.primitives.Ints;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractQueue;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* The concurrent hash map implementation built by {@link MapMaker}.
*
* <p>This implementation is heavily derived from revision 1.96 of <a
* href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>.
*
* @author Bob Lee
* @author Charles Fry
* @author Doug Lea ({@code ConcurrentHashMap})
*/
class MapMakerInternalMap<K, V>
extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable {
/*
* The basic strategy is to subdivide the table among Segments, each of which itself is a
* concurrently readable hash table. The map supports non-blocking reads and concurrent writes
* across different segments.
*
* If a maximum size is specified, a best-effort bounding is performed per segment, using a
* page-replacement algorithm to determine which entries to evict when the capacity has been
* exceeded.
*
* The page replacement algorithm's data structures are kept casually consistent with the map. The
* ordering of writes to a segment is sequentially consistent. An update to the map and recording
* of reads may not be immediately reflected on the algorithm's data structures. These structures
* are guarded by a lock and operations are applied in batches to avoid lock contention. The
* penalty of applying the batches is spread across threads so that the amortized cost is slightly
* higher than performing just the operation without enforcing the capacity constraint.
*
* This implementation uses a per-segment queue to record a memento of the additions, removals,
* and accesses that were performed on the map. The queue is drained on writes and when it exceeds
* its capacity threshold.
*
* The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit
* rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation
* operates per-segment rather than globally for increased implementation simplicity. We expect
* the cache hit rate to be similar to that of a global LRU algorithm.
*/
// Constants
/**
* The maximum capacity, used if a higher value is implicitly specified by either of the
* constructors with arguments. MUST be a power of two <= 1<<30 to ensure that entries are
* indexable using ints.
*/
static final int MAXIMUM_CAPACITY = Ints.MAX_POWER_OF_TWO;
/** The maximum number of segments to allow; used to bound constructor arguments. */
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
/** Number of (unsynchronized) retries in the containsValue method. */
static final int CONTAINS_VALUE_RETRIES = 3;
/**
* Number of cache access operations that can be buffered per segment before the cache's recency
* ordering information is updated. This is used to avoid lock contention by recording a memento
* of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs.
*
* <p>This must be a (2^n)-1 as it is used as a mask.
*/
static final int DRAIN_THRESHOLD = 0x3F;
/**
* Maximum number of entries to be drained in a single cleanup run. This applies independently to
* the cleanup queue and both reference queues.
*/
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
static final long CLEANUP_EXECUTOR_DELAY_SECS = 60;
// Fields
private static final Logger logger = Logger.getLogger(MapMakerInternalMap.class.getName());
/**
* Mask value for indexing into segments. The upper bits of a key's hash code are used to choose
* the segment.
*/
final transient int segmentMask;
/**
* Shift value for indexing within segments. Helps prevent entries that end up in the same segment
* from also ending up in the same bucket.
*/
final transient int segmentShift;
/** The segments, each of which is a specialized hash table. */
final transient Segment<K, V>[] segments;
/** The concurrency level. */
final int concurrencyLevel;
/** Strategy for comparing keys. */
final Equivalence<Object> keyEquivalence;
/** Strategy for comparing values. */
final Equivalence<Object> valueEquivalence;
/** Strategy for referencing keys. */
final Strength keyStrength;
/** Strategy for referencing values. */
final Strength valueStrength;
/** The maximum size of this map. MapMaker.UNSET_INT if there is no maximum. */
final int maximumSize;
/** How long after the last access to an entry the map will retain that entry. */
final long expireAfterAccessNanos;
/** How long after the last write to an entry the map will retain that entry. */
final long expireAfterWriteNanos;
/** Entries waiting to be consumed by the removal listener. */
// TODO(fry): define a new type which creates event objects and automates the clear logic
final Queue<RemovalNotification<K, V>> removalNotificationQueue;
/**
* A listener that is invoked when an entry is removed due to expiration or garbage collection of
* soft/weak entries.
*/
final RemovalListener<K, V> removalListener;
/** Factory used to create new entries. */
final transient EntryFactory entryFactory;
/** Measures time in a testable way. */
final Ticker ticker;
/**
* Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
*/
MapMakerInternalMap(MapMaker builder) {
concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS);
keyStrength = builder.getKeyStrength();
valueStrength = builder.getValueStrength();
keyEquivalence = builder.getKeyEquivalence();
valueEquivalence = valueStrength.defaultEquivalence();
maximumSize = builder.maximumSize;
expireAfterAccessNanos = builder.getExpireAfterAccessNanos();
expireAfterWriteNanos = builder.getExpireAfterWriteNanos();
entryFactory = EntryFactory.getFactory(keyStrength, expires(), evictsBySize());
ticker = builder.getTicker();
removalListener = builder.getRemovalListener();
removalNotificationQueue = (removalListener == NullListener.INSTANCE)
? MapMakerInternalMap.<RemovalNotification<K, V>>discardingQueue()
: new ConcurrentLinkedQueue<RemovalNotification<K, V>>();
int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY);
if (evictsBySize()) {
initialCapacity = Math.min(initialCapacity, maximumSize);
}
// Find power-of-two sizes best matching arguments. Constraints:
// (segmentCount <= maximumSize)
// && (concurrencyLevel > maximumSize || segmentCount > concurrencyLevel)
int segmentShift = 0;
int segmentCount = 1;
while (segmentCount < concurrencyLevel
&& (!evictsBySize() || segmentCount * 2 <= maximumSize)) {
++segmentShift;
segmentCount <<= 1;
}
this.segmentShift = 32 - segmentShift;
segmentMask = segmentCount - 1;
this.segments = newSegmentArray(segmentCount);
int segmentCapacity = initialCapacity / segmentCount;
if (segmentCapacity * segmentCount < initialCapacity) {
++segmentCapacity;
}
int segmentSize = 1;
while (segmentSize < segmentCapacity) {
segmentSize <<= 1;
}
if (evictsBySize()) {
// Ensure sum of segment max sizes = overall max size
int maximumSegmentSize = maximumSize / segmentCount + 1;
int remainder = maximumSize % segmentCount;
for (int i = 0; i < this.segments.length; ++i) {
if (i == remainder) {
maximumSegmentSize--;
}
this.segments[i] =
createSegment(segmentSize, maximumSegmentSize);
}
} else {
for (int i = 0; i < this.segments.length; ++i) {
this.segments[i] =
createSegment(segmentSize, MapMaker.UNSET_INT);
}
}
}
boolean evictsBySize() {
return maximumSize != MapMaker.UNSET_INT;
}
boolean expires() {
return expiresAfterWrite() || expiresAfterAccess();
}
boolean expiresAfterWrite() {
return expireAfterWriteNanos > 0;
}
boolean expiresAfterAccess() {
return expireAfterAccessNanos > 0;
}
boolean usesKeyReferences() {
return keyStrength != Strength.STRONG;
}
boolean usesValueReferences() {
return valueStrength != Strength.STRONG;
}
enum Strength {
/*
* TODO(kevinb): If we strongly reference the value and aren't computing, we needn't wrap the
* value. This could save ~8 bytes per entry.
*/
STRONG {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) {
return new StrongValueReference<K, V>(value);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.equals();
}
},
SOFT {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) {
return new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
},
WEAK {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) {
return new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
};
/**
* Creates a reference for the given value according to this value strength.
*/
abstract <K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value);
/**
* Returns the default equivalence strategy used to compare and hash keys or values referenced
* at this strength. This strategy will be used unless the user explicitly specifies an
* alternate strategy.
*/
abstract Equivalence<Object> defaultEquivalence();
}
/**
* Creates new entries.
*/
enum EntryFactory {
STRONG {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongEntry<K, V>(key, hash, next);
}
},
STRONG_EXPIRABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongExpirableEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
return newEntry;
}
},
STRONG_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongEvictableEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
STRONG_EXPIRABLE_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongExpirableEvictableEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
SOFT {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new SoftEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
},
SOFT_EXPIRABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new SoftExpirableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
return newEntry;
}
},
SOFT_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new SoftEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
SOFT_EXPIRABLE_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new SoftExpirableEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
WEAK {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
},
WEAK_EXPIRABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakExpirableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
return newEntry;
}
},
WEAK_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
WEAK_EXPIRABLE_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakExpirableEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
copyEvictableEntry(original, newEntry);
return newEntry;
}
};
/**
* Masks used to compute indices in the following table.
*/
static final int EXPIRABLE_MASK = 1;
static final int EVICTABLE_MASK = 2;
/**
* Look-up table for factories. First dimension is the reference type. The second dimension is
* the result of OR-ing the feature masks.
*/
static final EntryFactory[][] factories = {
{ STRONG, STRONG_EXPIRABLE, STRONG_EVICTABLE, STRONG_EXPIRABLE_EVICTABLE },
{ SOFT, SOFT_EXPIRABLE, SOFT_EVICTABLE, SOFT_EXPIRABLE_EVICTABLE },
{ WEAK, WEAK_EXPIRABLE, WEAK_EVICTABLE, WEAK_EXPIRABLE_EVICTABLE }
};
static EntryFactory getFactory(Strength keyStrength, boolean expireAfterWrite,
boolean evictsBySize) {
int flags = (expireAfterWrite ? EXPIRABLE_MASK : 0) | (evictsBySize ? EVICTABLE_MASK : 0);
return factories[keyStrength.ordinal()][flags];
}
/**
* Creates a new entry.
*
* @param segment to create the entry for
* @param key of the entry
* @param hash of the key
* @param next entry in the same bucket
*/
abstract <K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next);
/**
* Copies an entry, assigning it a new {@code next} entry.
*
* @param original the entry to copy
* @param newNext entry in the same bucket
*/
@GuardedBy("Segment.this")
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
return newEntry(segment, original.getKey(), original.getHash(), newNext);
}
@GuardedBy("Segment.this")
<K, V> void copyExpirableEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectExpirables, nullifyExpirable.
newEntry.setExpirationTime(original.getExpirationTime());
connectExpirables(original.getPreviousExpirable(), newEntry);
connectExpirables(newEntry, original.getNextExpirable());
nullifyExpirable(original);
}
@GuardedBy("Segment.this")
<K, V> void copyEvictableEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectEvictables, nullifyEvictable.
connectEvictables(original.getPreviousEvictable(), newEntry);
connectEvictables(newEntry, original.getNextEvictable());
nullifyEvictable(original);
}
}
/**
* A reference to a value.
*/
interface ValueReference<K, V> {
/**
* Gets the value. Does not block or throw exceptions.
*/
V get();
/**
* Waits for a value that may still be computing. Unlike get(), this method can block (in the
* case of FutureValueReference).
*
* @throws ExecutionException if the computing thread throws an exception
*/
V waitForValue() throws ExecutionException;
/**
* Returns the entry associated with this value reference, or {@code null} if this value
* reference is independent of any entry.
*/
ReferenceEntry<K, V> getEntry();
/**
* Creates a copy of this reference for the given entry.
*
* <p>{@code value} may be null only for a loading reference.
*/
ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry);
/**
* Clears this reference object.
*
* @param newValue the new value reference which will replace this one; this is only used during
* computation to immediately notify blocked threads of the new value
*/
void clear(@Nullable ValueReference<K, V> newValue);
/**
* Returns {@code true} if the value type is a computing reference (regardless of whether or not
* computation has completed). This is necessary to distiguish between partially-collected
* entries and computing entries, which need to be cleaned up differently.
*/
boolean isComputingReference();
}
/**
* Placeholder. Indicates that the value hasn't been set yet.
*/
static final ValueReference<Object, Object> UNSET = new ValueReference<Object, Object>() {
@Override
public Object get() {
return null;
}
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
}
@Override
public ValueReference<Object, Object> copyFor(ReferenceQueue<Object> queue,
@Nullable Object value, ReferenceEntry<Object, Object> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public Object waitForValue() {
return null;
}
@Override
public void clear(ValueReference<Object, Object> newValue) {}
};
/**
* Singleton placeholder that indicates a value is being computed.
*/
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ValueReference<K, V> unset() {
return (ValueReference<K, V>) UNSET;
}
/**
* An entry in a reference map.
*
* Entries in the map can be in the following states:
*
* Valid:
* - Live: valid key/value are set
* - Computing: computation is pending
*
* Invalid:
* - Expired: time expired (key/value may still be set)
* - Collected: key/value was partially collected, but not yet cleaned up
*/
interface ReferenceEntry<K, V> {
/**
* Gets the value reference from this entry.
*/
ValueReference<K, V> getValueReference();
/**
* Sets the value reference for this entry.
*/
void setValueReference(ValueReference<K, V> valueReference);
/**
* Gets the next entry in the chain.
*/
ReferenceEntry<K, V> getNext();
/**
* Gets the entry's hash.
*/
int getHash();
/**
* Gets the key for this entry.
*/
K getKey();
/*
* Used by entries that are expirable. Expirable entries are maintained in a doubly-linked list.
* New entries are added at the tail of the list at write time; stale entries are expired from
* the head of the list.
*/
/**
* Gets the entry expiration time in ns.
*/
long getExpirationTime();
/**
* Sets the entry expiration time in ns.
*/
void setExpirationTime(long time);
/**
* Gets the next entry in the recency list.
*/
ReferenceEntry<K, V> getNextExpirable();
/**
* Sets the next entry in the recency list.
*/
void setNextExpirable(ReferenceEntry<K, V> next);
/**
* Gets the previous entry in the recency list.
*/
ReferenceEntry<K, V> getPreviousExpirable();
/**
* Sets the previous entry in the recency list.
*/
void setPreviousExpirable(ReferenceEntry<K, V> previous);
/*
* Implemented by entries that are evictable. Evictable entries are maintained in a
* doubly-linked list. New entries are added at the tail of the list at write time and stale
* entries are expired from the head of the list.
*/
/**
* Gets the next entry in the recency list.
*/
ReferenceEntry<K, V> getNextEvictable();
/**
* Sets the next entry in the recency list.
*/
void setNextEvictable(ReferenceEntry<K, V> next);
/**
* Gets the previous entry in the recency list.
*/
ReferenceEntry<K, V> getPreviousEvictable();
/**
* Sets the previous entry in the recency list.
*/
void setPreviousEvictable(ReferenceEntry<K, V> previous);
}
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
}
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
}
@Override
public int getHash() {
return 0;
}
@Override
public Object getKey() {
return null;
}
@Override
public long getExpirationTime() {
return 0;
}
@Override
public void setExpirationTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextExpirable() {
return this;
}
@Override
public void setNextExpirable(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousExpirable() {
return this;
}
@Override
public void setPreviousExpirable(ReferenceEntry<Object, Object> previous) {}
@Override
public ReferenceEntry<Object, Object> getNextEvictable() {
return this;
}
@Override
public void setNextEvictable(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousEvictable() {
return this;
}
@Override
public void setPreviousEvictable(ReferenceEntry<Object, Object> previous) {}
}
abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> {
@Override
public ValueReference<K, V> getValueReference() {
throw new UnsupportedOperationException();
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNext() {
throw new UnsupportedOperationException();
}
@Override
public int getHash() {
throw new UnsupportedOperationException();
}
@Override
public K getKey() {
throw new UnsupportedOperationException();
}
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ReferenceEntry<K, V> nullEntry() {
return (ReferenceEntry<K, V>) NullEntry.INSTANCE;
}
static final Queue<? extends Object> DISCARDING_QUEUE = new AbstractQueue<Object>() {
@Override
public boolean offer(Object o) {
return true;
}
@Override
public Object peek() {
return null;
}
@Override
public Object poll() {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Object> iterator() {
return Iterators.emptyIterator();
}
};
/**
* Queue that discards all elements.
*/
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <E> Queue<E> discardingQueue() {
return (Queue) DISCARDING_QUEUE;
}
/*
* Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins!
* To maintain this code, make a change for the strong reference type. Then, cut and paste, and
* replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that
* strong entries store the key reference directly while soft and weak entries delegate to their
* respective superclasses.
*/
/**
* Used for strongly-referenced keys.
*/
static class StrongEntry<K, V> implements ReferenceEntry<K, V> {
final K key;
StrongEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
this.key = key;
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return this.key;
}
// null expiration
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null eviction
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
ValueReference<K, V> previous = this.valueReference;
this.valueReference = valueReference;
previous.clear(valueReference);
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class StrongExpirableEntry<K, V> extends StrongEntry<K, V>
implements ReferenceEntry<K, V> {
StrongExpirableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
}
static final class StrongEvictableEntry<K, V>
extends StrongEntry<K, V> implements ReferenceEntry<K, V> {
StrongEvictableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
static final class StrongExpirableEvictableEntry<K, V>
extends StrongEntry<K, V> implements ReferenceEntry<K, V> {
StrongExpirableEvictableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
/**
* Used for softly-referenced keys.
*/
static class SoftEntry<K, V> extends SoftReference<K> implements ReferenceEntry<K, V> {
SoftEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
// null expiration
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null eviction
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
ValueReference<K, V> previous = this.valueReference;
this.valueReference = valueReference;
previous.clear(valueReference);
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class SoftExpirableEntry<K, V>
extends SoftEntry<K, V> implements ReferenceEntry<K, V> {
SoftExpirableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
}
static final class SoftEvictableEntry<K, V>
extends SoftEntry<K, V> implements ReferenceEntry<K, V> {
SoftEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
static final class SoftExpirableEvictableEntry<K, V>
extends SoftEntry<K, V> implements ReferenceEntry<K, V> {
SoftExpirableEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
/**
* Used for weakly-referenced keys.
*/
static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> {
WeakEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
// null expiration
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null eviction
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
ValueReference<K, V> previous = this.valueReference;
this.valueReference = valueReference;
previous.clear(valueReference);
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class WeakExpirableEntry<K, V>
extends WeakEntry<K, V> implements ReferenceEntry<K, V> {
WeakExpirableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
}
static final class WeakEvictableEntry<K, V>
extends WeakEntry<K, V> implements ReferenceEntry<K, V> {
WeakEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
static final class WeakExpirableEvictableEntry<K, V>
extends WeakEntry<K, V> implements ReferenceEntry<K, V> {
WeakExpirableEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
/**
* References a weak value.
*/
static final class WeakValueReference<K, V>
extends WeakReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void clear(ValueReference<K, V> newValue) {
clear();
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeakValueReference<K, V>(queue, value, entry);
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
}
/**
* References a soft value.
*/
static final class SoftValueReference<K, V>
extends SoftReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void clear(ValueReference<K, V> newValue) {
clear();
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new SoftValueReference<K, V>(queue, value, entry);
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
}
/**
* References a strong value.
*/
static final class StrongValueReference<K, V> implements ValueReference<K, V> {
final V referent;
StrongValueReference(V referent) {
this.referent = referent;
}
@Override
public V get() {
return referent;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void clear(ValueReference<K, V> newValue) {}
}
/**
* Applies a supplemental hash function to a given hash code, which defends against poor quality
* hash functions. This is critical when the concurrent hash map uses power-of-two length hash
* tables, that otherwise encounter collisions for hash codes that do not differ in lower or
* upper bits.
*
* @param h hash code
*/
static int rehash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
// TODO(kevinb): use Hashing/move this to Hashing?
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#newEntry} directly.
*/
@GuardedBy("Segment.this")
@VisibleForTesting
ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return segmentFor(hash).newEntry(key, hash, next);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly.
*/
@GuardedBy("Segment.this")
@VisibleForTesting
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
int hash = original.getHash();
return segmentFor(hash).copyEntry(original, newNext);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#setValue} instead.
*/
@GuardedBy("Segment.this")
@VisibleForTesting
ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value) {
int hash = entry.getHash();
return valueStrength.referenceValue(segmentFor(hash), entry, value);
}
int hash(Object key) {
int h = keyEquivalence.hash(key);
return rehash(h);
}
void reclaimValue(ValueReference<K, V> valueReference) {
ReferenceEntry<K, V> entry = valueReference.getEntry();
int hash = entry.getHash();
segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference);
}
void reclaimKey(ReferenceEntry<K, V> entry) {
int hash = entry.getHash();
segmentFor(hash).reclaimKey(entry, hash);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#getLiveValue}
* instead.
*/
@VisibleForTesting
boolean isLive(ReferenceEntry<K, V> entry) {
return segmentFor(entry.getHash()).getLiveValue(entry) != null;
}
/**
* Returns the segment that should be used for a key with the given hash.
*
* @param hash the hash code for the key
* @return the segment
*/
Segment<K, V> segmentFor(int hash) {
// TODO(fry): Lazily create segments?
return segments[(hash >>> segmentShift) & segmentMask];
}
Segment<K, V> createSegment(int initialCapacity, int maxSegmentSize) {
return new Segment<K, V>(this, initialCapacity, maxSegmentSize);
}
/**
* Gets the value from an entry. Returns {@code null} if the entry is invalid,
* partially-collected, computing, or expired. Unlike {@link Segment#getLiveValue} this method
* does not attempt to clean up stale entries.
*/
V getLiveValue(ReferenceEntry<K, V> entry) {
if (entry.getKey() == null) {
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
return null;
}
if (expires() && isExpired(entry)) {
return null;
}
return value;
}
// expiration
/**
* Returns {@code true} if the entry has expired.
*/
boolean isExpired(ReferenceEntry<K, V> entry) {
return isExpired(entry, ticker.read());
}
/**
* Returns {@code true} if the entry has expired.
*/
boolean isExpired(ReferenceEntry<K, V> entry, long now) {
// if the expiration time had overflowed, this "undoes" the overflow
return now - entry.getExpirationTime() > 0;
}
@GuardedBy("Segment.this")
static <K, V> void connectExpirables(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextExpirable(next);
next.setPreviousExpirable(previous);
}
@GuardedBy("Segment.this")
static <K, V> void nullifyExpirable(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextExpirable(nullEntry);
nulled.setPreviousExpirable(nullEntry);
}
// eviction
/**
* Notifies listeners that an entry has been automatically removed due to expiration, eviction,
* or eligibility for garbage collection. This should be called every time expireEntries or
* evictEntry is called (once the lock is released).
*/
void processPendingNotifications() {
RemovalNotification<K, V> notification;
while ((notification = removalNotificationQueue.poll()) != null) {
try {
removalListener.onRemoval(notification);
} catch (Exception e) {
logger.log(Level.WARNING, "Exception thrown by removal listener", e);
}
}
}
/** Links the evitables together. */
@GuardedBy("Segment.this")
static <K, V> void connectEvictables(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextEvictable(next);
next.setPreviousEvictable(previous);
}
@GuardedBy("Segment.this")
static <K, V> void nullifyEvictable(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextEvictable(nullEntry);
nulled.setPreviousEvictable(nullEntry);
}
@SuppressWarnings("unchecked")
final Segment<K, V>[] newSegmentArray(int ssize) {
return new Segment[ssize];
}
// Inner Classes
/**
* Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock
* opportunistically, just to simplify some locking and avoid separate construction.
*/
@SuppressWarnings("serial") // This class is never serialized.
static class Segment<K, V> extends ReentrantLock {
/*
* TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class.
* It will require more memory but will reduce indirection.
*/
/*
* Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can
* be read without locking. Next fields of nodes are immutable (final). All list additions are
* performed at the front of each bin. This makes it easy to check changes, and also fast to
* traverse. When nodes would otherwise be changed, new nodes are created to replace them. This
* works well for hash tables since the bin lists tend to be short. (The average length is less
* than two.)
*
* Read operations can thus proceed without locking, but rely on selected uses of volatiles to
* ensure that completed write operations performed by other threads are noticed. For most
* purposes, the "count" field, tracking the number of elements, serves as that volatile
* variable ensuring visibility. This is convenient because this field needs to be read in many
* read operations anyway:
*
* - All (unsynchronized) read operations must first read the "count" field, and should not
* look at table entries if it is 0.
*
* - All (synchronized) write operations should write to the "count" field after structurally
* changing any bin. The operations must not take any action that could even momentarily
* cause a concurrent read operation to see inconsistent data. This is made easier by the
* nature of the read operations in Map. For example, no operation can reveal that the table
* has grown but the threshold has not yet been updated, so there are no atomicity requirements
* for this with respect to reads.
*
* As a guide, all critical volatile reads and writes to the count field are marked in code
* comments.
*/
final MapMakerInternalMap<K, V> map;
/**
* The number of live elements in this segment's region. This does not include unset elements
* which are awaiting cleanup.
*/
volatile int count;
/**
* Number of updates that alter the size of the table. This is used during bulk-read methods to
* make sure they see a consistent snapshot: If modCounts change during a traversal of segments
* computing size or checking containsValue, then we might have an inconsistent view of state
* so (usually) must retry.
*/
int modCount;
/**
* The table is expanded when its size exceeds this threshold. (The value of this field is
* always {@code (int)(capacity * 0.75)}.)
*/
int threshold;
/**
* The per-segment table.
*/
volatile AtomicReferenceArray<ReferenceEntry<K, V>> table;
/**
* The maximum size of this map. MapMaker.UNSET_INT if there is no maximum.
*/
final int maxSegmentSize;
/**
* The key reference queue contains entries whose keys have been garbage collected, and which
* need to be cleaned up internally.
*/
final ReferenceQueue<K> keyReferenceQueue;
/**
* The value reference queue contains value references whose values have been garbage collected,
* and which need to be cleaned up internally.
*/
final ReferenceQueue<V> valueReferenceQueue;
/**
* The recency queue is used to record which entries were accessed for updating the eviction
* list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is
* crossed or a write occurs on the segment.
*/
final Queue<ReferenceEntry<K, V>> recencyQueue;
/**
* A counter of the number of reads since the last write, used to drain queues on a small
* fraction of read operations.
*/
final AtomicInteger readCount = new AtomicInteger();
/**
* A queue of elements currently in the map, ordered by access time. Elements are added to the
* tail of the queue on access/write.
*/
@GuardedBy("Segment.this")
final Queue<ReferenceEntry<K, V>> evictionQueue;
/**
* A queue of elements currently in the map, ordered by expiration time (either access or write
* time). Elements are added to the tail of the queue on access/write.
*/
@GuardedBy("Segment.this")
final Queue<ReferenceEntry<K, V>> expirationQueue;
Segment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) {
this.map = map;
this.maxSegmentSize = maxSegmentSize;
initTable(newEntryArray(initialCapacity));
keyReferenceQueue = map.usesKeyReferences()
? new ReferenceQueue<K>() : null;
valueReferenceQueue = map.usesValueReferences()
? new ReferenceQueue<V>() : null;
recencyQueue = (map.evictsBySize() || map.expiresAfterAccess())
? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
: MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
evictionQueue = map.evictsBySize()
? new EvictionQueue<K, V>()
: MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
expirationQueue = map.expires()
? new ExpirationQueue<K, V>()
: MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
return new AtomicReferenceArray<ReferenceEntry<K, V>>(size);
}
void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
if (this.threshold == maxSegmentSize) {
// prevent spurious expansion before eviction
this.threshold++;
}
this.table = newTable;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return map.entryFactory.newEntry(this, key, hash, next);
}
/**
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
@GuardedBy("Segment.this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
if (original.getKey() == null) {
// key collected
return null;
}
ValueReference<K, V> valueReference = original.getValueReference();
V value = valueReference.get();
if ((value == null) && !valueReference.isComputingReference()) {
// value collected
return null;
}
ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
/**
* Sets a new value of an entry. Adds newly created entries at the end of the expiration queue.
*/
@GuardedBy("Segment.this")
void setValue(ReferenceEntry<K, V> entry, V value) {
ValueReference<K, V> valueReference = map.valueStrength.referenceValue(this, entry, value);
entry.setValueReference(valueReference);
recordWrite(entry);
}
// reference queues, for garbage collection cleanup
/**
* Cleanup collected entries when the lock is available.
*/
void tryDrainReferenceQueues() {
if (tryLock()) {
try {
drainReferenceQueues();
} finally {
unlock();
}
}
}
/**
* Drain the key and value reference queues, cleaning up internal entries containing garbage
* collected keys or values.
*/
@GuardedBy("Segment.this")
void drainReferenceQueues() {
if (map.usesKeyReferences()) {
drainKeyReferenceQueue();
}
if (map.usesValueReferences()) {
drainValueReferenceQueue();
}
}
@GuardedBy("Segment.this")
void drainKeyReferenceQueue() {
Reference<? extends K> ref;
int i = 0;
while ((ref = keyReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref;
map.reclaimKey(entry);
if (++i == DRAIN_MAX) {
break;
}
}
}
@GuardedBy("Segment.this")
void drainValueReferenceQueue() {
Reference<? extends V> ref;
int i = 0;
while ((ref = valueReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ValueReference<K, V> valueReference = (ValueReference<K, V>) ref;
map.reclaimValue(valueReference);
if (++i == DRAIN_MAX) {
break;
}
}
}
/**
* Clears all entries from the key and value reference queues.
*/
void clearReferenceQueues() {
if (map.usesKeyReferences()) {
clearKeyReferenceQueue();
}
if (map.usesValueReferences()) {
clearValueReferenceQueue();
}
}
void clearKeyReferenceQueue() {
while (keyReferenceQueue.poll() != null) {}
}
void clearValueReferenceQueue() {
while (valueReferenceQueue.poll() != null) {}
}
// recency queue, shared by expiration and eviction
/**
* Records the relative order in which this read was performed by adding {@code entry} to the
* recency queue. At write-time, or when the queue is full past the threshold, the queue will
* be drained and the entries therein processed.
*
* <p>Note: locked reads should use {@link #recordLockedRead}.
*/
void recordRead(ReferenceEntry<K, V> entry) {
if (map.expiresAfterAccess()) {
recordExpirationTime(entry, map.expireAfterAccessNanos);
}
recencyQueue.add(entry);
}
/**
* Updates the eviction metadata that {@code entry} was just read. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*
* <p>Note: this method should only be called under lock, as it directly manipulates the
* eviction queues. Unlocked reads should use {@link #recordRead}.
*/
@GuardedBy("Segment.this")
void recordLockedRead(ReferenceEntry<K, V> entry) {
evictionQueue.add(entry);
if (map.expiresAfterAccess()) {
recordExpirationTime(entry, map.expireAfterAccessNanos);
expirationQueue.add(entry);
}
}
/**
* Updates eviction metadata that {@code entry} was just written. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*/
@GuardedBy("Segment.this")
void recordWrite(ReferenceEntry<K, V> entry) {
// we are already under lock, so drain the recency queue immediately
drainRecencyQueue();
evictionQueue.add(entry);
if (map.expires()) {
// currently MapMaker ensures that expireAfterWrite and
// expireAfterAccess are mutually exclusive
long expiration = map.expiresAfterAccess()
? map.expireAfterAccessNanos
: map.expireAfterWriteNanos;
recordExpirationTime(entry, expiration);
expirationQueue.add(entry);
}
}
/**
* Drains the recency queue, updating eviction metadata that the entries therein were read in
* the specified relative order. This currently amounts to adding them to relevant eviction
* lists (accounting for the fact that they could have been removed from the map since being
* added to the recency queue).
*/
@GuardedBy("Segment.this")
void drainRecencyQueue() {
ReferenceEntry<K, V> e;
while ((e = recencyQueue.poll()) != null) {
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
// all of the segment's entries.
if (evictionQueue.contains(e)) {
evictionQueue.add(e);
}
if (map.expiresAfterAccess() && expirationQueue.contains(e)) {
expirationQueue.add(e);
}
}
}
// expiration
void recordExpirationTime(ReferenceEntry<K, V> entry, long expirationNanos) {
// might overflow, but that's okay (see isExpired())
entry.setExpirationTime(map.ticker.read() + expirationNanos);
}
/**
* Cleanup expired entries when the lock is available.
*/
void tryExpireEntries() {
if (tryLock()) {
try {
expireEntries();
} finally {
unlock();
// don't call postWriteCleanup as we're in a read
}
}
}
@GuardedBy("Segment.this")
void expireEntries() {
drainRecencyQueue();
if (expirationQueue.isEmpty()) {
// There's no point in calling nanoTime() if we have no entries to
// expire.
return;
}
long now = map.ticker.read();
ReferenceEntry<K, V> e;
while ((e = expirationQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
}
// eviction
void enqueueNotification(ReferenceEntry<K, V> entry, RemovalCause cause) {
enqueueNotification(entry.getKey(), entry.getHash(), entry.getValueReference().get(), cause);
}
void enqueueNotification(@Nullable K key, int hash, @Nullable V value, RemovalCause cause) {
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
RemovalNotification<K, V> notification = new RemovalNotification<K, V>(key, value, cause);
map.removalNotificationQueue.offer(notification);
}
}
/**
* Performs eviction if the segment is full. This should only be called prior to adding a new
* entry and increasing {@code count}.
*
* @return {@code true} if eviction occurred
*/
@GuardedBy("Segment.this")
boolean evictEntries() {
if (map.evictsBySize() && count >= maxSegmentSize) {
drainRecencyQueue();
ReferenceEntry<K, V> e = evictionQueue.remove();
if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
return true;
}
return false;
}
/**
* Returns first entry of bin for given hash.
*/
ReferenceEntry<K, V> getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
return table.get(hash & (table.length() - 1));
}
// Specialized implementations of map methods
ReferenceEntry<K, V> getEntry(Object key, int hash) {
if (count != 0) { // read-volatile
for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) {
if (e.getHash() != hash) {
continue;
}
K entryKey = e.getKey();
if (entryKey == null) {
tryDrainReferenceQueues();
continue;
}
if (map.keyEquivalence.equivalent(key, entryKey)) {
return e;
}
}
}
return null;
}
ReferenceEntry<K, V> getLiveEntry(Object key, int hash) {
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e == null) {
return null;
} else if (map.expires() && map.isExpired(e)) {
tryExpireEntries();
return null;
}
return e;
}
V get(Object key, int hash) {
try {
ReferenceEntry<K, V> e = getLiveEntry(key, hash);
if (e == null) {
return null;
}
V value = e.getValueReference().get();
if (value != null) {
recordRead(e);
} else {
tryDrainReferenceQueues();
}
return value;
} finally {
postReadCleanup();
}
}
boolean containsKey(Object key, int hash) {
try {
if (count != 0) { // read-volatile
ReferenceEntry<K, V> e = getLiveEntry(key, hash);
if (e == null) {
return false;
}
return e.getValueReference().get() != null;
}
return false;
} finally {
postReadCleanup();
}
}
/**
* This method is a convenience for testing. Code should call {@link
* MapMakerInternalMap#containsValue} directly.
*/
@VisibleForTesting
boolean containsValue(Object value) {
try {
if (count != 0) { // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int length = table.length();
for (int i = 0; i < length; ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
V entryValue = getLiveValue(e);
if (entryValue == null) {
continue;
}
if (map.valueEquivalence.equivalent(value, entryValue)) {
return true;
}
}
}
}
return false;
} finally {
postReadCleanup();
}
}
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
preWriteCleanup();
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
++modCount;
setValue(e, value);
if (!valueReference.isComputingReference()) {
enqueueNotification(key, hash, entryValue, RemovalCause.COLLECTED);
newCount = this.count; // count remains unchanged
} else if (evictEntries()) { // evictEntries after setting new value
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
return null;
} else if (onlyIfAbsent) {
// Mimic
// "if (!map.containsKey(key)) ...
// else return map.get(key);
recordLockedRead(e);
return entryValue;
} else {
// clobber existing entry, count remains unchanged
++modCount;
enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED);
setValue(e, value);
return entryValue;
}
}
}
// Create a new entry.
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, value);
table.set(index, newEntry);
if (evictEntries()) { // evictEntries after setting new value
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
return null;
} finally {
unlock();
postWriteCleanup();
}
}
/**
* Expands the table if possible.
*/
@GuardedBy("Segment.this")
void expand() {
AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table;
int oldCapacity = oldTable.length();
if (oldCapacity >= MAXIMUM_CAPACITY) {
return;
}
/*
* Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move with a power of two offset.
* We eliminate unnecessary node creation by catching cases where old nodes can be reused
* because their next fields won't change. Statistically, at the default threshold, only
* about one-sixth of them need cloning when a table doubles. The nodes they replace will be
* garbage collectable as soon as they are no longer referenced by any reader thread that may
* be in the midst of traversing table right now.
*/
int newCount = count;
AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1);
threshold = newTable.length() * 3 / 4;
int newMask = newTable.length() - 1;
for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
ReferenceEntry<K, V> head = oldTable.get(oldIndex);
if (head != null) {
ReferenceEntry<K, V> next = head.getNext();
int headIndex = head.getHash() & newMask;
// Single node on list
if (next == null) {
newTable.set(headIndex, head);
} else {
// Reuse the consecutive sequence of nodes with the same target
// index from the end of the list. tail points to the first
// entry in the reusable list.
ReferenceEntry<K, V> tail = head;
int tailIndex = headIndex;
for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
if (newIndex != tailIndex) {
// The index changed. We'll need to copy the previous entry.
tailIndex = newIndex;
tail = e;
}
}
newTable.set(tailIndex, tail);
// Clone nodes leading up to the tail.
for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
ReferenceEntry<K, V> newNext = newTable.get(newIndex);
ReferenceEntry<K, V> newFirst = copyEntry(e, newNext);
if (newFirst != null) {
newTable.set(newIndex, newFirst);
} else {
removeCollectedEntry(e);
newCount--;
}
}
}
}
}
table = newTable;
this.count = newCount;
}
boolean replace(K key, int hash, V oldValue, V newValue) {
lock();
try {
preWriteCleanup();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// If the value disappeared, this entry is partially collected,
// and we should pretend like it doesn't exist.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (isCollected(valueReference)) {
int newCount = this.count - 1;
++modCount;
enqueueNotification(entryKey, hash, entryValue, RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return false;
}
if (map.valueEquivalence.equivalent(oldValue, entryValue)) {
++modCount;
enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED);
setValue(e, newValue);
return true;
} else {
// Mimic
// "if (map.containsKey(key) && map.get(key).equals(oldValue))..."
recordLockedRead(e);
return false;
}
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
V replace(K key, int hash, V newValue) {
lock();
try {
preWriteCleanup();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// If the value disappeared, this entry is partially collected,
// and we should pretend like it doesn't exist.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (isCollected(valueReference)) {
int newCount = this.count - 1;
++modCount;
enqueueNotification(entryKey, hash, entryValue, RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return null;
}
++modCount;
enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED);
setValue(e, newValue);
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
V remove(Object key, int hash) {
lock();
try {
preWriteCleanup();
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (entryValue != null) {
cause = RemovalCause.EXPLICIT;
} else if (isCollected(valueReference)) {
cause = RemovalCause.COLLECTED;
} else {
return null;
}
++modCount;
enqueueNotification(entryKey, hash, entryValue, cause);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
boolean remove(Object key, int hash, Object value) {
lock();
try {
preWriteCleanup();
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (map.valueEquivalence.equivalent(value, entryValue)) {
cause = RemovalCause.EXPLICIT;
} else if (isCollected(valueReference)) {
cause = RemovalCause.COLLECTED;
} else {
return false;
}
++modCount;
enqueueNotification(entryKey, hash, entryValue, cause);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return (cause == RemovalCause.EXPLICIT);
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
void clear() {
if (count != 0) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
for (int i = 0; i < table.length(); ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
// Computing references aren't actually in the map yet.
if (!e.getValueReference().isComputingReference()) {
enqueueNotification(e, RemovalCause.EXPLICIT);
}
}
}
}
for (int i = 0; i < table.length(); ++i) {
table.set(i, null);
}
clearReferenceQueues();
evictionQueue.clear();
expirationQueue.clear();
readCount.set(0);
++modCount;
count = 0; // write-volatile
} finally {
unlock();
postWriteCleanup();
}
}
}
/**
* Removes an entry from within a table. All entries following the removed node can stay, but
* all preceding ones need to be cloned.
*
* <p>This method does not decrement count for the removed entry, but does decrement count for
* all partially collected entries which are skipped. As such callers which are modifying count
* must re-read it after calling removeFromChain.
*
* @param first the first entry of the table
* @param entry the entry being removed from the table
* @return the new first entry for the table
*/
@GuardedBy("Segment.this")
ReferenceEntry<K, V> removeFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) {
evictionQueue.remove(entry);
expirationQueue.remove(entry);
int newCount = count;
ReferenceEntry<K, V> newFirst = entry.getNext();
for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) {
ReferenceEntry<K, V> next = copyEntry(e, newFirst);
if (next != null) {
newFirst = next;
} else {
removeCollectedEntry(e);
newCount--;
}
}
this.count = newCount;
return newFirst;
}
void removeCollectedEntry(ReferenceEntry<K, V> entry) {
enqueueNotification(entry, RemovalCause.COLLECTED);
evictionQueue.remove(entry);
expirationQueue.remove(entry);
}
/**
* Removes an entry whose key has been garbage collected.
*/
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
int newCount = count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
enqueueNotification(
e.getKey(), hash, e.getValueReference().get(), RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
/**
* Removes an entry whose value has been garbage collected.
*/
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
++modCount;
enqueueNotification(key, hash, valueReference.get(), RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
return false;
}
}
return false;
} finally {
unlock();
if (!isHeldByCurrentThread()) { // don't cleanup inside of put
postWriteCleanup();
}
}
}
/**
* Clears a value that has not yet been set, and thus does not require count to be modified.
*/
boolean clearValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
table.set(index, newFirst);
return true;
}
return false;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@GuardedBy("Segment.this")
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
enqueueNotification(e.getKey(), hash, e.getValueReference().get(), cause);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
}
/**
* Returns {@code true} if the value has been partially collected, meaning that the value is
* null and it is not computing.
*/
boolean isCollected(ValueReference<K, V> valueReference) {
if (valueReference.isComputingReference()) {
return false;
}
return (valueReference.get() == null);
}
/**
* Gets the value from an entry. Returns {@code null} if the entry is invalid,
* partially-collected, computing, or expired.
*/
V getLiveValue(ReferenceEntry<K, V> entry) {
if (entry.getKey() == null) {
tryDrainReferenceQueues();
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
tryDrainReferenceQueues();
return null;
}
if (map.expires() && map.isExpired(entry)) {
tryExpireEntries();
return null;
}
return value;
}
/**
* Performs routine cleanup following a read. Normally cleanup happens during writes, or from
* the cleanupExecutor. If cleanup is not observed after a sufficient number of reads, try
* cleaning up from the read thread.
*/
void postReadCleanup() {
if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) {
runCleanup();
}
}
/**
* Performs routine cleanup prior to executing a write. This should be called every time a
* write thread acquires the segment lock, immediately after acquiring the lock.
*
* <p>Post-condition: expireEntries has been run.
*/
@GuardedBy("Segment.this")
void preWriteCleanup() {
runLockedCleanup();
}
/**
* Performs routine cleanup following a write.
*/
void postWriteCleanup() {
runUnlockedCleanup();
}
void runCleanup() {
runLockedCleanup();
runUnlockedCleanup();
}
void runLockedCleanup() {
if (tryLock()) {
try {
drainReferenceQueues();
expireEntries(); // calls drainRecencyQueue
readCount.set(0);
} finally {
unlock();
}
}
}
void runUnlockedCleanup() {
// locked cleanup may generate notifications we can send unlocked
if (!isHeldByCurrentThread()) {
map.processPendingNotifications();
}
}
}
// Queues
/**
* A custom queue for managing eviction order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in
* the map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle
* of the queue as part of copyEvictableEntry, and (2) the contains method is highly optimized
* for the current model.
*/
static final class EvictionQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() {
ReferenceEntry<K, V> nextEvictable = this;
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
ReferenceEntry<K, V> previousEvictable = this;
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectEvictables(entry.getPreviousEvictable(), entry.getNextEvictable());
// add to tail
connectEvictables(head.getPreviousEvictable(), entry);
connectEvictables(entry, head);
return true;
}
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextEvictable();
return (next == head) ? null : next;
}
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextEvictable();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
ReferenceEntry<K, V> previous = e.getPreviousEvictable();
ReferenceEntry<K, V> next = e.getNextEvictable();
connectEvictables(previous, next);
nullifyEvictable(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
return e.getNextEvictable() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextEvictable() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextEvictable(); e != head; e = e.getNextEvictable()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextEvictable();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextEvictable();
nullifyEvictable(e);
e = next;
}
head.setNextEvictable(head);
head.setPreviousEvictable(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextEvictable();
return (next == head) ? null : next;
}
};
}
}
/**
* A custom queue for managing expiration order. Note that this is tightly integrated with
* {@code ReferenceEntry}, upon which it reliese to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in
* the map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle
* of the queue as part of copyEvictableEntry, and (2) the contains method is highly optimized
* for the current model.
*/
static final class ExpirationQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() {
@Override
public long getExpirationTime() {
return Long.MAX_VALUE;
}
@Override
public void setExpirationTime(long time) {}
ReferenceEntry<K, V> nextExpirable = this;
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
ReferenceEntry<K, V> previousExpirable = this;
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectExpirables(entry.getPreviousExpirable(), entry.getNextExpirable());
// add to tail
connectExpirables(head.getPreviousExpirable(), entry);
connectExpirables(entry, head);
return true;
}
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextExpirable();
return (next == head) ? null : next;
}
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextExpirable();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
ReferenceEntry<K, V> previous = e.getPreviousExpirable();
ReferenceEntry<K, V> next = e.getNextExpirable();
connectExpirables(previous, next);
nullifyExpirable(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
return e.getNextExpirable() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextExpirable() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextExpirable(); e != head; e = e.getNextExpirable()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextExpirable();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextExpirable();
nullifyExpirable(e);
e = next;
}
head.setNextExpirable(head);
head.setPreviousExpirable(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextExpirable();
return (next == head) ? null : next;
}
};
}
}
static final class CleanupMapTask implements Runnable {
final WeakReference<MapMakerInternalMap<?, ?>> mapReference;
public CleanupMapTask(MapMakerInternalMap<?, ?> map) {
this.mapReference = new WeakReference<MapMakerInternalMap<?, ?>>(map);
}
@Override
public void run() {
MapMakerInternalMap<?, ?> map = mapReference.get();
if (map == null) {
throw new CancellationException();
}
for (Segment<?, ?> segment : map.segments) {
segment.runCleanup();
}
}
}
// ConcurrentMap methods
@Override
public boolean isEmpty() {
/*
* Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and
* removed in one segment while checking another, in which case the table was never actually
* empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment
* modifications before recheck.) Method containsValue() uses similar constructions for
* stability checks.
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0) {
return false;
}
sum += segments[i].modCount;
}
if (sum != 0L) { // recheck unless no modifications
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0) {
return false;
}
sum -= segments[i].modCount;
}
if (sum != 0L) {
return false;
}
}
return true;
}
@Override
public int size() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
for (int i = 0; i < segments.length; ++i) {
sum += segments[i].count;
}
return Ints.saturatedCast(sum);
}
@Override
public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).get(key, hash);
}
/**
* Returns the internal entry for the specified key. The entry may be computing, expired, or
* partially collected. Does not impact recency ordering.
*/
ReferenceEntry<K, V> getEntry(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).getEntry(key, hash);
}
@Override
public boolean containsKey(@Nullable Object key) {
if (key == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).containsKey(key, hash);
}
@Override
public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
// This implementation is patterned after ConcurrentHashMap, but without the locking. The only
// way for it to return a false negative would be for the target value to jump around in the map
// such that none of the subsequent iterations observed it, despite the fact that at every point
// in time it was present somewhere int the map. This becomes increasingly unlikely as
// CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible.
final Segment<K, V>[] segments = this.segments;
long last = -1L;
for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
long sum = 0L;
for (Segment<K, V> segment : segments) {
// ensure visibility of most recent completed write
@SuppressWarnings({"UnusedDeclaration", "unused"})
int c = segment.count; // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
for (int j = 0; j < table.length(); j++) {
for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
V v = segment.getLiveValue(e);
if (v != null && valueEquivalence.equivalent(value, v)) {
return true;
}
}
}
sum += segment.modCount;
}
if (sum == last) {
break;
}
last = sum;
}
return false;
}
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, false);
}
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, true);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public V remove(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash);
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
if (key == null || value == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash, value);
}
@Override
public boolean replace(K key, @Nullable V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).replace(key, hash, value);
}
@Override
public void clear() {
for (Segment<K, V> segment : segments) {
segment.clear();
}
}
transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
}
transient Collection<V> values;
@Override
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
// Iterator Support
abstract class HashIterator<E> implements Iterator<E> {
int nextSegmentIndex;
int nextTableIndex;
Segment<K, V> currentSegment;
AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
ReferenceEntry<K, V> nextEntry;
WriteThroughEntry nextExternal;
WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
nextTableIndex = -1;
advance();
}
public abstract E next();
final void advance() {
nextExternal = null;
if (nextInChain()) {
return;
}
if (nextInTable()) {
return;
}
while (nextSegmentIndex >= 0) {
currentSegment = segments[nextSegmentIndex--];
if (currentSegment.count != 0) {
currentTable = currentSegment.table;
nextTableIndex = currentTable.length() - 1;
if (nextInTable()) {
return;
}
}
}
}
/**
* Finds the next entry in the current chain. Returns {@code true} if an entry was found.
*/
boolean nextInChain() {
if (nextEntry != null) {
for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) {
if (advanceTo(nextEntry)) {
return true;
}
}
}
return false;
}
/**
* Finds the next entry in the current table. Returns {@code true} if an entry was found.
*/
boolean nextInTable() {
while (nextTableIndex >= 0) {
if ((nextEntry = currentTable.get(nextTableIndex--)) != null) {
if (advanceTo(nextEntry) || nextInChain()) {
return true;
}
}
}
return false;
}
/**
* Advances to the given entry. Returns {@code true} if the entry was valid, {@code false} if it
* should be skipped.
*/
boolean advanceTo(ReferenceEntry<K, V> entry) {
try {
K key = entry.getKey();
V value = getLiveValue(entry);
if (value != null) {
nextExternal = new WriteThroughEntry(key, value);
return true;
} else {
// Skip stale entry.
return false;
}
} finally {
currentSegment.postReadCleanup();
}
}
public boolean hasNext() {
return nextExternal != null;
}
WriteThroughEntry nextEntry() {
if (nextExternal == null) {
throw new NoSuchElementException();
}
lastReturned = nextExternal;
advance();
return lastReturned;
}
public void remove() {
checkState(lastReturned != null);
MapMakerInternalMap.this.remove(lastReturned.getKey());
lastReturned = null;
}
}
final class KeyIterator extends HashIterator<K> {
@Override
public K next() {
return nextEntry().getKey();
}
}
final class ValueIterator extends HashIterator<V> {
@Override
public V next() {
return nextEntry().getValue();
}
}
/**
* Custom Entry class used by EntryIterator.next(), that relays setValue changes to the
* underlying map.
*/
final class WriteThroughEntry extends AbstractMapEntry<K, V> {
final K key; // non-null
V value; // non-null
WriteThroughEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public boolean equals(@Nullable Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return key.equals(that.getKey()) && value.equals(that.getValue());
}
return false;
}
@Override
public int hashCode() {
// Cannot use key and value equivalence
return key.hashCode() ^ value.hashCode();
}
@Override
public V setValue(V newValue) {
V oldValue = put(key, newValue);
value = newValue; // only if put succeeds
return oldValue;
}
}
final class EntryIterator extends HashIterator<Entry<K, V>> {
@Override
public Entry<K, V> next() {
return nextEntry();
}
}
final class KeySet extends AbstractSet<K> {
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public int size() {
return MapMakerInternalMap.this.size();
}
@Override
public boolean isEmpty() {
return MapMakerInternalMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
return MapMakerInternalMap.this.containsKey(o);
}
@Override
public boolean remove(Object o) {
return MapMakerInternalMap.this.remove(o) != null;
}
@Override
public void clear() {
MapMakerInternalMap.this.clear();
}
}
final class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public int size() {
return MapMakerInternalMap.this.size();
}
@Override
public boolean isEmpty() {
return MapMakerInternalMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
return MapMakerInternalMap.this.containsValue(o);
}
@Override
public void clear() {
MapMakerInternalMap.this.clear();
}
}
final class EntrySet extends AbstractSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
if (key == null) {
return false;
}
V v = MapMakerInternalMap.this.get(key);
return v != null && valueEquivalence.equivalent(e.getValue(), v);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
return key != null && MapMakerInternalMap.this.remove(key, e.getValue());
}
@Override
public int size() {
return MapMakerInternalMap.this.size();
}
@Override
public boolean isEmpty() {
return MapMakerInternalMap.this.isEmpty();
}
@Override
public void clear() {
MapMakerInternalMap.this.clear();
}
}
// Serialization Support
private static final long serialVersionUID = 5;
Object writeReplace() {
return new SerializationProxy<K, V>(keyStrength, valueStrength, keyEquivalence,
valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize,
concurrencyLevel, removalListener, this);
}
/**
* The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a
* circular dependency is present, so the proxy must be able to behave as the map itself.
*/
abstract static class AbstractSerializationProxy<K, V>
extends ForwardingConcurrentMap<K, V> implements Serializable {
private static final long serialVersionUID = 3;
final Strength keyStrength;
final Strength valueStrength;
final Equivalence<Object> keyEquivalence;
final Equivalence<Object> valueEquivalence;
final long expireAfterWriteNanos;
final long expireAfterAccessNanos;
final int maximumSize;
final int concurrencyLevel;
final RemovalListener<? super K, ? super V> removalListener;
transient ConcurrentMap<K, V> delegate;
AbstractSerializationProxy(Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
ConcurrentMap<K, V> delegate) {
this.keyStrength = keyStrength;
this.valueStrength = valueStrength;
this.keyEquivalence = keyEquivalence;
this.valueEquivalence = valueEquivalence;
this.expireAfterWriteNanos = expireAfterWriteNanos;
this.expireAfterAccessNanos = expireAfterAccessNanos;
this.maximumSize = maximumSize;
this.concurrencyLevel = concurrencyLevel;
this.removalListener = removalListener;
this.delegate = delegate;
}
@Override
protected ConcurrentMap<K, V> delegate() {
return delegate;
}
void writeMapTo(ObjectOutputStream out) throws IOException {
out.writeInt(delegate.size());
for (Entry<K, V> entry : delegate.entrySet()) {
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
out.writeObject(null); // terminate entries
}
@SuppressWarnings("deprecation") // serialization of deprecated feature
MapMaker readMapMaker(ObjectInputStream in) throws IOException {
int size = in.readInt();
MapMaker mapMaker = new MapMaker()
.initialCapacity(size)
.setKeyStrength(keyStrength)
.setValueStrength(valueStrength)
.keyEquivalence(keyEquivalence)
.concurrencyLevel(concurrencyLevel);
mapMaker.removalListener(removalListener);
if (expireAfterWriteNanos > 0) {
mapMaker.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS);
}
if (expireAfterAccessNanos > 0) {
mapMaker.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (maximumSize != MapMaker.UNSET_INT) {
mapMaker.maximumSize(maximumSize);
}
return mapMaker;
}
@SuppressWarnings("unchecked")
void readEntries(ObjectInputStream in) throws IOException, ClassNotFoundException {
while (true) {
K key = (K) in.readObject();
if (key == null) {
break; // terminator
}
V value = (V) in.readObject();
delegate.put(key, value);
}
}
}
/**
* The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a
* circular dependency is present, so the proxy must be able to behave as the map itself.
*/
private static final class SerializationProxy<K, V> extends AbstractSerializationProxy<K, V> {
private static final long serialVersionUID = 3;
SerializationProxy(Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
ConcurrentMap<K, V> delegate) {
super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos,
expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate);
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
writeMapTo(out);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MapMaker mapMaker = readMapMaker(in);
delegate = mapMaker.makeMap();
readEntries(in);
}
private Object readResolve() {
return delegate;
}
}
}
| Java |
/*
* Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible;
/**
* Unused stub class, unreferenced under Java and manually emulated under GWT.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
abstract class ForwardingImmutableMap<K, V> {
private ForwardingImmutableMap() {}
}
| Java |
/*
* Copyright (C) 2012 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.collect.Maps.keyOrNull;
import com.google.common.annotations.Beta;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import javax.annotation.Nullable;
/**
* A navigable map which forwards all its method calls to another navigable map. Subclasses should
* override one or more methods to modify the behavior of the backing map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingNavigableMap} forward <i>indiscriminately</i>
* to the methods of the delegate. For example, overriding {@link #put} alone <i>will not</i>
* change the behavior of {@link #putAll}, which can lead to unexpected behavior. In this case, you
* should override {@code putAll} as well, either providing your own implementation, or delegating
* to the provided {@code standardPutAll} method.
*
* <p>Each of the {@code standard} methods uses the map's comparator (or the natural ordering of
* the elements, if there is no comparator) to test element equality. As a result, if the comparator
* is not consistent with equals, some of the standard implementations may violate the {@code Map}
* contract.
*
* <p>The {@code standard} methods and the collection views they return are not guaranteed to be
* thread-safe, even when all of the methods that they depend on are thread-safe.
*
* @author Louis Wasserman
* @since 12.0
*/
@Beta
public abstract class ForwardingNavigableMap<K, V>
extends ForwardingSortedMap<K, V> implements NavigableMap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingNavigableMap() {}
@Override
protected abstract NavigableMap<K, V> delegate();
@Override
public Entry<K, V> lowerEntry(K key) {
return delegate().lowerEntry(key);
}
/**
* A sensible definition of {@link #lowerEntry} in terms of the {@code lastEntry()} of
* {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override
* {@code lowerEntry} to forward to this implementation.
*/
protected Entry<K, V> standardLowerEntry(K key) {
return headMap(key, false).lastEntry();
}
@Override
public K lowerKey(K key) {
return delegate().lowerKey(key);
}
/**
* A sensible definition of {@link #lowerKey} in terms of {@code lowerEntry}. If you override
* {@link #lowerEntry}, you may wish to override {@code lowerKey} to forward to this
* implementation.
*/
protected K standardLowerKey(K key) {
return keyOrNull(lowerEntry(key));
}
@Override
public Entry<K, V> floorEntry(K key) {
return delegate().floorEntry(key);
}
/**
* A sensible definition of {@link #floorEntry} in terms of the {@code lastEntry()} of
* {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override
* {@code floorEntry} to forward to this implementation.
*/
protected Entry<K, V> standardFloorEntry(K key) {
return headMap(key, true).lastEntry();
}
@Override
public K floorKey(K key) {
return delegate().floorKey(key);
}
/**
* A sensible definition of {@link #floorKey} in terms of {@code floorEntry}. If you override
* {@code floorEntry}, you may wish to override {@code floorKey} to forward to this
* implementation.
*/
protected K standardFloorKey(K key) {
return keyOrNull(floorEntry(key));
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return delegate().ceilingEntry(key);
}
/**
* A sensible definition of {@link #ceilingEntry} in terms of the {@code firstEntry()} of
* {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override
* {@code ceilingEntry} to forward to this implementation.
*/
protected Entry<K, V> standardCeilingEntry(K key) {
return tailMap(key, true).firstEntry();
}
@Override
public K ceilingKey(K key) {
return delegate().ceilingKey(key);
}
/**
* A sensible definition of {@link #ceilingKey} in terms of {@code ceilingEntry}. If you override
* {@code ceilingEntry}, you may wish to override {@code ceilingKey} to forward to this
* implementation.
*/
protected K standardCeilingKey(K key) {
return keyOrNull(ceilingEntry(key));
}
@Override
public Entry<K, V> higherEntry(K key) {
return delegate().higherEntry(key);
}
/**
* A sensible definition of {@link #higherEntry} in terms of the {@code firstEntry()} of
* {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override
* {@code higherEntry} to forward to this implementation.
*/
protected Entry<K, V> standardHigherEntry(K key) {
return tailMap(key, false).firstEntry();
}
@Override
public K higherKey(K key) {
return delegate().higherKey(key);
}
/**
* A sensible definition of {@link #higherKey} in terms of {@code higherEntry}. If you override
* {@code higherEntry}, you may wish to override {@code higherKey} to forward to this
* implementation.
*/
protected K standardHigherKey(K key) {
return keyOrNull(higherEntry(key));
}
@Override
public Entry<K, V> firstEntry() {
return delegate().firstEntry();
}
/**
* A sensible definition of {@link #firstEntry} in terms of the {@code iterator()} of
* {@link #entrySet}. If you override {@code entrySet}, you may wish to override
* {@code firstEntry} to forward to this implementation.
*/
protected Entry<K, V> standardFirstEntry() {
return Iterables.getFirst(entrySet(), null);
}
/**
* A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If you override
* {@code firstEntry}, you may wish to override {@code firstKey} to forward to this
* implementation.
*/
protected K standardFirstKey() {
Entry<K, V> entry = firstEntry();
if (entry == null) {
throw new NoSuchElementException();
} else {
return entry.getKey();
}
}
@Override
public Entry<K, V> lastEntry() {
return delegate().lastEntry();
}
/**
* A sensible definition of {@link #lastEntry} in terms of the {@code iterator()} of the
* {@link #entrySet} of {@link #descendingMap}. If you override {@code descendingMap}, you may
* wish to override {@code lastEntry} to forward to this implementation.
*/
protected Entry<K, V> standardLastEntry() {
return Iterables.getFirst(descendingMap().entrySet(), null);
}
/**
* A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If you override
* {@code lastEntry}, you may wish to override {@code lastKey} to forward to this implementation.
*/
protected K standardLastKey() {
Entry<K, V> entry = lastEntry();
if (entry == null) {
throw new NoSuchElementException();
} else {
return entry.getKey();
}
}
@Override
public Entry<K, V> pollFirstEntry() {
return delegate().pollFirstEntry();
}
/**
* A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of
* {@code entrySet}. If you override {@code entrySet}, you may wish to override
* {@code pollFirstEntry} to forward to this implementation.
*/
protected Entry<K, V> standardPollFirstEntry() {
return poll(entrySet().iterator());
}
@Override
public Entry<K, V> pollLastEntry() {
return delegate().pollLastEntry();
}
/**
* A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of the
* {@code entrySet} of {@code descendingMap}. If you override {@code descendingMap}, you may wish
* to override {@code pollFirstEntry} to forward to this implementation.
*/
protected Entry<K, V> standardPollLastEntry() {
return poll(descendingMap().entrySet().iterator());
}
@Override
public NavigableMap<K, V> descendingMap() {
return delegate().descendingMap();
}
/**
* A sensible implementation of {@link NavigableMap#descendingMap} in terms of the methods of
* this {@code NavigableMap}. In many cases, you may wish to override
* {@link ForwardingNavigableMap#descendingMap} to forward to this implementation or a subclass
* thereof.
*
* <p>In particular, this map iterates over entries with repeated calls to
* {@link NavigableMap#lowerEntry}. If a more efficient means of iteration is available, you may
* wish to override the {@code entryIterator()} method of this class.
*
* @since 12.0
*/
@Beta
protected class StandardDescendingMap extends Maps.DescendingMap<K, V> {
/** Constructor for use by subclasses. */
public StandardDescendingMap() {}
@Override
NavigableMap<K, V> forward() {
return ForwardingNavigableMap.this;
}
@Override
protected Iterator<Entry<K, V>> entryIterator() {
return new Iterator<Entry<K, V>>() {
private Entry<K, V> toRemove = null;
private Entry<K, V> nextOrNull = forward().lastEntry();
@Override
public boolean hasNext() {
return nextOrNull != null;
}
@Override
public java.util.Map.Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return nextOrNull;
} finally {
toRemove = nextOrNull;
nextOrNull = forward().lowerEntry(nextOrNull.getKey());
}
}
@Override
public void remove() {
Iterators.checkRemove(toRemove != null);
forward().remove(toRemove.getKey());
toRemove = null;
}
};
}
}
@Override
public NavigableSet<K> navigableKeySet() {
return delegate().navigableKeySet();
}
/**
* A sensible implementation of {@link NavigableMap#navigableKeySet} in terms of the methods of
* this {@code NavigableMap}. In many cases, you may wish to override
* {@link ForwardingNavigableMap#navigableKeySet} to forward to this implementation or a subclass
* thereof.
*
* @since 12.0
*/
@Beta
protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardNavigableKeySet() {}
@Override
NavigableMap<K, V> map() {
return ForwardingNavigableMap.this;
}
}
@Override
public NavigableSet<K> descendingKeySet() {
return delegate().descendingKeySet();
}
/**
* A sensible definition of {@link #descendingKeySet} as the {@code navigableKeySet} of
* {@link #descendingMap}. (The {@link StandardDescendingMap} implementation implements
* {@code navigableKeySet} on its own, so as not to cause an infinite loop.) If you override
* {@code descendingMap}, you may wish to override {@code descendingKeySet} to forward to this
* implementation.
*/
protected NavigableSet<K> standardDescendingKeySet() {
return descendingMap().navigableKeySet();
}
/**
* A sensible definition of {@link #subMap(Object, Object)} in terms of
* {@link #subMap(Object, boolean, Object, boolean)}. If you override
* {@code subMap(K, boolean, K, boolean)}, you may wish to override {@code subMap} to forward to
* this implementation.
*/
@Override
protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return delegate().headMap(toKey, inclusive);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return delegate().tailMap(fromKey, inclusive);
}
/**
* A sensible definition of {@link #headMap(Object)} in terms of
* {@link #headMap(Object, boolean)}. If you override {@code headMap(K, boolean)}, you may wish
* to override {@code headMap} to forward to this implementation.
*/
protected SortedMap<K, V> standardHeadMap(K toKey) {
return headMap(toKey, false);
}
/**
* A sensible definition of {@link #tailMap(Object)} in terms of
* {@link #tailMap(Object, boolean)}. If you override {@code tailMap(K, boolean)}, you may wish
* to override {@code tailMap} to forward to this implementation.
*/
protected SortedMap<K, V> standardTailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Nullable
private static <T> T poll(Iterator<T> iterator) {
if (iterator.hasNext()) {
T result = iterator.next();
iterator.remove();
return result;
}
return null;
}
}
| Java |
/*
* 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.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An immutable {@link Multimap}. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableMultimap(Multimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>In addition to methods defined by {@link Multimap}, an {@link #inverse}
* method is also supported.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public abstract class ImmutableMultimap<K, V>
implements Multimap<K, V>, Serializable {
/** Returns an empty multimap. */
public static <K, V> ImmutableMultimap<K, V> of() {
return ImmutableListMultimap.of();
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) {
return ImmutableListMultimap.of(k1, v1);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
return ImmutableListMultimap.of(k1, v1, k2, v2);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Multimap for {@link ImmutableMultimap.Builder} that maintains key and
* value orderings, allows duplicate values, and performs better than
* {@link LinkedListMultimap}.
*/
private static class BuilderMultimap<K, V> extends AbstractMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Lists.newArrayList();
}
private static final long serialVersionUID = 0;
}
/**
* A builder for creating immutable multimap instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<K, V> {
Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>();
Comparator<? super K> keyComparator;
Comparator<? super V> valueComparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMultimap#builder}.
*/
public Builder() {}
/**
* Adds a key-value mapping to the built multimap.
*/
public Builder<K, V> put(K key, V value) {
builderMultimap.put(checkNotNull(key), checkNotNull(value));
return this;
}
/**
* Adds an entry to the built multimap.
*
* @since 11.0
*/
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
builderMultimap.put(
checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
return this;
}
/**
* Stores a collection of values with the same key in the built multimap.
*
* @throws NullPointerException if {@code key}, {@code values}, or any
* element in {@code values} is null. The builder is left in an invalid
* state.
*/
public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
Collection<V> valueList = builderMultimap.get(checkNotNull(key));
for (V value : values) {
valueList.add(checkNotNull(value));
}
return this;
}
/**
* Stores an array of values with the same key in the built multimap.
*
* @throws NullPointerException if the key or any value is null. The builder
* is left in an invalid state.
*/
public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
/**
* Stores another multimap's entries in the built multimap. The generated
* multimap's key and value orderings correspond to the iteration ordering
* of the {@code multimap.asMap()} view, with new keys and values following
* any existing keys and values.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null. The builder is left in an invalid state.
*/
public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Specifies the ordering of the generated multimap's keys.
*
* @since 8.0
*/
@Beta
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
this.keyComparator = checkNotNull(keyComparator);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* @since 8.0
*/
@Beta
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
this.valueComparator = checkNotNull(valueComparator);
return this;
}
/**
* Returns a newly-created immutable multimap.
*/
public ImmutableMultimap<K, V> build() {
if (valueComparator != null) {
for (Collection<V> values : builderMultimap.asMap().values()) {
List<V> list = (List <V>) values;
Collections.sort(list, valueComparator);
}
}
if (keyComparator != null) {
Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>();
List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList(
builderMultimap.asMap().entrySet());
Collections.sort(
entries,
Ordering.from(keyComparator).onResultOf(new Function<Entry<K, Collection<V>>, K>() {
@Override
public K apply(Entry<K, Collection<V>> entry) {
return entry.getKey();
}
}));
for (Map.Entry<K, Collection<V>> entry : entries) {
sortedCopy.putAll(entry.getKey(), entry.getValue());
}
builderMultimap = sortedCopy;
}
return copyOf(builderMultimap);
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code
* multimap}. The generated multimap's key and value orderings correspond to
* the iteration ordering of the {@code multimap.asMap()} view.
*
* <p>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 NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap instanceof ImmutableMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableMultimap<K, V> kvMultimap
= (ImmutableMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
return ImmutableListMultimap.copyOf(multimap);
}
final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map;
final transient int size;
// These constants allow the deserialization code to set final fields. This
// holder class makes sure they are not initialized unless an instance is
// deserialized.
@GwtIncompatible("java serialization is not supported")
static class FieldSettersHolder {
static final Serialization.FieldSetter<ImmutableMultimap>
MAP_FIELD_SETTER = Serialization.getFieldSetter(
ImmutableMultimap.class, "map");
static final Serialization.FieldSetter<ImmutableMultimap>
SIZE_FIELD_SETTER = Serialization.getFieldSetter(
ImmutableMultimap.class, "size");
}
ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map,
int size) {
this.map = map;
this.size = size;
}
// mutators (not supported)
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public ImmutableCollection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public ImmutableCollection<V> replaceValues(K key,
Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public void clear() {
throw new UnsupportedOperationException();
}
/**
* Returns an immutable collection of the values for the given key. If no
* mappings in the multimap have the provided key, an empty immutable
* collection is returned. The values are in the same order as the parameters
* used to build this multimap.
*/
@Override
public abstract ImmutableCollection<V> get(K key);
/**
* Returns an immutable multimap which is the inverse of this one. For every
* key-value mapping in the original, the result will have a mapping with
* key and value reversed.
*
* @since 11.0
*/
@Beta
public abstract ImmutableMultimap<V, K> inverse();
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
boolean isPartialView() {
return map.isPartialView();
}
// accessors
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
Collection<V> values = map.get(key);
return values != null && values.contains(value);
}
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Collection<V> valueCollection : map.values()) {
if (valueCollection.contains(value)) {
return true;
}
}
return false;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int size() {
return size;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return this.map.equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
@Override public String toString() {
return map.toString();
}
// views
/**
* Returns an immutable set of the distinct keys in this multimap. These keys
* are ordered according to when they first appeared during the construction
* of this multimap.
*/
@Override
public ImmutableSet<K> keySet() {
return map.keySet();
}
/**
* Returns an immutable map that associates each key with its corresponding
* values in the multimap.
*/
@Override
@SuppressWarnings("unchecked") // a widening cast
public ImmutableMap<K, Collection<V>> asMap() {
return (ImmutableMap) map;
}
private transient ImmutableCollection<Entry<K, V>> entries;
/**
* Returns an immutable collection of all key-value pairs in the multimap. Its
* iterator traverses the values for the first key, the values for the second
* key, and so on.
*/
@Override
public ImmutableCollection<Entry<K, V>> entries() {
ImmutableCollection<Entry<K, V>> result = entries;
return (result == null)
? (entries = new EntryCollection<K, V>(this)) : result;
}
private static class EntryCollection<K, V>
extends ImmutableCollection<Entry<K, V>> {
final ImmutableMultimap<K, V> multimap;
EntryCollection(ImmutableMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override public UnmodifiableIterator<Entry<K, V>> iterator() {
final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>>
mapIterator = this.multimap.map.entrySet().iterator();
return new UnmodifiableIterator<Entry<K, V>>() {
K key;
Iterator<V> valueIterator;
@Override
public boolean hasNext() {
return (key != null && valueIterator.hasNext())
|| mapIterator.hasNext();
}
@Override
public Entry<K, V> next() {
if (key == null || !valueIterator.hasNext()) {
Entry<K, ? extends ImmutableCollection<V>> entry
= mapIterator.next();
key = entry.getKey();
valueIterator = entry.getValue().iterator();
}
return Maps.immutableEntry(key, valueIterator.next());
}
};
}
@Override boolean isPartialView() {
return multimap.isPartialView();
}
@Override
public int size() {
return multimap.size();
}
@Override public boolean contains(Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
return multimap.containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
private static final long serialVersionUID = 0;
}
private transient ImmutableMultiset<K> keys;
/**
* Returns a collection, which may contain duplicates, of all keys. The number
* of times a key appears in the returned multiset equals the number of
* mappings the key has in the multimap. Duplicate keys appear consecutively
* in the multiset's iteration order.
*/
@Override
public ImmutableMultiset<K> keys() {
ImmutableMultiset<K> result = keys;
return (result == null) ? (keys = createKeys()) : result;
}
private ImmutableMultiset<K> createKeys() {
return new Keys();
}
@SuppressWarnings("serial") // Uses writeReplace, not default serialization
class Keys extends ImmutableMultiset<K> {
@Override
public boolean contains(@Nullable Object object) {
return containsKey(object);
}
@Override
public int count(@Nullable Object element) {
Collection<V> values = map.get(element);
return (values == null) ? 0 : values.size();
}
@Override
public Set<K> elementSet() {
return keySet();
}
@Override
public int size() {
return ImmutableMultimap.this.size();
}
@Override
ImmutableSet<Entry<K>> createEntrySet() {
return new KeysEntrySet();
}
private class KeysEntrySet extends ImmutableMultiset<K>.EntrySet {
@Override
public int size() {
return keySet().size();
}
@Override
public UnmodifiableIterator<Entry<K>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<K>> createAsList() {
final ImmutableList<? extends Map.Entry<K, ? extends Collection<V>>> mapEntries =
map.entrySet().asList();
return new ImmutableAsList<Entry<K>>() {
@Override
public Entry<K> get(int index) {
Map.Entry<K, ? extends Collection<V>> entry = mapEntries.get(index);
return Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
}
@Override
ImmutableCollection<Entry<K>> delegateCollection() {
return KeysEntrySet.this;
}
};
}
}
@Override
boolean isPartialView() {
return true;
}
}
private transient ImmutableCollection<V> values;
/**
* Returns an immutable collection of the values in this multimap. Its
* iterator traverses the values for the first key, the values for the second
* key, and so on.
*/
@Override
public ImmutableCollection<V> values() {
ImmutableCollection<V> result = values;
return (result == null) ? (values = new Values<V>(this)) : result;
}
private static class Values<V> extends ImmutableCollection<V> {
final ImmutableMultimap<?, V> multimap;
Values(ImmutableMultimap<?, V> multimap) {
this.multimap = multimap;
}
@Override public UnmodifiableIterator<V> iterator() {
return Maps.valueIterator(multimap.entries().iterator());
}
@Override
public int size() {
return multimap.size();
}
@Override boolean isPartialView() {
return true;
}
private static final long serialVersionUID = 0;
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* An immutable collection. Does not permit null elements.
*
* <p>In addition to the {@link Collection} methods, this class has an {@link
* #asList()} method, which returns a list view of the collection's elements.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed
* outside of this package as it has no public or protected constructors. Thus,
* instances of this type are guaranteed to be immutable.
*
* @author Jesse Wilson
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableCollection<E>
implements Collection<E>, Serializable {
static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION
= new EmptyImmutableCollection();
ImmutableCollection() {}
/**
* Returns an unmodifiable iterator across the elements in this collection.
*/
@Override
public abstract UnmodifiableIterator<E> iterator();
@Override
public Object[] toArray() {
return ObjectArrays.toArrayImpl(this);
}
@Override
public <T> T[] toArray(T[] other) {
return ObjectArrays.toArrayImpl(this, other);
}
@Override
public boolean contains(@Nullable Object object) {
return object != null && Iterators.contains(iterator(), object);
}
@Override
public boolean containsAll(Collection<?> targets) {
return Collections2.containsAllImpl(this, targets);
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override public String toString() {
return Collections2.toStringImpl(this);
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean add(E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean remove(Object object) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean addAll(Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void clear() {
throw new UnsupportedOperationException();
}
/*
* TODO(kevinb): Restructure code so ImmutableList doesn't contain this
* variable, which it doesn't use.
*/
private transient ImmutableList<E> asList;
/**
* Returns a list view of the collection.
*
* @since 2.0
*/
public ImmutableList<E> asList() {
ImmutableList<E> list = asList;
return (list == null) ? (asList = createAsList()) : list;
}
ImmutableList<E> createAsList() {
switch (size()) {
case 0:
return ImmutableList.of();
case 1:
return ImmutableList.of(iterator().next());
default:
return new RegularImmutableAsList<E>(this, toArray());
}
}
abstract boolean isPartialView();
private static class EmptyImmutableCollection
extends ImmutableCollection<Object> {
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean contains(@Nullable Object object) {
return false;
}
@Override public UnmodifiableIterator<Object> iterator() {
return Iterators.EMPTY_LIST_ITERATOR;
}
private static final Object[] EMPTY_ARRAY = new Object[0];
@Override public Object[] toArray() {
return EMPTY_ARRAY;
}
@Override public <T> T[] toArray(T[] array) {
if (array.length > 0) {
array[0] = null;
}
return array;
}
@Override ImmutableList<Object> createAsList() {
return ImmutableList.of();
}
@Override boolean isPartialView() {
return false;
}
}
/**
* Nonempty collection stored in an array.
*/
private static class ArrayImmutableCollection<E>
extends ImmutableCollection<E> {
private final E[] elements;
ArrayImmutableCollection(E[] elements) {
this.elements = elements;
}
@Override
public int size() {
return elements.length;
}
@Override public boolean isEmpty() {
return false;
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.forArray(elements);
}
@Override ImmutableList<E> createAsList() {
return elements.length == 1 ? new SingletonImmutableList<E>(elements[0])
: new RegularImmutableList<E>(elements);
}
@Override boolean isPartialView() {
return false;
}
}
/*
* Serializes ImmutableCollections as their logical contents. This ensures
* that implementation types do not leak into the serialized representation.
*/
private static class SerializedForm implements Serializable {
final Object[] elements;
SerializedForm(Object[] elements) {
this.elements = elements;
}
Object readResolve() {
return elements.length == 0
? EMPTY_IMMUTABLE_COLLECTION
: new ArrayImmutableCollection<Object>(Platform.clone(elements));
}
private static final long serialVersionUID = 0;
}
Object writeReplace() {
return new SerializedForm(toArray());
}
/**
* Abstract base class for builders of {@link ImmutableCollection} types.
*
* @since 10.0
*/
public abstract static class Builder<E> {
static final int DEFAULT_INITIAL_CAPACITY = 4;
@VisibleForTesting
static int expandedCapacity(int oldCapacity, int minCapacity) {
if (minCapacity < 0) {
throw new AssertionError("cannot store more than MAX_VALUE elements");
}
// careful of overflow!
int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
if (newCapacity < minCapacity) {
newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
}
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
// guaranteed to be >= newCapacity
}
return newCapacity;
}
Builder() {
}
/**
* Adds {@code element} to the {@code ImmutableCollection} being built.
*
* <p>Note that each builder class covariantly returns its own type from
* this method.
*
* @param element the element to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code element} is null
*/
public abstract Builder<E> add(E element);
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection}
* being built.
*
* <p>Note that each builder class overrides this method in order to
* covariantly return its own type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
public Builder<E> add(E... elements) {
for (E element : elements) {
add(element);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection}
* being built.
*
* <p>Note that each builder class overrides this method in order to
* covariantly return its own type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
public Builder<E> addAll(Iterable<? extends E> elements) {
for (E element : elements) {
add(element);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection}
* being built.
*
* <p>Note that each builder class overrides this method in order to
* covariantly return its own type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
public Builder<E> addAll(Iterator<? extends E> elements) {
while (elements.hasNext()) {
add(elements.next());
}
return this;
}
/**
* Returns a newly-created {@code ImmutableCollection} of the appropriate
* type, containing the elements provided to this builder.
*
* <p>Note that each builder class covariantly returns the appropriate type
* of {@code ImmutableCollection} from this method.
*/
public abstract ImmutableCollection<E> build();
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.EnumMap;
import java.util.Iterator;
/**
* Multiset implementation backed by an {@link EnumMap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> {
/** Creates an empty {@code EnumMultiset}. */
public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) {
return new EnumMultiset<E>(type);
}
/**
* Creates a new {@code EnumMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link
* Multiset}.
*
* @param elements the elements that the multiset should contain
* @throws IllegalArgumentException if {@code elements} is empty
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) {
Iterator<E> iterator = elements.iterator();
checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable");
EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass());
Iterables.addAll(multiset, elements);
return multiset;
}
private transient Class<E> type;
/** Creates an empty {@code EnumMultiset}. */
private EnumMultiset(Class<E> type) {
super(WellBehavedMap.wrap(new EnumMap<E, Count>(type)));
this.type = type;
}
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(type);
Serialization.writeMultiset(this, stream);
}
/**
* @serialData the {@code Class<E>} for the enum type, the number of distinct
* elements, the first element, its count, the second element, its
* count, and so on
*/
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
Class<E> localType = (Class<E>) stream.readObject();
type = localType;
setBackingMap(WellBehavedMap.wrap(new EnumMap<E, Count>(type)));
Serialization.populateMultiset(this, stream);
}
@GwtIncompatible("Not needed in emulated source")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible;
/**
* Unused stub class, unreferenced under Java and manually emulated under GWT.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
abstract class ForwardingImmutableSet<E> {
private ForwardingImmutableSet() {}
}
| Java |
/*
* Copyright (C) 2012 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 java.util.Comparator;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An empty immutable sorted map.
*
* @author Louis Wasserman
*/
@SuppressWarnings("serial") // uses writeReplace, not default serialization
final class EmptyImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> {
private final transient ImmutableSortedSet<K> keySet;
EmptyImmutableSortedMap(Comparator<? super K> comparator) {
this.keySet = ImmutableSortedSet.emptySet(comparator);
}
EmptyImmutableSortedMap(
Comparator<? super K> comparator, ImmutableSortedMap<K, V> descendingMap) {
super(descendingMap);
this.keySet = ImmutableSortedSet.emptySet(comparator);
}
@Override
public V get(@Nullable Object key) {
return null;
}
@Override
public ImmutableSortedSet<K> keySet() {
return keySet;
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public ImmutableCollection<V> values() {
return ImmutableList.of();
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Map) {
Map<?, ?> map = (Map<?, ?>) object;
return map.isEmpty();
}
return false;
}
@Override
public String toString() {
return "{}";
}
@Override
boolean isPartialView() {
return false;
}
@Override
public ImmutableSet<Entry<K, V>> entrySet() {
return ImmutableSet.of();
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
throw new AssertionError("should never be called");
}
@Override
public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
checkNotNull(toKey);
return this;
}
@Override
public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
checkNotNull(fromKey);
return this;
}
@Override
ImmutableSortedMap<K, V> createDescendingMap() {
return new EmptyImmutableSortedMap<K, V>(Ordering.from(comparator()).reverse(), this);
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.primitives.Primitives;
import java.util.Map;
/**
* A class-to-instance map backed by an {@link ImmutableMap}. See also {@link
* MutableClassToInstanceMap}.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
public final class ImmutableClassToInstanceMap<B> extends
ForwardingMap<Class<? extends B>, B> implements ClassToInstanceMap<B> {
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <B> Builder<B> builder() {
return new Builder<B>();
}
/**
* A builder for creating immutable class-to-instance maps. Example:
* <pre> {@code
*
* static final ImmutableClassToInstanceMap<Handler> HANDLERS =
* new ImmutableClassToInstanceMap.Builder<Handler>()
* .put(FooHandler.class, new FooHandler())
* .put(BarHandler.class, new SubBarHandler())
* .put(Handler.class, new QuuxHandler())
* .build();}</pre>
*
* After invoking {@link #build()} it is still possible to add more entries
* and build again. Thus each map generated by this builder will be a superset
* of any map generated before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<B> {
private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder
= ImmutableMap.builder();
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys are not allowed, and will cause {@link #build} to fail.
*/
public <T extends B> Builder<B> put(Class<T> key, T value) {
mapBuilder.put(key, value);
return this;
}
/**
* Associates all of {@code map's} keys and values in the built map.
* Duplicate keys are not allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws ClassCastException if any value is not an instance of the type
* specified by its key
*/
public <T extends B> Builder<B> putAll(
Map<? extends Class<? extends T>, ? extends T> map) {
for (Entry<? extends Class<? extends T>, ? extends T> entry
: map.entrySet()) {
Class<? extends T> type = entry.getKey();
T value = entry.getValue();
mapBuilder.put(type, cast(type, value));
}
return this;
}
private static <B, T extends B> T cast(Class<T> type, B value) {
return Primitives.wrap(type).cast(value);
}
/**
* Returns a new immutable class-to-instance map containing the entries
* provided to this builder.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableClassToInstanceMap<B> build() {
return new ImmutableClassToInstanceMap<B>(mapBuilder.build());
}
}
/**
* Returns an immutable map containing the same entries as {@code map}. If
* {@code map} somehow contains entries with duplicate keys (for example, if
* it is a {@code SortedMap} whose comparator is not <i>consistent with
* equals</i>), the results of this method are undefined.
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code map} is
* an {@code ImmutableClassToInstanceMap}, no copy will actually be performed.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws ClassCastException if any value is not an instance of the type
* specified by its key
*/
public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf(
Map<? extends Class<? extends S>, ? extends S> map) {
if (map instanceof ImmutableClassToInstanceMap) {
@SuppressWarnings("unchecked") // covariant casts safe (unmodifiable)
// Eclipse won't compile if we cast to the parameterized type.
ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap) map;
return cast;
}
return new Builder<B>().putAll(map).build();
}
private final ImmutableMap<Class<? extends B>, B> delegate;
private ImmutableClassToInstanceMap(
ImmutableMap<Class<? extends B>, B> delegate) {
this.delegate = delegate;
}
@Override protected Map<Class<? extends B>, B> delegate() {
return delegate;
}
@Override
@SuppressWarnings("unchecked") // value could not get in if not a T
public <T extends B> T getInstance(Class<T> type) {
return (T) delegate.get(type);
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public <T extends B> T putInstance(Class<T> type, T value) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* 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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2.TransformedCollection;
import com.google.common.collect.Table.Cell;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static methods that involve a {@code Table}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Tables">
* {@code Tables}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 7.0
*/
@GwtCompatible
public final class Tables {
private Tables() {}
/**
* Returns an immutable cell with the specified row key, column key, and
* value.
*
* <p>The returned cell is serializable.
*
* @param rowKey the row key to be associated with the returned cell
* @param columnKey the column key to be associated with the returned cell
* @param value the value to be associated with the returned cell
*/
public static <R, C, V> Cell<R, C, V> immutableCell(
@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) {
return new ImmutableCell<R, C, V>(rowKey, columnKey, value);
}
static final class ImmutableCell<R, C, V>
extends AbstractCell<R, C, V> implements Serializable {
private final R rowKey;
private final C columnKey;
private final V value;
ImmutableCell(
@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) {
this.rowKey = rowKey;
this.columnKey = columnKey;
this.value = value;
}
@Override
public R getRowKey() {
return rowKey;
}
@Override
public C getColumnKey() {
return columnKey;
}
@Override
public V getValue() {
return value;
}
private static final long serialVersionUID = 0;
}
abstract static class AbstractCell<R, C, V> implements Cell<R, C, V> {
// needed for serialization
AbstractCell() {}
@Override public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Cell) {
Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj;
return Objects.equal(getRowKey(), other.getRowKey())
&& Objects.equal(getColumnKey(), other.getColumnKey())
&& Objects.equal(getValue(), other.getValue());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(getRowKey(), getColumnKey(), getValue());
}
@Override public String toString() {
return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue();
}
}
/**
* Creates a transposed view of a given table that flips its row and column
* keys. In other words, calling {@code get(columnKey, rowKey)} on the
* generated table always returns the same value as calling {@code
* get(rowKey, columnKey)} on the original table. Updating the original table
* changes the contents of the transposed table and vice versa.
*
* <p>The returned table supports update operations as long as the input table
* supports the analogous operation with swapped rows and columns. For
* example, in a {@link HashBasedTable} instance, {@code
* rowKeySet().iterator()} supports {@code remove()} but {@code
* columnKeySet().iterator()} doesn't. With a transposed {@link
* HashBasedTable}, it's the other way around.
*/
public static <R, C, V> Table<C, R, V> transpose(Table<R, C, V> table) {
return (table instanceof TransposeTable)
? ((TransposeTable<R, C, V>) table).original
: new TransposeTable<C, R, V>(table);
}
private static class TransposeTable<C, R, V> implements Table<C, R, V> {
final Table<R, C, V> original;
TransposeTable(Table<R, C, V> original) {
this.original = checkNotNull(original);
}
@Override
public void clear() {
original.clear();
}
@Override
public Map<C, V> column(R columnKey) {
return original.row(columnKey);
}
@Override
public Set<R> columnKeySet() {
return original.rowKeySet();
}
@Override
public Map<R, Map<C, V>> columnMap() {
return original.rowMap();
}
@Override
public boolean contains(
@Nullable Object rowKey, @Nullable Object columnKey) {
return original.contains(columnKey, rowKey);
}
@Override
public boolean containsColumn(@Nullable Object columnKey) {
return original.containsRow(columnKey);
}
@Override
public boolean containsRow(@Nullable Object rowKey) {
return original.containsColumn(rowKey);
}
@Override
public boolean containsValue(@Nullable Object value) {
return original.containsValue(value);
}
@Override
public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
return original.get(columnKey, rowKey);
}
@Override
public boolean isEmpty() {
return original.isEmpty();
}
@Override
public V put(C rowKey, R columnKey, V value) {
return original.put(columnKey, rowKey, value);
}
@Override
public void putAll(Table<? extends C, ? extends R, ? extends V> table) {
original.putAll(transpose(table));
}
@Override
public V remove(@Nullable Object rowKey, @Nullable Object columnKey) {
return original.remove(columnKey, rowKey);
}
@Override
public Map<R, V> row(C rowKey) {
return original.column(rowKey);
}
@Override
public Set<C> rowKeySet() {
return original.columnKeySet();
}
@Override
public Map<C, Map<R, V>> rowMap() {
return original.columnMap();
}
@Override
public int size() {
return original.size();
}
@Override
public Collection<V> values() {
return original.values();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Table) {
Table<?, ?, ?> other = (Table<?, ?, ?>) obj;
return cellSet().equals(other.cellSet());
}
return false;
}
@Override public int hashCode() {
return cellSet().hashCode();
}
@Override public String toString() {
return rowMap().toString();
}
// Will cast TRANSPOSE_CELL to a type that always succeeds
private static final Function<Cell<?, ?, ?>, Cell<?, ?, ?>> TRANSPOSE_CELL =
new Function<Cell<?, ?, ?>, Cell<?, ?, ?>>() {
@Override
public Cell<?, ?, ?> apply(Cell<?, ?, ?> cell) {
return immutableCell(
cell.getColumnKey(), cell.getRowKey(), cell.getValue());
}
};
CellSet cellSet;
@Override
public Set<Cell<C, R, V>> cellSet() {
CellSet result = cellSet;
return (result == null) ? cellSet = new CellSet() : result;
}
class CellSet extends TransformedCollection<Cell<R, C, V>, Cell<C, R, V>>
implements Set<Cell<C, R, V>> {
// Casting TRANSPOSE_CELL to a type that always succeeds
@SuppressWarnings("unchecked")
CellSet() {
super(original.cellSet(), (Function) TRANSPOSE_CELL);
}
@Override public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Set)) {
return false;
}
Set<?> os = (Set<?>) obj;
if (os.size() != size()) {
return false;
}
return containsAll(os);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override public boolean contains(Object obj) {
if (obj instanceof Cell) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
return original.cellSet().contains(immutableCell(
cell.getColumnKey(), cell.getRowKey(), cell.getValue()));
}
return false;
}
@Override public boolean remove(Object obj) {
if (obj instanceof Cell) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
return original.cellSet().remove(immutableCell(
cell.getColumnKey(), cell.getRowKey(), cell.getValue()));
}
return false;
}
}
}
/**
* Creates a table that uses the specified backing map and factory. It can
* generate a table based on arbitrary {@link Map} classes.
*
* <p>The {@code factory}-generated and {@code backingMap} classes determine
* the table iteration order. However, the table's {@code row()} method
* returns instances of a different class than {@code factory.get()} does.
*
* <p>Call this method only when the simpler factory methods in classes like
* {@link HashBasedTable} and {@link TreeBasedTable} won't suffice.
*
* <p>The views returned by the {@code Table} methods {@link Table#column},
* {@link Table#columnKeySet}, and {@link Table#columnMap} have iterators that
* don't support {@code remove()}. Otherwise, all optional operations are
* supported. Null row keys, columns keys, and values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because
* the data is stored in a {@code Map<R, Map<C, V>>}. A method call like
* {@code column(columnKey).get(rowKey)} still runs quickly, since the row key
* is provided. However, {@code column(columnKey).size()} takes longer, since
* an iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access this table concurrently and one of the threads modifies the table,
* it must be synchronized externally.
*
* <p>The table is serializable if {@code backingMap}, {@code factory}, the
* maps generated by {@code factory}, and the table contents are all
* serializable.
*
* <p>Note: the table assumes complete ownership over of {@code backingMap}
* and the maps returned by {@code factory}. Those objects should not be
* manually updated and they should not use soft, weak, or phantom references.
*
* @param backingMap place to store the mapping from each row key to its
* corresponding column key / value map
* @param factory supplier of new, empty maps that will each hold all column
* key / value mappings for a given row key
* @throws IllegalArgumentException if {@code backingMap} is not empty
* @since 10.0
*/
@Beta
public static <R, C, V> Table<R, C, V> newCustomTable(
Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
checkArgument(backingMap.isEmpty());
checkNotNull(factory);
// TODO(jlevy): Wrap factory to validate that the supplied maps are empty?
return new StandardTable<R, C, V>(backingMap, factory);
}
/**
* Returns a view of a table where each value is transformed by a function.
* All other properties of the table, such as iteration order, are left
* intact.
*
* <p>Changes in the underlying table are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying table.
*
* <p>It's acceptable for the underlying table to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed table might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned table is not thread-safe or serializable, even if the
* underlying table is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned table to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Table#containsValue} and
* {@code Table.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned table doesn't need to
* be a view, copy the returned table into a new table of your choosing.
*
* @since 10.0
*/
@Beta
public static <R, C, V1, V2> Table<R, C, V2> transformValues(
Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
return new TransformedTable<R, C, V1, V2>(fromTable, function);
}
private static class TransformedTable<R, C, V1, V2>
implements Table<R, C, V2> {
final Table<R, C, V1> fromTable;
final Function<? super V1, V2> function;
TransformedTable(
Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
this.fromTable = checkNotNull(fromTable);
this.function = checkNotNull(function);
}
@Override public boolean contains(Object rowKey, Object columnKey) {
return fromTable.contains(rowKey, columnKey);
}
@Override public boolean containsRow(Object rowKey) {
return fromTable.containsRow(rowKey);
}
@Override public boolean containsColumn(Object columnKey) {
return fromTable.containsColumn(columnKey);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
@Override public V2 get(Object rowKey, Object columnKey) {
// The function is passed a null input only when the table contains a null
// value.
return contains(rowKey, columnKey)
? function.apply(fromTable.get(rowKey, columnKey)) : null;
}
@Override public boolean isEmpty() {
return fromTable.isEmpty();
}
@Override public int size() {
return fromTable.size();
}
@Override public void clear() {
fromTable.clear();
}
@Override public V2 put(R rowKey, C columnKey, V2 value) {
throw new UnsupportedOperationException();
}
@Override public void putAll(
Table<? extends R, ? extends C, ? extends V2> table) {
throw new UnsupportedOperationException();
}
@Override public V2 remove(Object rowKey, Object columnKey) {
return contains(rowKey, columnKey)
? function.apply(fromTable.remove(rowKey, columnKey)) : null;
}
@Override public Map<C, V2> row(R rowKey) {
return Maps.transformValues(fromTable.row(rowKey), function);
}
@Override public Map<R, V2> column(C columnKey) {
return Maps.transformValues(fromTable.column(columnKey), function);
}
Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() {
return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() {
@Override public Cell<R, C, V2> apply(Cell<R, C, V1> cell) {
return immutableCell(
cell.getRowKey(), cell.getColumnKey(),
function.apply(cell.getValue()));
}
};
}
class CellSet extends TransformedCollection<Cell<R, C, V1>, Cell<R, C, V2>>
implements Set<Cell<R, C, V2>> {
CellSet() {
super(fromTable.cellSet(), cellFunction());
}
@Override public boolean equals(Object obj) {
return Sets.equalsImpl(this, obj);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override public boolean contains(Object obj) {
if (obj instanceof Cell) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
if (!Objects.equal(
cell.getValue(), get(cell.getRowKey(), cell.getColumnKey()))) {
return false;
}
return cell.getValue() != null
|| fromTable.contains(cell.getRowKey(), cell.getColumnKey());
}
return false;
}
@Override public boolean remove(Object obj) {
if (contains(obj)) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
fromTable.remove(cell.getRowKey(), cell.getColumnKey());
return true;
}
return false;
}
}
CellSet cellSet;
@Override public Set<Cell<R, C, V2>> cellSet() {
return (cellSet == null) ? cellSet = new CellSet() : cellSet;
}
@Override public Set<R> rowKeySet() {
return fromTable.rowKeySet();
}
@Override public Set<C> columnKeySet() {
return fromTable.columnKeySet();
}
Collection<V2> values;
@Override public Collection<V2> values() {
return (values == null)
? values = Collections2.transform(fromTable.values(), function)
: values;
}
Map<R, Map<C, V2>> createRowMap() {
Function<Map<C, V1>, Map<C, V2>> rowFunction =
new Function<Map<C, V1>, Map<C, V2>>() {
@Override public Map<C, V2> apply(Map<C, V1> row) {
return Maps.transformValues(row, function);
}
};
return Maps.transformValues(fromTable.rowMap(), rowFunction);
}
Map<R, Map<C, V2>> rowMap;
@Override public Map<R, Map<C, V2>> rowMap() {
return (rowMap == null) ? rowMap = createRowMap() : rowMap;
}
Map<C, Map<R, V2>> createColumnMap() {
Function<Map<R, V1>, Map<R, V2>> columnFunction =
new Function<Map<R, V1>, Map<R, V2>>() {
@Override public Map<R, V2> apply(Map<R, V1> column) {
return Maps.transformValues(column, function);
}
};
return Maps.transformValues(fromTable.columnMap(), columnFunction);
}
Map<C, Map<R, V2>> columnMap;
@Override public Map<C, Map<R, V2>> columnMap() {
return (columnMap == null) ? columnMap = createColumnMap() : columnMap;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Table) {
Table<?, ?, ?> other = (Table<?, ?, ?>) obj;
return cellSet().equals(other.cellSet());
}
return false;
}
@Override public int hashCode() {
return cellSet().hashCode();
}
@Override public String toString() {
return rowMap().toString();
}
}
/**
* Returns an unmodifiable view of the specified table. This method allows modules to provide
* users with "read-only" access to internal tables. Query operations on the returned table
* "read through" to the specified table, and attempts to modify the returned table, whether
* direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change.
*
* @param table
* the table for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified table
* @since 11.0
*/
public static <R, C, V> Table<R, C, V> unmodifiableTable(
Table<? extends R, ? extends C, ? extends V> table) {
return new UnmodifiableTable<R, C, V>(table);
}
private static class UnmodifiableTable<R, C, V>
extends ForwardingTable<R, C, V> implements Serializable {
final Table<? extends R, ? extends C, ? extends V> delegate;
UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) {
this.delegate = checkNotNull(delegate);
}
@SuppressWarnings("unchecked") // safe, covariant cast
@Override
protected Table<R, C, V> delegate() {
return (Table<R, C, V>) delegate;
}
@Override
public Set<Cell<R, C, V>> cellSet() {
return Collections.unmodifiableSet(super.cellSet());
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Map<R, V> column(@Nullable C columnKey) {
return Collections.unmodifiableMap(super.column(columnKey));
}
@Override
public Set<C> columnKeySet() {
return Collections.unmodifiableSet(super.columnKeySet());
}
@Override
public Map<C, Map<R, V>> columnMap() {
Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper));
}
@Override
public V put(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
throw new UnsupportedOperationException();
}
@Override
public V remove(@Nullable Object rowKey, @Nullable Object columnKey) {
throw new UnsupportedOperationException();
}
@Override
public Map<C, V> row(@Nullable R rowKey) {
return Collections.unmodifiableMap(super.row(rowKey));
}
@Override
public Set<R> rowKeySet() {
return Collections.unmodifiableSet(super.rowKeySet());
}
@Override
public Map<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper));
}
@Override
public Collection<V> values() {
return Collections.unmodifiableCollection(super.values());
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable view of the specified row-sorted table. This method allows modules to
* provide users with "read-only" access to internal tables. Query operations on the returned
* table "read through" to the specified table, and attemps to modify the returned table, whether
* direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* @param table the row-sorted table for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified table
* @since 11.0
*/
@Beta
public static <R, C, V> RowSortedTable<R, C, V> unmodifiableRowSortedTable(
RowSortedTable<R, ? extends C, ? extends V> table) {
/*
* It's not ? extends R, because it's technically not covariant in R. Specifically,
* table.rowMap().comparator() could return a comparator that only works for the ? extends R.
* Collections.unmodifiableSortedMap makes the same distinction.
*/
return new UnmodifiableRowSortedMap<R, C, V>(table);
}
static final class UnmodifiableRowSortedMap<R, C, V> extends UnmodifiableTable<R, C, V>
implements RowSortedTable<R, C, V> {
public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) {
super(delegate);
}
@Override
protected RowSortedTable<R, C, V> delegate() {
return (RowSortedTable<R, C, V>) super.delegate();
}
@Override
public SortedMap<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper));
}
@Override
public SortedSet<R> rowKeySet() {
return Collections.unmodifiableSortedSet(delegate().rowKeySet());
}
private static final long serialVersionUID = 0;
}
@SuppressWarnings("unchecked")
private static <K, V> Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() {
return (Function) UNMODIFIABLE_WRAPPER;
}
private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER =
new Function<Map<Object, Object>, Map<Object, Object>>() {
@Override
public Map<Object, Object> apply(Map<Object, Object> input) {
return Collections.unmodifiableMap(input);
}
};
}
| Java |
/*
* 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 static com.google.common.collect.Maps.safeContainsKey;
import static com.google.common.collect.Maps.safeGet;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* {@link Table} implementation backed by a map that associates row keys with
* column key / value secondary maps. This class provides rapid access to
* records by the row key alone or by both keys, but not by just the column key.
*
* <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link
* #columnMap()} have iterators that don't support {@code remove()}. Otherwise,
* all optional operations are supported. Null row keys, columns keys, and
* values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because
* the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code
* column(columnKey).get(rowKey)} still runs quickly, since the row key is
* provided. However, {@code column(columnKey).size()} takes longer, since an
* iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access this table concurrently and one of the threads modifies the table, it
* must be synchronized externally.
*
* @author Jared Levy
*/
@GwtCompatible
class StandardTable<R, C, V> implements Table<R, C, V>, Serializable {
@GwtTransient final Map<R, Map<C, V>> backingMap;
@GwtTransient final Supplier<? extends Map<C, V>> factory;
StandardTable(Map<R, Map<C, V>> backingMap,
Supplier<? extends Map<C, V>> factory) {
this.backingMap = backingMap;
this.factory = factory;
}
// Accessors
@Override public boolean contains(
@Nullable Object rowKey, @Nullable Object columnKey) {
if ((rowKey == null) || (columnKey == null)) {
return false;
}
Map<C, V> map = safeGet(backingMap, rowKey);
return map != null && safeContainsKey(map, columnKey);
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
if (columnKey == null) {
return false;
}
for (Map<C, V> map : backingMap.values()) {
if (safeContainsKey(map, columnKey)) {
return true;
}
}
return false;
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return rowKey != null && safeContainsKey(backingMap, rowKey);
}
@Override public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
for (Map<C, V> map : backingMap.values()) {
if (map.containsValue(value)) {
return true;
}
}
return false;
}
@Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
if ((rowKey == null) || (columnKey == null)) {
return null;
}
Map<C, V> map = safeGet(backingMap, rowKey);
return map == null ? null : safeGet(map, columnKey);
}
@Override public boolean isEmpty() {
return backingMap.isEmpty();
}
@Override public int size() {
int size = 0;
for (Map<C, V> map : backingMap.values()) {
size += map.size();
}
return size;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Table) {
Table<?, ?, ?> other = (Table<?, ?, ?>) obj;
return cellSet().equals(other.cellSet());
}
return false;
}
@Override public int hashCode() {
return cellSet().hashCode();
}
/**
* Returns the string representation {@code rowMap().toString()}.
*/
@Override public String toString() {
return rowMap().toString();
}
// Mutators
@Override public void clear() {
backingMap.clear();
}
private Map<C, V> getOrCreate(R rowKey) {
Map<C, V> map = backingMap.get(rowKey);
if (map == null) {
map = factory.get();
backingMap.put(rowKey, map);
}
return map;
}
@Override public V put(R rowKey, C columnKey, V value) {
checkNotNull(rowKey);
checkNotNull(columnKey);
checkNotNull(value);
return getOrCreate(rowKey).put(columnKey, value);
}
@Override public void putAll(
Table<? extends R, ? extends C, ? extends V> table) {
for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
}
@Override public V remove(
@Nullable Object rowKey, @Nullable Object columnKey) {
if ((rowKey == null) || (columnKey == null)) {
return null;
}
Map<C, V> map = safeGet(backingMap, rowKey);
if (map == null) {
return null;
}
V value = map.remove(columnKey);
if (map.isEmpty()) {
backingMap.remove(rowKey);
}
return value;
}
private Map<R, V> removeColumn(Object column) {
Map<R, V> output = new LinkedHashMap<R, V>();
Iterator<Entry<R, Map<C, V>>> iterator
= backingMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<R, Map<C, V>> entry = iterator.next();
V value = entry.getValue().remove(column);
if (value != null) {
output.put(entry.getKey(), value);
if (entry.getValue().isEmpty()) {
iterator.remove();
}
}
}
return output;
}
private boolean containsMapping(
Object rowKey, Object columnKey, Object value) {
return value != null && value.equals(get(rowKey, columnKey));
}
/** Remove a row key / column key / value mapping, if present. */
private boolean removeMapping(Object rowKey, Object columnKey, Object value) {
if (containsMapping(rowKey, columnKey, value)) {
remove(rowKey, columnKey);
return true;
}
return false;
}
// Views
/**
* Abstract collection whose {@code isEmpty()} returns whether the table is
* empty and whose {@code clear()} clears all table mappings.
*/
private abstract class TableCollection<T> extends AbstractCollection<T> {
@Override public boolean isEmpty() {
return backingMap.isEmpty();
}
@Override public void clear() {
backingMap.clear();
}
}
/**
* Abstract set whose {@code isEmpty()} returns whether the table is empty and
* whose {@code clear()} clears all table mappings.
*/
private abstract class TableSet<T> extends AbstractSet<T> {
@Override public boolean isEmpty() {
return backingMap.isEmpty();
}
@Override public void clear() {
backingMap.clear();
}
}
private transient CellSet cellSet;
/**
* {@inheritDoc}
*
* <p>The set's iterator traverses the mappings for the first row, the
* mappings for the second row, and so on.
*
* <p>Each cell is an immutable snapshot of a row key / column key / value
* mapping, taken at the time the cell is returned by a method call to the
* set or its iterator.
*/
@Override public Set<Cell<R, C, V>> cellSet() {
CellSet result = cellSet;
return (result == null) ? cellSet = new CellSet() : result;
}
private class CellSet extends TableSet<Cell<R, C, V>> {
@Override public Iterator<Cell<R, C, V>> iterator() {
return new CellIterator();
}
@Override public int size() {
return StandardTable.this.size();
}
@Override public boolean contains(Object obj) {
if (obj instanceof Cell) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
return containsMapping(
cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
return false;
}
@Override public boolean remove(Object obj) {
if (obj instanceof Cell) {
Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
return removeMapping(
cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
return false;
}
}
private class CellIterator implements Iterator<Cell<R, C, V>> {
final Iterator<Entry<R, Map<C, V>>> rowIterator
= backingMap.entrySet().iterator();
Entry<R, Map<C, V>> rowEntry;
Iterator<Entry<C, V>> columnIterator
= Iterators.emptyModifiableIterator();
@Override public boolean hasNext() {
return rowIterator.hasNext() || columnIterator.hasNext();
}
@Override public Cell<R, C, V> next() {
if (!columnIterator.hasNext()) {
rowEntry = rowIterator.next();
columnIterator = rowEntry.getValue().entrySet().iterator();
}
Entry<C, V> columnEntry = columnIterator.next();
return Tables.immutableCell(
rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue());
}
@Override public void remove() {
columnIterator.remove();
if (rowEntry.getValue().isEmpty()) {
rowIterator.remove();
}
}
}
@Override public Map<C, V> row(R rowKey) {
return new Row(rowKey);
}
class Row extends AbstractMap<C, V> {
final R rowKey;
Row(R rowKey) {
this.rowKey = checkNotNull(rowKey);
}
Map<C, V> backingRowMap;
Map<C, V> backingRowMap() {
return (backingRowMap == null
|| (backingRowMap.isEmpty() && backingMap.containsKey(rowKey)))
? backingRowMap = computeBackingRowMap()
: backingRowMap;
}
Map<C, V> computeBackingRowMap() {
return backingMap.get(rowKey);
}
// Call this every time we perform a removal.
void maintainEmptyInvariant() {
if (backingRowMap() != null && backingRowMap.isEmpty()) {
backingMap.remove(rowKey);
backingRowMap = null;
}
}
@Override
public boolean containsKey(Object key) {
Map<C, V> backingRowMap = backingRowMap();
return (key != null && backingRowMap != null)
&& Maps.safeContainsKey(backingRowMap, key);
}
@Override
public V get(Object key) {
Map<C, V> backingRowMap = backingRowMap();
return (key != null && backingRowMap != null)
? Maps.safeGet(backingRowMap, key)
: null;
}
@Override
public V put(C key, V value) {
checkNotNull(key);
checkNotNull(value);
if (backingRowMap != null && !backingRowMap.isEmpty()) {
return backingRowMap.put(key, value);
}
return StandardTable.this.put(rowKey, key, value);
}
@Override
public V remove(Object key) {
try {
Map<C, V> backingRowMap = backingRowMap();
if (backingRowMap == null) {
return null;
}
V result = backingRowMap.remove(key);
maintainEmptyInvariant();
return result;
} catch (ClassCastException e) {
return null;
}
}
@Override
public void clear() {
Map<C, V> backingRowMap = backingRowMap();
if (backingRowMap != null) {
backingRowMap.clear();
}
maintainEmptyInvariant();
}
Set<C> keySet;
@Override
public Set<C> keySet() {
Set<C> result = keySet;
if (result == null) {
return keySet = new Maps.KeySet<C, V>() {
@Override
Map<C, V> map() {
return Row.this;
}
};
}
return result;
}
Set<Entry<C, V>> entrySet;
@Override
public Set<Entry<C, V>> entrySet() {
Set<Entry<C, V>> result = entrySet;
if (result == null) {
return entrySet = new RowEntrySet();
}
return result;
}
private class RowEntrySet extends Maps.EntrySet<C, V> {
@Override
Map<C, V> map() {
return Row.this;
}
@Override
public int size() {
Map<C, V> map = backingRowMap();
return (map == null) ? 0 : map.size();
}
@Override
public Iterator<Entry<C, V>> iterator() {
final Map<C, V> map = backingRowMap();
if (map == null) {
return Iterators.emptyModifiableIterator();
}
final Iterator<Entry<C, V>> iterator = map.entrySet().iterator();
return new Iterator<Entry<C, V>>() {
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public Entry<C, V> next() {
final Entry<C, V> entry = iterator.next();
return new ForwardingMapEntry<C, V>() {
@Override protected Entry<C, V> delegate() {
return entry;
}
@Override public V setValue(V value) {
return super.setValue(checkNotNull(value));
}
@Override
public boolean equals(Object object) {
// TODO(user): identify why this affects GWT tests
return standardEquals(object);
}
};
}
@Override
public void remove() {
iterator.remove();
maintainEmptyInvariant();
}
};
}
}
}
/**
* {@inheritDoc}
*
* <p>The returned map's views have iterators that don't support
* {@code remove()}.
*/
@Override public Map<R, V> column(C columnKey) {
return new Column(columnKey);
}
private class Column extends Maps.ImprovedAbstractMap<R, V> {
final C columnKey;
Column(C columnKey) {
this.columnKey = checkNotNull(columnKey);
}
@Override public V put(R key, V value) {
return StandardTable.this.put(key, columnKey, value);
}
@Override public V get(Object key) {
return StandardTable.this.get(key, columnKey);
}
@Override public boolean containsKey(Object key) {
return StandardTable.this.contains(key, columnKey);
}
@Override public V remove(Object key) {
return StandardTable.this.remove(key, columnKey);
}
@Override public Set<Entry<R, V>> createEntrySet() {
return new EntrySet();
}
Values columnValues;
@Override public Collection<V> values() {
Values result = columnValues;
return (result == null) ? columnValues = new Values() : result;
}
/**
* Removes all {@code Column} mappings whose row key and value satisfy the
* given predicate.
*/
boolean removePredicate(Predicate<? super Entry<R, V>> predicate) {
boolean changed = false;
Iterator<Entry<R, Map<C, V>>> iterator
= backingMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<R, Map<C, V>> entry = iterator.next();
Map<C, V> map = entry.getValue();
V value = map.get(columnKey);
if (value != null
&& predicate.apply(
new ImmutableEntry<R, V>(entry.getKey(), value))) {
map.remove(columnKey);
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
class EntrySet extends Sets.ImprovedAbstractSet<Entry<R, V>> {
@Override public Iterator<Entry<R, V>> iterator() {
return new EntrySetIterator();
}
@Override public int size() {
int size = 0;
for (Map<C, V> map : backingMap.values()) {
if (map.containsKey(columnKey)) {
size++;
}
}
return size;
}
@Override public boolean isEmpty() {
return !containsColumn(columnKey);
}
@Override public void clear() {
Predicate<Entry<R, V>> predicate = Predicates.alwaysTrue();
removePredicate(predicate);
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return containsMapping(entry.getKey(), columnKey, entry.getValue());
}
return false;
}
@Override public boolean remove(Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return removeMapping(entry.getKey(), columnKey, entry.getValue());
}
return false;
}
@Override public boolean retainAll(Collection<?> c) {
return removePredicate(Predicates.not(Predicates.in(c)));
}
}
class EntrySetIterator extends AbstractIterator<Entry<R, V>> {
final Iterator<Entry<R, Map<C, V>>> iterator
= backingMap.entrySet().iterator();
@Override protected Entry<R, V> computeNext() {
while (iterator.hasNext()) {
final Entry<R, Map<C, V>> entry = iterator.next();
if (entry.getValue().containsKey(columnKey)) {
return new AbstractMapEntry<R, V>() {
@Override public R getKey() {
return entry.getKey();
}
@Override public V getValue() {
return entry.getValue().get(columnKey);
}
@Override public V setValue(V value) {
return entry.getValue().put(columnKey, checkNotNull(value));
}
};
}
}
return endOfData();
}
}
KeySet keySet;
@Override public Set<R> keySet() {
KeySet result = keySet;
return result == null ? keySet = new KeySet() : result;
}
class KeySet extends Sets.ImprovedAbstractSet<R> {
@Override public Iterator<R> iterator() {
return Maps.keyIterator(Column.this.entrySet().iterator());
}
@Override public int size() {
return entrySet().size();
}
@Override public boolean isEmpty() {
return !containsColumn(columnKey);
}
@Override public boolean contains(Object obj) {
return StandardTable.this.contains(obj, columnKey);
}
@Override public boolean remove(Object obj) {
return StandardTable.this.remove(obj, columnKey) != null;
}
@Override public void clear() {
entrySet().clear();
}
@Override public boolean retainAll(final Collection<?> c) {
checkNotNull(c);
Predicate<Entry<R, V>> predicate = new Predicate<Entry<R, V>>() {
@Override
public boolean apply(Entry<R, V> entry) {
return !c.contains(entry.getKey());
}
};
return removePredicate(predicate);
}
}
class Values extends AbstractCollection<V> {
@Override public Iterator<V> iterator() {
return Maps.valueIterator(Column.this.entrySet().iterator());
}
@Override public int size() {
return entrySet().size();
}
@Override public boolean isEmpty() {
return !containsColumn(columnKey);
}
@Override public void clear() {
entrySet().clear();
}
@Override public boolean remove(Object obj) {
if (obj == null) {
return false;
}
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
if (map.entrySet().remove(
new ImmutableEntry<C, Object>(columnKey, obj))) {
if (map.isEmpty()) {
iterator.remove();
}
return true;
}
}
return false;
}
@Override public boolean removeAll(final Collection<?> c) {
checkNotNull(c);
Predicate<Entry<R, V>> predicate = new Predicate<Entry<R, V>>() {
@Override
public boolean apply(Entry<R, V> entry) {
return c.contains(entry.getValue());
}
};
return removePredicate(predicate);
}
@Override public boolean retainAll(final Collection<?> c) {
checkNotNull(c);
Predicate<Entry<R, V>> predicate = new Predicate<Entry<R, V>>() {
@Override
public boolean apply(Entry<R, V> entry) {
return !c.contains(entry.getValue());
}
};
return removePredicate(predicate);
}
}
}
private transient RowKeySet rowKeySet;
@Override public Set<R> rowKeySet() {
Set<R> result = rowKeySet;
return (result == null) ? rowKeySet = new RowKeySet() : result;
}
class RowKeySet extends TableSet<R> {
@Override public Iterator<R> iterator() {
return Maps.keyIterator(rowMap().entrySet().iterator());
}
@Override public int size() {
return backingMap.size();
}
@Override public boolean contains(Object obj) {
return containsRow(obj);
}
@Override public boolean remove(Object obj) {
return (obj != null) && backingMap.remove(obj) != null;
}
}
private transient Set<C> columnKeySet;
/**
* {@inheritDoc}
*
* <p>The returned set has an iterator that does not support {@code remove()}.
*
* <p>The set's iterator traverses the columns of the first row, the
* columns of the second row, etc., skipping any columns that have
* appeared previously.
*/
@Override
public Set<C> columnKeySet() {
Set<C> result = columnKeySet;
return (result == null) ? columnKeySet = new ColumnKeySet() : result;
}
private class ColumnKeySet extends TableSet<C> {
@Override public Iterator<C> iterator() {
return createColumnKeyIterator();
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean remove(Object obj) {
if (obj == null) {
return false;
}
boolean changed = false;
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
if (map.keySet().remove(obj)) {
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override public boolean removeAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
// map.keySet().removeAll(c) can throw a NPE when map is a TreeMap with
// natural ordering and c contains a null.
if (Iterators.removeAll(map.keySet().iterator(), c)) {
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
if (map.keySet().retainAll(c)) {
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override public boolean contains(Object obj) {
if (obj == null) {
return false;
}
for (Map<C, V> map : backingMap.values()) {
if (map.containsKey(obj)) {
return true;
}
}
return false;
}
}
/**
* Creates an iterator that returns each column value with duplicates
* omitted.
*/
Iterator<C> createColumnKeyIterator() {
return new ColumnKeyIterator();
}
private class ColumnKeyIterator extends AbstractIterator<C> {
// Use the same map type to support TreeMaps with comparators that aren't
// consistent with equals().
final Map<C, V> seen = factory.get();
final Iterator<Map<C, V>> mapIterator = backingMap.values().iterator();
Iterator<Entry<C, V>> entryIterator = Iterators.emptyIterator();
@Override protected C computeNext() {
while (true) {
if (entryIterator.hasNext()) {
Entry<C, V> entry = entryIterator.next();
if (!seen.containsKey(entry.getKey())) {
seen.put(entry.getKey(), entry.getValue());
return entry.getKey();
}
} else if (mapIterator.hasNext()) {
entryIterator = mapIterator.next().entrySet().iterator();
} else {
return endOfData();
}
}
}
}
private transient Values values;
/**
* {@inheritDoc}
*
* <p>The collection's iterator traverses the values for the first row,
* the values for the second row, and so on.
*/
@Override public Collection<V> values() {
Values result = values;
return (result == null) ? values = new Values() : result;
}
private class Values extends TableCollection<V> {
@Override public Iterator<V> iterator() {
return new TransformedIterator<Cell<R, C, V>, V>(cellSet().iterator()) {
@Override
V transform(Cell<R, C, V> cell) {
return cell.getValue();
}
};
}
@Override public int size() {
return StandardTable.this.size();
}
}
private transient RowMap rowMap;
@Override public Map<R, Map<C, V>> rowMap() {
RowMap result = rowMap;
return (result == null) ? rowMap = new RowMap() : result;
}
class RowMap extends Maps.ImprovedAbstractMap<R, Map<C, V>> {
@Override public boolean containsKey(Object key) {
return containsRow(key);
}
// performing cast only when key is in backing map and has the correct type
@SuppressWarnings("unchecked")
@Override public Map<C, V> get(Object key) {
return containsRow(key) ? row((R) key) : null;
}
@Override public Set<R> keySet() {
return rowKeySet();
}
@Override public Map<C, V> remove(Object key) {
return (key == null) ? null : backingMap.remove(key);
}
@Override protected Set<Entry<R, Map<C, V>>> createEntrySet() {
return new EntrySet();
}
class EntrySet extends TableSet<Entry<R, Map<C, V>>> {
@Override public Iterator<Entry<R, Map<C, V>>> iterator() {
return new TransformedIterator<R, Entry<R, Map<C, V>>>(
backingMap.keySet().iterator()) {
@Override
Entry<R, Map<C, V>> transform(R rowKey) {
return new ImmutableEntry<R, Map<C, V>>(rowKey, row(rowKey));
}
};
}
@Override public int size() {
return backingMap.size();
}
@Override public boolean contains(Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return entry.getKey() != null
&& entry.getValue() instanceof Map
&& Collections2.safeContains(backingMap.entrySet(), entry);
}
return false;
}
@Override public boolean remove(Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return entry.getKey() != null
&& entry.getValue() instanceof Map
&& backingMap.entrySet().remove(entry);
}
return false;
}
}
}
private transient ColumnMap columnMap;
@Override public Map<C, Map<R, V>> columnMap() {
ColumnMap result = columnMap;
return (result == null) ? columnMap = new ColumnMap() : result;
}
private class ColumnMap extends Maps.ImprovedAbstractMap<C, Map<R, V>> {
// The cast to C occurs only when the key is in the map, implying that it
// has the correct type.
@SuppressWarnings("unchecked")
@Override public Map<R, V> get(Object key) {
return containsColumn(key) ? column((C) key) : null;
}
@Override public boolean containsKey(Object key) {
return containsColumn(key);
}
@Override public Map<R, V> remove(Object key) {
return containsColumn(key) ? removeColumn(key) : null;
}
@Override public Set<Entry<C, Map<R, V>>> createEntrySet() {
return new ColumnMapEntrySet();
}
@Override public Set<C> keySet() {
return columnKeySet();
}
ColumnMapValues columnMapValues;
@Override public Collection<Map<R, V>> values() {
ColumnMapValues result = columnMapValues;
return
(result == null) ? columnMapValues = new ColumnMapValues() : result;
}
class ColumnMapEntrySet extends TableSet<Entry<C, Map<R, V>>> {
@Override public Iterator<Entry<C, Map<R, V>>> iterator() {
return new TransformedIterator<C, Entry<C, Map<R, V>>>(
columnKeySet().iterator()) {
@Override
Entry<C, Map<R, V>> transform(C columnKey) {
return new ImmutableEntry<C, Map<R, V>>(
columnKey, column(columnKey));
}
};
}
@Override public int size() {
return columnKeySet().size();
}
@Override public boolean contains(Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
if (containsColumn(entry.getKey())) {
// The cast to C occurs only when the key is in the map, implying
// that it has the correct type.
@SuppressWarnings("unchecked")
C columnKey = (C) entry.getKey();
return get(columnKey).equals(entry.getValue());
}
}
return false;
}
@Override public boolean remove(Object obj) {
if (contains(obj)) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
removeColumn(entry.getKey());
return true;
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
boolean changed = false;
for (Object obj : c) {
changed |= remove(obj);
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
boolean changed = false;
for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
if (!c.contains(new ImmutableEntry<C, Map<R, V>>(
columnKey, column(columnKey)))) {
removeColumn(columnKey);
changed = true;
}
}
return changed;
}
}
private class ColumnMapValues extends TableCollection<Map<R, V>> {
@Override public Iterator<Map<R, V>> iterator() {
return Maps.valueIterator(ColumnMap.this.entrySet().iterator());
}
@Override public boolean remove(Object obj) {
for (Entry<C, Map<R, V>> entry : ColumnMap.this.entrySet()) {
if (entry.getValue().equals(obj)) {
removeColumn(entry.getKey());
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
if (c.contains(column(columnKey))) {
removeColumn(columnKey);
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
if (!c.contains(column(columnKey))) {
removeColumn(columnKey);
changed = true;
}
}
return changed;
}
@Override public int size() {
return columnKeySet().size();
}
}
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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;
/**
* "Overrides" the {@link ImmutableMultiset} static methods that lack
* {@link ImmutableSortedMultiset} equivalents with deprecated, exception-throwing versions. This
* prevents accidents like the following:
*
* <pre> {@code
*
* List<Object> objects = ...;
* // Sort them:
* Set<Object> sorted = ImmutableSortedMultiset.copyOf(objects);
* // BAD CODE! The returned multiset is actually an unsorted ImmutableMultiset!}</pre>
*
* While we could put the overrides in {@link ImmutableSortedMultiset} itself, it seems clearer to
* separate these "do not call" methods from those intended for normal use.
*
* @author Louis Wasserman
*/
abstract class ImmutableSortedMultisetFauxverideShim<E> extends ImmutableMultiset<E> {
/**
* Not supported. Use {@link ImmutableSortedMultiset#naturalOrder}, which offers better
* type-safety, instead. This method exists only to hide {@link ImmutableMultiset#builder} from
* consumers of {@code ImmutableSortedMultiset}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedMultiset#naturalOrder}, which offers better type-safety.
*/
@Deprecated
public static <E> ImmutableSortedMultiset.Builder<E> builder() {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain a non-{@code
* Comparable} element.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass a parameter of type {@code Comparable} to use
* {@link ImmutableSortedMultiset#of(Comparable)}.</b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> of(E element) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain a non-{@code
* Comparable} element.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use
* {@link ImmutableSortedMultiset#of(Comparable, Comparable)}.</b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> of(E e1, E e2) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain a non-{@code
* Comparable} element.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use
* {@link ImmutableSortedMultiset#of(Comparable, Comparable, Comparable)}.</b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain a non-{@code
* Comparable} element.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable)}. </b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3, E e4) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain a non-{@code
* Comparable} element.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable,
* Comparable)} . </b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain a non-{@code
* Comparable} element.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable,
* Comparable, Comparable, Comparable...)} . </b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> of(
E e1,
E e2,
E e3,
E e4,
E e5,
E e6,
E... remaining) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a multiset that may contain non-{@code
* Comparable} elements.</b> Proper calls will resolve to the version in {@code
* ImmutableSortedMultiset}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass parameters of type {@code Comparable} to use
* {@link ImmutableSortedMultiset#copyOf(Comparable[])}.</b>
*/
@Deprecated
public static <E> ImmutableSortedMultiset<E> copyOf(E[] elements) {
throw new UnsupportedOperationException();
}
/*
* We would like to include an unsupported "<E> copyOf(Iterable<E>)" here, providing only the
* properly typed "<E extends Comparable<E>> copyOf(Iterable<E>)" in ImmutableSortedMultiset (and
* likewise for the Iterator equivalent). However, due to a change in Sun's interpretation of the
* JLS (as described at http://bugs.sun.com/view_bug.do?bug_id=6182950), the OpenJDK 7 compiler
* available as of this writing rejects our attempts. To maintain compatibility with that version
* and with any other compilers that interpret the JLS similarly, there is no definition of
* copyOf() here, and the definition in ImmutableSortedMultiset matches that in
* ImmutableMultiset.
*
* The result is that ImmutableSortedMultiset.copyOf() may be called on non-Comparable elements.
* We have not discovered a better solution. In retrospect, the static factory methods should
* have gone in a separate class so that ImmutableSortedMultiset wouldn't "inherit"
* too-permissive factory methods from ImmutableMultiset.
*/
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.collect.Maps.EntryTransformer;
import java.lang.reflect.Array;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
class Platform {
/**
* Clone the given array using {@link Object#clone()}. It is factored out so
* that it can be emulated in GWT.
*/
static <T> T[] clone(T[] array) {
return array.clone();
}
/**
* Returns a new array of the given length with the same type as a reference
* array.
*
* @param reference any array of the desired type
* @param length the length of the new array
*/
static <T> T[] newArray(T[] reference, int length) {
Class<?> type = reference.getClass().getComponentType();
// the cast is safe because
// result.getClass() == reference.getClass().getComponentType()
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, length);
return result;
}
/**
* Configures the given map maker to use weak keys, if possible; does nothing
* otherwise (i.e., in GWT). This is sometimes acceptable, when only
* server-side code could generate enough volume that reclamation becomes
* important.
*/
static MapMaker tryWeakKeys(MapMaker mapMaker) {
return mapMaker.weakKeys();
}
static <K, V1, V2> SortedMap<K, V2> mapsTransformEntriesSortedMap(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return (fromMap instanceof NavigableMap)
? Maps.transformEntries((NavigableMap<K, V1>) fromMap, transformer)
: Maps.transformEntriesIgnoreNavigable(fromMap, transformer);
}
static <K, V> SortedMap<K, V> mapsAsMapSortedSet(SortedSet<K> set,
Function<? super K, V> function) {
return (set instanceof NavigableSet)
? Maps.asMap((NavigableSet<K>) set, function)
: Maps.asMapSortedIgnoreNavigable(set, function);
}
private Platform() {}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Comparator;
/** An ordering that tries several comparators in order. */
@GwtCompatible(serializable = true)
final class CompoundOrdering<T> extends Ordering<T> implements Serializable {
final ImmutableList<Comparator<? super T>> comparators;
CompoundOrdering(Comparator<? super T> primary,
Comparator<? super T> secondary) {
this.comparators
= ImmutableList.<Comparator<? super T>>of(primary, secondary);
}
CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) {
this.comparators = ImmutableList.copyOf(comparators);
}
@Override public int compare(T left, T right) {
// Avoid using the Iterator to avoid generating garbage (issue 979).
int size = comparators.size();
for (int i = 0; i < size; i++) {
int result = comparators.get(i).compare(left, right);
if (result != 0) {
return result;
}
}
return 0;
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof CompoundOrdering) {
CompoundOrdering<?> that = (CompoundOrdering<?>) object;
return this.comparators.equals(that.comparators);
}
return false;
}
@Override public int hashCode() {
return comparators.hashCode();
}
@Override public String toString() {
return "Ordering.compound(" + comparators + ")";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.Nullable;
/** An ordering that treats {@code null} as less than all other values. */
@GwtCompatible(serializable = true)
final class NullsFirstOrdering<T> extends Ordering<T> implements Serializable {
final Ordering<? super T> ordering;
NullsFirstOrdering(Ordering<? super T> ordering) {
this.ordering = ordering;
}
@Override public int compare(@Nullable T left, @Nullable T right) {
if (left == right) {
return 0;
}
if (left == null) {
return RIGHT_IS_GREATER;
}
if (right == null) {
return LEFT_IS_GREATER;
}
return ordering.compare(left, right);
}
@Override public <S extends T> Ordering<S> reverse() {
// ordering.reverse() might be optimized, so let it do its thing
return ordering.reverse().nullsLast();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override public <S extends T> Ordering<S> nullsFirst() {
return (Ordering<S>) this;
}
@Override public <S extends T> Ordering<S> nullsLast() {
return ordering.nullsLast();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof NullsFirstOrdering) {
NullsFirstOrdering<?> that = (NullsFirstOrdering<?>) object;
return this.ordering.equals(that.ordering);
}
return false;
}
@Override public int hashCode() {
return ordering.hashCode() ^ 957692532; // meaningless
}
@Override public String toString() {
return ordering + ".nullsFirst()";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A general-purpose bimap implementation using any two backing {@code Map}
* instances.
*
* <p>Note that this class contains {@code equals()} calls that keep it from
* supporting {@code IdentityHashMap} backing maps.
*
* @author Kevin Bourrillion
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
abstract class AbstractBiMap<K, V> extends ForwardingMap<K, V>
implements BiMap<K, V>, Serializable {
private transient Map<K, V> delegate;
transient AbstractBiMap<V, K> inverse;
/** Package-private constructor for creating a map-backed bimap. */
AbstractBiMap(Map<K, V> forward, Map<V, K> backward) {
setDelegates(forward, backward);
}
/** Private constructor for inverse bimap. */
private AbstractBiMap(Map<K, V> backward, AbstractBiMap<V, K> forward) {
delegate = backward;
inverse = forward;
}
@Override protected Map<K, V> delegate() {
return delegate;
}
/**
* Returns its input, or throws an exception if this is not a valid key.
*/
K checkKey(@Nullable K key) {
return key;
}
/**
* Returns its input, or throws an exception if this is not a valid value.
*/
V checkValue(@Nullable V value) {
return value;
}
/**
* Specifies the delegate maps going in each direction. Called by the
* constructor and by subclasses during deserialization.
*/
void setDelegates(Map<K, V> forward, Map<V, K> backward) {
checkState(delegate == null);
checkState(inverse == null);
checkArgument(forward.isEmpty());
checkArgument(backward.isEmpty());
checkArgument(forward != backward);
delegate = forward;
inverse = new Inverse<V, K>(backward, this);
}
void setInverse(AbstractBiMap<V, K> inverse) {
this.inverse = inverse;
}
// Query Operations (optimizations)
@Override public boolean containsValue(Object value) {
return inverse.containsKey(value);
}
// Modification Operations
@Override public V put(K key, V value) {
return putInBothMaps(key, value, false);
}
@Override
public V forcePut(K key, V value) {
return putInBothMaps(key, value, true);
}
private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) {
checkKey(key);
checkValue(value);
boolean containedKey = containsKey(key);
if (containedKey && Objects.equal(value, get(key))) {
return value;
}
if (force) {
inverse().remove(value);
} else {
checkArgument(!containsValue(value), "value already present: %s", value);
}
V oldValue = delegate.put(key, value);
updateInverseMap(key, containedKey, oldValue, value);
return oldValue;
}
private void updateInverseMap(
K key, boolean containedKey, V oldValue, V newValue) {
if (containedKey) {
removeFromInverseMap(oldValue);
}
inverse.delegate.put(newValue, key);
}
@Override public V remove(Object key) {
return containsKey(key) ? removeFromBothMaps(key) : null;
}
private V removeFromBothMaps(Object key) {
V oldValue = delegate.remove(key);
removeFromInverseMap(oldValue);
return oldValue;
}
private void removeFromInverseMap(V oldValue) {
inverse.delegate.remove(oldValue);
}
// Bulk Operations
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override public void clear() {
delegate.clear();
inverse.delegate.clear();
}
// Views
@Override
public BiMap<V, K> inverse() {
return inverse;
}
private transient Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = new KeySet() : result;
}
private class KeySet extends ForwardingSet<K> {
@Override protected Set<K> delegate() {
return delegate.keySet();
}
@Override public void clear() {
AbstractBiMap.this.clear();
}
@Override public boolean remove(Object key) {
if (!contains(key)) {
return false;
}
removeFromBothMaps(key);
return true;
}
@Override public boolean removeAll(Collection<?> keysToRemove) {
return standardRemoveAll(keysToRemove);
}
@Override public boolean retainAll(Collection<?> keysToRetain) {
return standardRetainAll(keysToRetain);
}
@Override public Iterator<K> iterator() {
return Maps.keyIterator(entrySet().iterator());
}
}
private transient Set<V> valueSet;
@Override public Set<V> values() {
/*
* We can almost reuse the inverse's keySet, except we have to fix the
* iteration order so that it is consistent with the forward map.
*/
Set<V> result = valueSet;
return (result == null) ? valueSet = new ValueSet() : result;
}
private class ValueSet extends ForwardingSet<V> {
final Set<V> valuesDelegate = inverse.keySet();
@Override protected Set<V> delegate() {
return valuesDelegate;
}
@Override public Iterator<V> iterator() {
return Maps.valueIterator(entrySet().iterator());
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public String toString() {
return standardToString();
}
}
private transient Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = new EntrySet() : result;
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
final Set<Entry<K, V>> esDelegate = delegate.entrySet();
@Override protected Set<Entry<K, V>> delegate() {
return esDelegate;
}
@Override public void clear() {
AbstractBiMap.this.clear();
}
@Override public boolean remove(Object object) {
if (!esDelegate.contains(object)) {
return false;
}
// safe because esDelgate.contains(object).
Entry<?, ?> entry = (Entry<?, ?>) object;
inverse.delegate.remove(entry.getValue());
/*
* Remove the mapping in inverse before removing from esDelegate because
* if entry is part of esDelegate, entry might be invalidated after the
* mapping is removed from esDelegate.
*/
esDelegate.remove(entry);
return true;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = esDelegate.iterator();
return new Iterator<Entry<K, V>>() {
Entry<K, V> entry;
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public Entry<K, V> next() {
entry = iterator.next();
final Entry<K, V> finalEntry = entry;
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return finalEntry;
}
@Override public V setValue(V value) {
// Preconditions keep the map and inverse consistent.
checkState(contains(this), "entry no longer in map");
// similar to putInBothMaps, but set via entry
if (Objects.equal(value, getValue())) {
return value;
}
checkArgument(!containsValue(value),
"value already present: %s", value);
V oldValue = finalEntry.setValue(value);
checkState(Objects.equal(value, get(getKey())),
"entry no longer in map");
updateInverseMap(getKey(), true, oldValue, value);
return oldValue;
}
};
}
@Override public void remove() {
checkState(entry != null);
V value = entry.getValue();
iterator.remove();
removeFromInverseMap(value);
}
};
}
// See java.util.Collections.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** The inverse of any other {@code AbstractBiMap} subclass. */
private static class Inverse<K, V> extends AbstractBiMap<K, V> {
private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) {
super(backward, forward);
}
/*
* Serialization stores the forward bimap, the inverse of this inverse.
* Deserialization calls inverse() on the forward bimap and returns that
* inverse.
*
* If a bimap and its inverse are serialized together, the deserialized
* instances have inverse() methods that return the other.
*/
@Override
K checkKey(K key) {
return inverse.checkValue(key);
}
@Override
V checkValue(V value) {
return inverse.checkKey(value);
}
/**
* @serialData the forward bimap
*/
@GwtIncompatible("java.io.ObjectOuputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(inverse());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
setInverse((AbstractBiMap<V, K>) stream.readObject());
}
@GwtIncompatible("Not needed in the emulated source.")
Object readResolve() {
return inverse().inverse();
}
@GwtIncompatible("Not needed in emulated source.")
private static final long serialVersionUID = 0;
}
@GwtIncompatible("Not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
* List returned by {@link ImmutableCollection#asList} that delegates {@code contains} checks
* to the backing collection.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial")
abstract class ImmutableAsList<E> extends ImmutableList<E> {
abstract ImmutableCollection<E> delegateCollection();
@Override public boolean contains(Object target) {
// The collection's contains() is at least as fast as ImmutableList's
// and is often faster.
return delegateCollection().contains(target);
}
@Override
public int size() {
return delegateCollection().size();
}
@Override
public boolean isEmpty() {
return delegateCollection().isEmpty();
}
@Override
boolean isPartialView() {
return delegateCollection().isPartialView();
}
/**
* Serialized form that leads to the same performance as the original list.
*/
@GwtIncompatible("serialization")
static class SerializedForm implements Serializable {
final ImmutableCollection<?> collection;
SerializedForm(ImmutableCollection<?> collection) {
this.collection = collection;
}
Object readResolve() {
return collection.asList();
}
private static final long serialVersionUID = 0;
}
@GwtIncompatible("serialization")
private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new SerializedForm(delegateCollection());
}
}
| Java |
/*
* Copyright (C) 2009 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 static com.google.common.collect.SortedLists.KeyAbsentBehavior.INVERTED_INSERTION_INDEX;
import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_HIGHER;
import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT;
import static com.google.common.collect.SortedLists.KeyPresentBehavior.FIRST_AFTER;
import static com.google.common.collect.SortedLists.KeyPresentBehavior.FIRST_PRESENT;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An immutable sorted set with one or more elements. TODO(jlevy): Consider
* separate class for a single-element sorted set.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial")
final class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> {
private transient final ImmutableList<E> elements;
RegularImmutableSortedSet(
ImmutableList<E> elements, Comparator<? super E> comparator) {
super(comparator);
this.elements = elements;
checkArgument(!elements.isEmpty());
}
@Override public UnmodifiableIterator<E> iterator() {
return elements.iterator();
}
@Override public boolean isEmpty() {
return false;
}
@Override
public int size() {
return elements.size();
}
@Override public boolean contains(Object o) {
if (o == null) {
return false;
}
try {
return unsafeBinarySearch(o) >= 0;
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsAll(Collection<?> targets) {
// TODO(jlevy): For optimal performance, use a binary search when
// targets.size() < size() / log(size())
// TODO(kevinb): see if we can share code with OrderedIterator after it
// graduates from labs.
if (!SortedIterables.hasSameComparator(comparator(), targets)
|| (targets.size() <= 1)) {
return super.containsAll(targets);
}
/*
* If targets is a sorted set with the same comparator, containsAll can run
* in O(n) time stepping through the two collections.
*/
Iterator<E> thisIterator = iterator();
Iterator<?> thatIterator = targets.iterator();
Object target = thatIterator.next();
try {
while (thisIterator.hasNext()) {
int cmp = unsafeCompare(thisIterator.next(), target);
if (cmp == 0) {
if (!thatIterator.hasNext()) {
return true;
}
target = thatIterator.next();
} else if (cmp > 0) {
return false;
}
}
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
return false;
}
private int unsafeBinarySearch(Object key) throws ClassCastException {
return Collections.binarySearch(elements, key, unsafeComparator());
}
@Override boolean isPartialView() {
return elements.isPartialView();
}
@Override public Object[] toArray() {
return elements.toArray();
}
@Override public <T> T[] toArray(T[] array) {
return elements.toArray(array);
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Set)) {
return false;
}
Set<?> that = (Set<?>) object;
if (size() != that.size()) {
return false;
}
if (SortedIterables.hasSameComparator(comparator, that)) {
Iterator<?> otherIterator = that.iterator();
try {
Iterator<E> iterator = iterator();
while (iterator.hasNext()) {
Object element = iterator.next();
Object otherElement = otherIterator.next();
if (otherElement == null
|| unsafeCompare(element, otherElement) != 0) {
return false;
}
}
return true;
} catch (ClassCastException e) {
return false;
} catch (NoSuchElementException e) {
return false; // concurrent change to other set
}
}
return this.containsAll(that);
}
@Override
public E first() {
return elements.get(0);
}
@Override
public E last() {
return elements.get(size() - 1);
}
@Override
ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) {
return getSubSet(0, headIndex(toElement, inclusive));
}
int headIndex(E toElement, boolean inclusive) {
return SortedLists.binarySearch(
elements, checkNotNull(toElement), comparator(),
inclusive ? FIRST_AFTER : FIRST_PRESENT, NEXT_HIGHER);
}
@Override
ImmutableSortedSet<E> subSetImpl(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return tailSetImpl(fromElement, fromInclusive)
.headSetImpl(toElement, toInclusive);
}
@Override
ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) {
return getSubSet(tailIndex(fromElement, inclusive), size());
}
int tailIndex(E fromElement, boolean inclusive) {
return SortedLists.binarySearch(
elements,
checkNotNull(fromElement),
comparator(),
inclusive ? FIRST_PRESENT : FIRST_AFTER, NEXT_HIGHER);
}
// Pretend the comparator can compare anything. If it turns out it can't
// compare two elements, it'll throw a CCE. Only methods that are specified to
// throw CCE should call this.
@SuppressWarnings("unchecked")
Comparator<Object> unsafeComparator() {
return (Comparator<Object>) comparator;
}
ImmutableSortedSet<E> getSubSet(int newFromIndex, int newToIndex) {
if (newFromIndex == 0 && newToIndex == size()) {
return this;
} else if (newFromIndex < newToIndex) {
return new RegularImmutableSortedSet<E>(
elements.subList(newFromIndex, newToIndex), comparator);
} else {
return emptySet(comparator);
}
}
@Override int indexOf(@Nullable Object target) {
if (target == null) {
return -1;
}
int position;
try {
position = SortedLists.binarySearch(elements, target, unsafeComparator(),
ANY_PRESENT, INVERTED_INSERTION_INDEX);
} catch (ClassCastException e) {
return -1;
}
return (position >= 0) ? position : -1;
}
@Override ImmutableList<E> createAsList() {
return new ImmutableSortedAsList<E>(this, elements);
}
@Override
ImmutableSortedSet<E> createDescendingSet() {
return new RegularImmutableSortedSet<E>(elements.reverse(),
Ordering.from(comparator).reverse());
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link SortedSetMultimap} interface. It's a
* wrapper around {@link AbstractMultimap} that converts the returned
* collections into sorted sets. The {@link #createCollection} method
* must return a {@code SortedSet}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractSortedSetMultimap<K, V>
extends AbstractSetMultimap<K, V> implements SortedSetMultimap<K, V> {
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
*/
protected AbstractSortedSetMultimap(Map<K, Collection<V>> map) {
super(map);
}
@Override abstract SortedSet<V> createCollection();
// Following Javadoc copied from Multimap and SortedSetMultimap.
/**
* Returns a collection view of all values associated with a key. If no
* mappings in the multimap have the provided key, an empty collection is
* returned.
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public SortedSet<V> get(@Nullable K key) {
return (SortedSet<V>) super.get(key);
}
/**
* Removes all values associated with a given key. The returned collection is
* immutable.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public SortedSet<V> removeAll(@Nullable Object key) {
return (SortedSet<V>) super.removeAll(key);
}
/**
* Stores a collection of values with the same key, replacing any existing
* values for that key. The returned collection is immutable.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
return (SortedSet<V>) super.replaceValues(key, values);
}
/**
* Returns a map view that associates each key with the corresponding values
* in the multimap. Changes to the returned map, such as element removal, will
* update the underlying multimap. The map does not support {@code setValue}
* on its entries, {@code put}, or {@code putAll}.
*
* <p>When passed a key that is present in the map, {@code
* asMap().get(Object)} has the same behavior as {@link #get}, returning a
* live collection. When passed a key that is not present, however, {@code
* asMap().get(Object)} returns {@code null} instead of an empty collection.
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link SortedSet} values.
*/
@Override public Map<K, Collection<V>> asMap() {
return super.asMap();
}
/**
* {@inheritDoc}
*
* Consequently, the values do not follow their natural ordering or the
* ordering of the value comparator.
*/
@Override public Collection<V> values() {
return super.values();
}
private static final long serialVersionUID = 430848587173315748L;
}
| Java |
/*
* 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 java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.common.annotations.GwtCompatible;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient}
* to work around build-system quirks. This annotation should be used
* <b>only</b> in {@code com.google.common.collect}.
*/
@Documented
@GwtCompatible
@Retention(RUNTIME)
@Target(FIELD)
@interface GwtTransient {
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
* A queue which forwards all its method calls to another queue. Subclasses
* should override one or more methods to modify the behavior of the backing
* queue as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingQueue} forward
* <b>indiscriminately</b> to the methods of the delegate. For example,
* overriding {@link #add} alone <b>will not</b> change the behavior of {@link
* #offer} which can lead to unexpected behavior. In this case, you should
* override {@code offer} as well, either providing your own implementation, or
* delegating to the provided {@code standardOffer} method.
*
* <p>The {@code standard} methods are not guaranteed to be thread-safe, even
* when all of the methods that they depend on are thread-safe.
*
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingQueue<E> extends ForwardingCollection<E>
implements Queue<E> {
/** Constructor for use by subclasses. */
protected ForwardingQueue() {}
@Override protected abstract Queue<E> delegate();
@Override
public boolean offer(E o) {
return delegate().offer(o);
}
@Override
public E poll() {
return delegate().poll();
}
@Override
public E remove() {
return delegate().remove();
}
@Override
public E peek() {
return delegate().peek();
}
@Override
public E element() {
return delegate().element();
}
/**
* A sensible definition of {@link #offer} in terms of {@link #add}. If you
* override {@link #add}, you may wish to override {@link #offer} to forward
* to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardOffer(E e) {
try {
return add(e);
} catch (IllegalStateException caught) {
return false;
}
}
/**
* A sensible definition of {@link #peek} in terms of {@link #element}. If you
* override {@link #element}, you may wish to override {@link #peek} to
* forward to this implementation.
*
* @since 7.0
*/
@Beta protected E standardPeek() {
try {
return element();
} catch (NoSuchElementException caught) {
return null;
}
}
/**
* A sensible definition of {@link #poll} in terms of {@link #remove}. If you
* override {@link #remove}, you may wish to override {@link #poll} to forward
* to this implementation.
*
* @since 7.0
*/
@Beta protected E standardPoll() {
try {
return remove();
} catch (NoSuchElementException caught) {
return null;
}
}
}
| Java |
/*
* 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.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.collect.BoundType.CLOSED;
import com.google.common.primitives.Ints;
import javax.annotation.Nullable;
/**
* An immutable sorted multiset with one or more distinct elements.
*
* @author Louis Wasserman
*/
@SuppressWarnings("serial") // uses writeReplace, not default serialization
final class RegularImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> {
private final transient RegularImmutableSortedSet<E> elementSet;
private final transient int[] counts;
private final transient long[] cumulativeCounts;
private final transient int offset;
private final transient int length;
RegularImmutableSortedMultiset(
RegularImmutableSortedSet<E> elementSet,
int[] counts,
long[] cumulativeCounts,
int offset,
int length) {
this.elementSet = elementSet;
this.counts = counts;
this.cumulativeCounts = cumulativeCounts;
this.offset = offset;
this.length = length;
}
private Entry<E> getEntry(int index) {
return Multisets.immutableEntry(
elementSet.asList().get(index),
counts[offset + index]);
}
@Override
public Entry<E> firstEntry() {
return getEntry(0);
}
@Override
public Entry<E> lastEntry() {
return getEntry(length - 1);
}
@Override
public int count(@Nullable Object element) {
int index = elementSet.indexOf(element);
return (index == -1) ? 0 : counts[index + offset];
}
@Override
public int size() {
long size = cumulativeCounts[offset + length] - cumulativeCounts[offset];
return Ints.saturatedCast(size);
}
@Override
public ImmutableSortedSet<E> elementSet() {
return elementSet;
}
@Override
public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
return getSubMultiset(0, elementSet.headIndex(upperBound, checkNotNull(boundType) == CLOSED));
}
@Override
public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
return getSubMultiset(elementSet.tailIndex(lowerBound, checkNotNull(boundType) == CLOSED),
length);
}
ImmutableSortedMultiset<E> getSubMultiset(int from, int to) {
checkPositionIndexes(from, to, length);
if (from == to) {
return emptyMultiset(comparator());
} else if (from == 0 && to == length) {
return this;
} else {
RegularImmutableSortedSet<E> subElementSet =
(RegularImmutableSortedSet<E>) elementSet.getSubSet(from, to);
return new RegularImmutableSortedMultiset<E>(
subElementSet, counts, cumulativeCounts, offset + from, to - from);
}
}
@Override
ImmutableSet<Entry<E>> createEntrySet() {
return new EntrySet();
}
private final class EntrySet extends ImmutableMultiset<E>.EntrySet {
@Override
public int size() {
return length;
}
@Override
public UnmodifiableIterator<Entry<E>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<E>> createAsList() {
return new ImmutableAsList<Entry<E>>() {
@Override
public Entry<E> get(int index) {
return getEntry(index);
}
@Override
ImmutableCollection<Entry<E>> delegateCollection() {
return EntrySet.this;
}
};
}
}
@Override
boolean isPartialView() {
return offset > 0 || length < counts.length;
}
}
| Java |
/*
* 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 static com.google.common.collect.BoundType.CLOSED;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* An implementation of {@link ContiguousSet} that contains one or more elements.
*
* @author Gregory Kick
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("unchecked") // allow ungenerified Comparable types
final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> {
private final Range<C> range;
RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) {
super(domain);
this.range = range;
}
private ContiguousSet<C> intersectionInCurrentDomain(Range<C> other) {
return (range.isConnected(other))
? range.intersection(other).asSet(domain)
: new EmptyContiguousSet<C>(domain);
}
@Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) {
return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive)));
}
@Override ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement,
boolean toInclusive) {
if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) {
// Range would reject our attempt to create (x, x).
return new EmptyContiguousSet<C>(domain);
}
return intersectionInCurrentDomain(Range.range(
fromElement, BoundType.forBoolean(fromInclusive),
toElement, BoundType.forBoolean(toInclusive)));
}
@Override ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) {
return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive)));
}
@GwtIncompatible("not used by GWT emulation")
@Override int indexOf(Object target) {
return contains(target) ? (int) domain.distance(first(), (C) target) : -1;
}
@Override public UnmodifiableIterator<C> iterator() {
return new AbstractSequentialIterator<C>(first()) {
final C last = last();
@Override
protected C computeNext(C previous) {
return equalsOrThrow(previous, last) ? null : domain.next(previous);
}
};
}
private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) {
return right != null && Range.compareOrThrow(left, right) == 0;
}
@Override boolean isPartialView() {
return false;
}
@Override public C first() {
return range.lowerBound.leastValueAbove(domain);
}
@Override public C last() {
return range.upperBound.greatestValueBelow(domain);
}
@Override public int size() {
long distance = domain.distance(first(), last());
return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1;
}
@Override public boolean contains(Object object) {
if (object == null) {
return false;
}
try {
return range.contains((C) object);
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsAll(Collection<?> targets) {
return Collections2.containsAllImpl(this, targets);
}
@Override public boolean isEmpty() {
return false;
}
// copied to make sure not to use the GWT-emulated version
@Override public Object[] toArray() {
return ObjectArrays.toArrayImpl(this);
}
// copied to make sure not to use the GWT-emulated version
@Override public <T> T[] toArray(T[] other) {
return ObjectArrays.toArrayImpl(this, other);
}
@Override public ContiguousSet<C> intersection(ContiguousSet<C> other) {
checkNotNull(other);
checkArgument(this.domain.equals(other.domain));
if (other.isEmpty()) {
return other;
} else {
C lowerEndpoint = Ordering.natural().max(this.first(), other.first());
C upperEndpoint = Ordering.natural().min(this.last(), other.last());
return (lowerEndpoint.compareTo(upperEndpoint) < 0)
? Range.closed(lowerEndpoint, upperEndpoint).asSet(domain)
: new EmptyContiguousSet<C>(domain);
}
}
@Override public Range<C> range() {
return range(CLOSED, CLOSED);
}
@Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) {
return Range.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain),
range.upperBound.withUpperBoundType(upperBoundType, domain));
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
} else if (object instanceof RegularContiguousSet) {
RegularContiguousSet<?> that = (RegularContiguousSet<?>) object;
if (this.domain.equals(that.domain)) {
return this.first().equals(that.first())
&& this.last().equals(that.last());
}
}
return super.equals(object);
}
// copied to make sure not to use the GWT-emulated version
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@GwtIncompatible("serialization")
private static final class SerializedForm<C extends Comparable> implements Serializable {
final Range<C> range;
final DiscreteDomain<C> domain;
private SerializedForm(Range<C> range, DiscreteDomain<C> domain) {
this.range = range;
this.domain = domain;
}
private Object readResolve() {
return new RegularContiguousSet<C>(range, domain);
}
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new SerializedForm<C>(range, domain);
}
private static final long serialVersionUID = 0;
@GwtIncompatible("NavigableSet")
@Override
ImmutableSortedSet<C> createDescendingSet() {
return new DescendingContiguousSet();
}
@GwtIncompatible("NavigableSet")
private final class DescendingContiguousSet extends ImmutableSortedSet<C> {
private DescendingContiguousSet() {
super(Ordering.natural().reverse());
}
@Override
public C first() {
return RegularContiguousSet.this.last();
}
@Override
public C last() {
return RegularContiguousSet.this.first();
}
@Override
public int size() {
return RegularContiguousSet.this.size();
}
@Override
public UnmodifiableIterator<C> iterator() {
return new AbstractSequentialIterator<C>(first()) {
final C last = last();
@Override
protected C computeNext(C previous) {
return equalsOrThrow(previous, last) ? null : domain.previous(previous);
}
};
}
@Override
ImmutableSortedSet<C> headSetImpl(C toElement, boolean inclusive) {
return RegularContiguousSet.this.tailSetImpl(toElement, inclusive).descendingSet();
}
@Override
ImmutableSortedSet<C> subSetImpl(
C fromElement,
boolean fromInclusive,
C toElement,
boolean toInclusive) {
return RegularContiguousSet.this.subSetImpl(
toElement,
toInclusive,
fromElement,
fromInclusive).descendingSet();
}
@Override
ImmutableSortedSet<C> tailSetImpl(C fromElement, boolean inclusive) {
return RegularContiguousSet.this.headSetImpl(fromElement, inclusive).descendingSet();
}
@Override
ImmutableSortedSet<C> createDescendingSet() {
return RegularContiguousSet.this;
}
@Override
int indexOf(Object target) {
return contains(target) ? (int) domain.distance(last(), (C) target) : -1;
}
@Override
boolean isPartialView() {
return false;
}
}
}
| Java |
/*
* 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.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Supplier;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Implementation of {@link Table} using hash tables.
*
* <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link
* #columnMap()} have iterators that don't support {@code remove()}. Otherwise,
* all optional operations are supported. Null row keys, columns keys, and
* values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because
* the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code
* column(columnKey).get(rowKey)} still runs quickly, since the row key is
* provided. However, {@code column(columnKey).size()} takes longer, since an
* iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access this table concurrently and one of the threads modifies the table, it
* must be synchronized externally.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table">
* {@code Table}</a>.
*
* @author Jared Levy
* @since 7.0
*/
@GwtCompatible(serializable = true)
public class HashBasedTable<R, C, V> extends StandardTable<R, C, V> {
private static class Factory<C, V>
implements Supplier<Map<C, V>>, Serializable {
final int expectedSize;
Factory(int expectedSize) {
this.expectedSize = expectedSize;
}
@Override
public Map<C, V> get() {
return Maps.newHashMapWithExpectedSize(expectedSize);
}
private static final long serialVersionUID = 0;
}
/**
* Creates an empty {@code HashBasedTable}.
*/
public static <R, C, V> HashBasedTable<R, C, V> create() {
return new HashBasedTable<R, C, V>(
new HashMap<R, Map<C, V>>(), new Factory<C, V>(0));
}
/**
* Creates an empty {@code HashBasedTable} with the specified map sizes.
*
* @param expectedRows the expected number of distinct row keys
* @param expectedCellsPerRow the expected number of column key / value
* mappings in each row
* @throws IllegalArgumentException if {@code expectedRows} or {@code
* expectedCellsPerRow} is negative
*/
public static <R, C, V> HashBasedTable<R, C, V> create(
int expectedRows, int expectedCellsPerRow) {
checkArgument(expectedCellsPerRow >= 0);
Map<R, Map<C, V>> backingMap =
Maps.newHashMapWithExpectedSize(expectedRows);
return new HashBasedTable<R, C, V>(
backingMap, new Factory<C, V>(expectedCellsPerRow));
}
/**
* Creates a {@code HashBasedTable} with the same mappings as the specified
* table.
*
* @param table the table to copy
* @throws NullPointerException if any of the row keys, column keys, or values
* in {@code table} is null
*/
public static <R, C, V> HashBasedTable<R, C, V> create(
Table<? extends R, ? extends C, ? extends V> table) {
HashBasedTable<R, C, V> result = create();
result.putAll(table);
return result;
}
HashBasedTable(Map<R, Map<C, V>> backingMap, Factory<C, V> factory) {
super(backingMap, factory);
}
// Overriding so NullPointerTester test passes.
@Override public boolean contains(
@Nullable Object rowKey, @Nullable Object columnKey) {
return super.contains(rowKey, columnKey);
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return super.containsColumn(columnKey);
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return super.containsRow(rowKey);
}
@Override public boolean containsValue(@Nullable Object value) {
return super.containsValue(value);
}
@Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
return super.get(rowKey, columnKey);
}
@Override public boolean equals(@Nullable Object obj) {
return super.equals(obj);
}
@Override public V remove(
@Nullable Object rowKey, @Nullable Object columnKey) {
return super.remove(rowKey, columnKey);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
/** An ordering that uses the reverse of the natural order of the values. */
@GwtCompatible(serializable = true)
final class UsingToStringOrdering
extends Ordering<Object> implements Serializable {
static final UsingToStringOrdering INSTANCE = new UsingToStringOrdering();
@Override public int compare(Object left, Object right) {
return left.toString().compareTo(right.toString());
}
// preserve singleton-ness, so equals() and hashCode() work correctly
private Object readResolve() {
return INSTANCE;
}
@Override public String toString() {
return "Ordering.usingToString()";
}
private UsingToStringOrdering() {}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.primitives.Ints;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of {@code Multimap} that does not allow duplicate key-value
* entries and that returns collections whose iterators follow the ordering in
* which the data was added to the multimap.
*
* <p>The collections returned by {@code keySet}, {@code keys}, and {@code
* asMap} iterate through the keys in the order they were first added to the
* multimap. Similarly, {@code get}, {@code removeAll}, and {@code
* replaceValues} return collections that iterate through the values in the
* order they were added. The collections generated by {@code entries} and
* {@code values} iterate across the key-value mappings in the order they were
* added to the multimap.
*
* <p>The iteration ordering of the collections generated by {@code keySet},
* {@code keys}, and {@code asMap} has a few subtleties. As long as the set of
* keys remains unchanged, adding or removing mappings does not affect the key
* iteration order. However, if you remove all values associated with a key and
* then add the key back to the multimap, that key will come last in the key
* iteration order.
*
* <p>The multimap does not store duplicate key-value pairs. Adding a new
* key-value pair equal to an existing key-value pair has no effect.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedSetMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> {
/**
* Creates a new, empty {@code LinkedHashMultimap} with the default initial
* capacities.
*/
public static <K, V> LinkedHashMultimap<K, V> create() {
return new LinkedHashMultimap<K, V>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY);
}
/**
* Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold
* the specified numbers of keys and values without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> LinkedHashMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new LinkedHashMultimap<K, V>(
Maps.capacity(expectedKeys),
Maps.capacity(expectedValuesPerKey));
}
/**
* Constructs a {@code LinkedHashMultimap} with the same mappings as the
* specified multimap. If a key-value mapping appears multiple times in the
* input multimap, it only appears once in the constructed multimap. The new
* multimap has the same {@link Multimap#entries()} iteration order as the
* input multimap, except for excluding duplicate mappings.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> LinkedHashMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY);
result.putAll(multimap);
return result;
}
private interface ValueSetLink<K, V> {
ValueSetLink<K, V> getPredecessorInValueSet();
ValueSetLink<K, V> getSuccessorInValueSet();
void setPredecessorInValueSet(ValueSetLink<K, V> entry);
void setSuccessorInValueSet(ValueSetLink<K, V> entry);
}
private static <K, V> void succeedsInValueSet(ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) {
pred.setSuccessorInValueSet(succ);
succ.setPredecessorInValueSet(pred);
}
private static <K, V> void succeedsInMultimap(
ValueEntry<K, V> pred, ValueEntry<K, V> succ) {
pred.setSuccessorInMultimap(succ);
succ.setPredecessorInMultimap(pred);
}
private static <K, V> void deleteFromValueSet(ValueSetLink<K, V> entry) {
succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet());
}
private static <K, V> void deleteFromMultimap(ValueEntry<K, V> entry) {
succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap());
}
/**
* LinkedHashMultimap entries are in no less than three coexisting linked lists:
* a row in the hash table for a Set<V> associated with a key, the linked list
* of insertion-ordered entries in that Set<V>, and the linked list of entries
* in the LinkedHashMultimap as a whole.
*/
private static final class ValueEntry<K, V> extends AbstractMapEntry<K, V>
implements ValueSetLink<K, V> {
final K key;
final V value;
final int valueHash;
@Nullable ValueEntry<K, V> nextInValueSetHashRow;
ValueSetLink<K, V> predecessorInValueSet;
ValueSetLink<K, V> successorInValueSet;
ValueEntry<K, V> predecessorInMultimap;
ValueEntry<K, V> successorInMultimap;
ValueEntry(@Nullable K key, @Nullable V value, int valueHash,
@Nullable ValueEntry<K, V> nextInValueSetHashRow) {
this.key = key;
this.value = value;
this.valueHash = valueHash;
this.nextInValueSetHashRow = nextInValueSetHashRow;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public ValueSetLink<K, V> getPredecessorInValueSet() {
return predecessorInValueSet;
}
@Override
public ValueSetLink<K, V> getSuccessorInValueSet() {
return successorInValueSet;
}
@Override
public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
predecessorInValueSet = entry;
}
@Override
public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
successorInValueSet = entry;
}
public ValueEntry<K, V> getPredecessorInMultimap() {
return predecessorInMultimap;
}
public ValueEntry<K, V> getSuccessorInMultimap() {
return successorInMultimap;
}
public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) {
this.successorInMultimap = multimapSuccessor;
}
public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) {
this.predecessorInMultimap = multimapPredecessor;
}
}
private static final int DEFAULT_KEY_CAPACITY = 16;
private static final int DEFAULT_VALUE_SET_CAPACITY = 2;
private static final int MAX_VALUE_SET_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;
@VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY;
private transient ValueEntry<K, V> multimapHeaderEntry;
private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) {
super(new LinkedHashMap<K, Collection<V>>(keyCapacity));
checkArgument(valueSetCapacity >= 0,
"expectedValuesPerKey must be >= 0 but was %s", valueSetCapacity);
this.valueSetCapacity = valueSetCapacity;
this.multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null);
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code LinkedHashSet} for a collection of values for
* one key.
*
* @return a new {@code LinkedHashSet} containing a collection of values for
* one key
*/
@Override
Set<V> createCollection() {
return new LinkedHashSet<V>(valueSetCapacity);
}
/**
* {@inheritDoc}
*
* <p>Creates a decorated insertion-ordered set that also keeps track of the
* order in which key-value pairs are added to the multimap.
*
* @param key key to associate with values in the collection
* @return a new decorated set containing a collection of values for one key
*/
@Override
Collection<V> createCollection(K key) {
return new ValueSet(key, valueSetCapacity);
}
/**
* {@inheritDoc}
*
* <p>If {@code values} is not empty and the multimap already contains a
* mapping for {@code key}, the {@code keySet()} ordering is unchanged.
* However, the provided values always come last in the {@link #entries()} and
* {@link #values()} iteration orderings.
*/
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values) {
return super.replaceValues(key, values);
}
/**
* Returns a set of all key-value pairs. Changes to the returned set will
* update the underlying multimap, and vice versa. The entries set does not
* support the {@code add} or {@code addAll} operations.
*
* <p>The iterator generated by the returned set traverses the entries in the
* order they were added to the multimap.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the
* multimap, taken at the time the entry is returned by a method call to the
* collection or its iterator.
*/
@Override public Set<Map.Entry<K, V>> entries() {
return super.entries();
}
/**
* Returns a collection of all values in the multimap. Changes to the returned
* collection will update the underlying multimap, and vice versa.
*
* <p>The iterator generated by the returned collection traverses the values
* in the order they were added to the multimap.
*/
@Override public Collection<V> values() {
return super.values();
}
@VisibleForTesting
final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> {
/*
* We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory
* consumption.
*/
private final K key;
private ValueEntry<K, V>[] hashTable;
private int size = 0;
private int modCount = 0;
// We use the set object itself as the end of the linked list, avoiding an unnecessary
// entry object per key.
private ValueSetLink<K, V> firstEntry;
private ValueSetLink<K, V> lastEntry;
ValueSet(K key, int expectedValues) {
this.key = key;
this.firstEntry = this;
this.lastEntry = this;
// Round expected values up to a power of 2 to get the table size.
int tableSize = Integer.highestOneBit(Math.max(expectedValues, 2) - 1) << 1;
if (tableSize < 0) {
tableSize = MAX_VALUE_SET_TABLE_SIZE;
}
@SuppressWarnings("unchecked")
ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize];
this.hashTable = hashTable;
}
@Override
public ValueSetLink<K, V> getPredecessorInValueSet() {
return lastEntry;
}
@Override
public ValueSetLink<K, V> getSuccessorInValueSet() {
return firstEntry;
}
@Override
public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
lastEntry = entry;
}
@Override
public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
firstEntry = entry;
}
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
ValueSetLink<K, V> nextEntry = firstEntry;
ValueEntry<K, V> toRemove;
int expectedModCount = modCount;
private void checkForComodification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForComodification();
return nextEntry != ValueSet.this;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry;
V result = entry.getValue();
toRemove = entry;
nextEntry = entry.getSuccessorInValueSet();
return result;
}
@Override
public void remove() {
checkForComodification();
Iterators.checkRemove(toRemove != null);
Object o = toRemove.getValue();
int hash = (o == null) ? 0 : o.hashCode();
int row = Hashing.smear(hash) & (hashTable.length - 1);
ValueEntry<K, V> prev = null;
for (ValueEntry<K, V> entry = hashTable[row]; entry != null;
prev = entry, entry = entry.nextInValueSetHashRow) {
if (entry == toRemove) {
if (prev == null) {
// first entry in row
hashTable[row] = entry.nextInValueSetHashRow;
} else {
prev.nextInValueSetHashRow = entry.nextInValueSetHashRow;
}
deleteFromValueSet(toRemove);
deleteFromMultimap(toRemove);
size--;
expectedModCount = ++modCount;
break;
}
}
toRemove = null;
}
};
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(@Nullable Object o) {
int hash = (o == null) ? 0 : o.hashCode();
int row = Hashing.smear(hash) & (hashTable.length - 1);
for (ValueEntry<K, V> entry = hashTable[row]; entry != null;
entry = entry.nextInValueSetHashRow) {
if (hash == entry.valueHash && Objects.equal(o, entry.getValue())) {
return true;
}
}
return false;
}
/**
* The threshold above which the hash table should be rebuilt.
*/
@VisibleForTesting int threshold() {
return hashTable.length; // load factor of 1.0
}
@Override
public boolean add(@Nullable V value) {
int hash = (value == null) ? 0 : value.hashCode();
int row = Hashing.smear(hash) & (hashTable.length - 1);
ValueEntry<K, V> rowHead = hashTable[row];
for (ValueEntry<K, V> entry = rowHead; entry != null;
entry = entry.nextInValueSetHashRow) {
if (hash == entry.valueHash && Objects.equal(value, entry.getValue())) {
return false;
}
}
ValueEntry<K, V> newEntry = new ValueEntry<K, V>(key, value, hash, rowHead);
succeedsInValueSet(lastEntry, newEntry);
succeedsInValueSet(newEntry, this);
succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry);
succeedsInMultimap(newEntry, multimapHeaderEntry);
hashTable[row] = newEntry;
size++;
modCount++;
rehashIfNecessary();
return true;
}
private void rehashIfNecessary() {
if (size > threshold() && hashTable.length < MAX_VALUE_SET_TABLE_SIZE) {
@SuppressWarnings("unchecked")
ValueEntry<K, V>[] hashTable = new ValueEntry[this.hashTable.length * 2];
this.hashTable = hashTable;
int mask = hashTable.length - 1;
for (ValueSetLink<K, V> entry = firstEntry;
entry != this; entry = entry.getSuccessorInValueSet()) {
ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
int row = Hashing.smear(valueEntry.valueHash) & mask;
valueEntry.nextInValueSetHashRow = hashTable[row];
hashTable[row] = valueEntry;
}
}
}
@Override
public boolean remove(@Nullable Object o) {
int hash = (o == null) ? 0 : o.hashCode();
int row = Hashing.smear(hash) & (hashTable.length - 1);
ValueEntry<K, V> prev = null;
for (ValueEntry<K, V> entry = hashTable[row]; entry != null;
prev = entry, entry = entry.nextInValueSetHashRow) {
if (hash == entry.valueHash && Objects.equal(o, entry.getValue())) {
if (prev == null) {
// first entry in the row
hashTable[row] = entry.nextInValueSetHashRow;
} else {
prev.nextInValueSetHashRow = entry.nextInValueSetHashRow;
}
deleteFromValueSet(entry);
deleteFromMultimap(entry);
size--;
modCount++;
return true;
}
}
return false;
}
@Override
public void clear() {
Arrays.fill(hashTable, null);
size = 0;
for (ValueSetLink<K, V> entry = firstEntry;
entry != this; entry = entry.getSuccessorInValueSet()) {
ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
deleteFromMultimap(valueEntry);
}
succeedsInValueSet(this, this);
modCount++;
}
}
@Override
Iterator<Map.Entry<K, V>> createEntryIterator() {
return new Iterator<Map.Entry<K, V>>() {
ValueEntry<K, V> nextEntry = multimapHeaderEntry.successorInMultimap;
ValueEntry<K, V> toRemove;
@Override
public boolean hasNext() {
return nextEntry != multimapHeaderEntry;
}
@Override
public Map.Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
ValueEntry<K, V> result = nextEntry;
toRemove = result;
nextEntry = nextEntry.successorInMultimap;
return result;
}
@Override
public void remove() {
Iterators.checkRemove(toRemove != null);
LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue());
toRemove = null;
}
};
}
@Override
public void clear() {
super.clear();
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
}
/**
* @serialData the expected values per key, the number of distinct keys,
* the number of entries, and the entries in order
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(valueSetCapacity);
stream.writeInt(keySet().size());
for (K key : keySet()) {
stream.writeObject(key);
}
stream.writeInt(size());
for (Map.Entry<K, V> entry : entries()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null);
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
valueSetCapacity = stream.readInt();
int distinctKeys = stream.readInt();
Map<K, Collection<V>> map =
new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys));
for (int i = 0; i < distinctKeys; i++) {
@SuppressWarnings("unchecked")
K key = (K) stream.readObject();
map.put(key, createCollection(key));
}
int entries = stream.readInt();
for (int i = 0; i < entries; i++) {
@SuppressWarnings("unchecked")
K key = (K) stream.readObject();
@SuppressWarnings("unchecked")
V value = (V) stream.readObject();
map.get(key).add(value);
}
setMap(map);
}
@GwtIncompatible("java serialization not supported")
private static final long serialVersionUID = 1;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A sorted set which forwards all its method calls to another sorted set.
* Subclasses should override one or more methods to modify the behavior of the
* backing sorted set as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingSortedSet} forward
* <i>indiscriminately</i> to the methods of the delegate. For example,
* overriding {@link #add} alone <i>will not</i> change the behavior of {@link
* #addAll}, which can lead to unexpected behavior. In this case, you should
* override {@code addAll} as well, either providing your own implementation, or
* delegating to the provided {@code standardAddAll} method.
*
* <p>Each of the {@code standard} methods, where appropriate, uses the set's
* comparator (or the natural ordering of the elements, if there is no
* comparator) to test element equality. As a result, if the comparator is not
* consistent with equals, some of the standard implementations may violate the
* {@code Set} contract.
*
* <p>The {@code standard} methods and the collection views they return are not
* guaranteed to be thread-safe, even when all of the methods that they depend
* on are thread-safe.
*
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingSortedSet<E> extends ForwardingSet<E>
implements SortedSet<E> {
/** Constructor for use by subclasses. */
protected ForwardingSortedSet() {}
@Override protected abstract SortedSet<E> delegate();
@Override
public Comparator<? super E> comparator() {
return delegate().comparator();
}
@Override
public E first() {
return delegate().first();
}
@Override
public SortedSet<E> headSet(E toElement) {
return delegate().headSet(toElement);
}
@Override
public E last() {
return delegate().last();
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return delegate().subSet(fromElement, toElement);
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return delegate().tailSet(fromElement);
}
// unsafe, but worst case is a CCE is thrown, which callers will be expecting
@SuppressWarnings("unchecked")
private int unsafeCompare(Object o1, Object o2) {
Comparator<? super E> comparator = comparator();
return (comparator == null)
? ((Comparable<Object>) o1).compareTo(o2)
: ((Comparator<Object>) comparator).compare(o1, o2);
}
/**
* A sensible definition of {@link #contains} in terms of the {@code first()}
* method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
* to override {@link #contains} to forward to this implementation.
*
* @since 7.0
*/
@Override @Beta protected boolean standardContains(@Nullable Object object) {
try {
// any ClassCastExceptions are caught
@SuppressWarnings("unchecked")
SortedSet<Object> self = (SortedSet<Object>) this;
Object ceiling = self.tailSet(object).first();
return unsafeCompare(ceiling, object) == 0;
} catch (ClassCastException e) {
return false;
} catch (NoSuchElementException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
/**
* A sensible definition of {@link #remove} in terms of the {@code iterator()}
* method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
* to override {@link #remove} to forward to this implementation.
*
* @since 7.0
*/
@Override @Beta protected boolean standardRemove(@Nullable Object object) {
try {
// any ClassCastExceptions are caught
@SuppressWarnings("unchecked")
SortedSet<Object> self = (SortedSet<Object>) this;
Iterator<Object> iterator = self.tailSet(object).iterator();
if (iterator.hasNext()) {
Object ceiling = iterator.next();
if (unsafeCompare(ceiling, object) == 0) {
iterator.remove();
return true;
}
}
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return false;
}
/**
* A sensible default implementation of {@link #subSet(Object, Object)} in
* terms of {@link #headSet(Object)} and {@link #tailSet(Object)}. In some
* situations, you may wish to override {@link #subSet(Object, Object)} to
* forward to this implementation.
*
* @since 7.0
*/
@Beta protected SortedSet<E> standardSubSet(E fromElement, E toElement) {
return tailSet(fromElement).headSet(toElement);
}
}
| Java |
/*
* Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible;
/**
* An {@link ImmutableAsList} implementation specialized for when the delegate collection is
* already backed by an {@code ImmutableList} or array.
*
* @author Louis Wasserman
*/
@GwtCompatible
@SuppressWarnings("serial") // uses writeReplace, not default serialization
class RegularImmutableAsList<E> extends ImmutableAsList<E> {
private final ImmutableCollection<E> delegate;
private final ImmutableList<? extends E> delegateList;
RegularImmutableAsList(ImmutableCollection<E> delegate, ImmutableList<? extends E> delegateList) {
this.delegate = delegate;
this.delegateList = delegateList;
}
RegularImmutableAsList(ImmutableCollection<E> delegate, Object[] array) {
this(delegate, ImmutableList.<E>asImmutableList(array));
}
@Override
ImmutableCollection<E> delegateCollection() {
return delegate;
}
ImmutableList<? extends E> delegateList() {
return delegateList;
}
@SuppressWarnings("unchecked") // safe covariant cast!
@Override
public UnmodifiableListIterator<E> listIterator(int index) {
return (UnmodifiableListIterator<E>) delegateList.listIterator(index);
}
@Override
public Object[] toArray() {
return delegateList.toArray();
}
@Override
public <T> T[] toArray(T[] other) {
return delegateList.toArray(other);
}
@Override
public int indexOf(Object object) {
return delegateList.indexOf(object);
}
@Override
public int lastIndexOf(Object object) {
return delegateList.lastIndexOf(object);
}
@Override
public boolean equals(Object obj) {
return delegateList.equals(obj);
}
@Override
public int hashCode() {
return delegateList.hashCode();
}
@Override
public E get(int index) {
return delegateList.get(index);
}
}
| Java |
/*
* 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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.LongMath.binomial;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
/**
* Provides static methods for working with {@code Collection} instances.
*
* @author Chris Povirk
* @author Mike Bostock
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Collections2 {
private Collections2() {}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* returned collection is a live view of {@code unfiltered}; changes to one
* affect the other.
*
* <p>The resulting collection's iterator does not support {@code remove()},
* but all other collection methods are supported. When given an element that
* doesn't satisfy the predicate, the collection's {@code add()} and {@code
* addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered
* collection, only elements that satisfy the filter will be removed from the
* underlying collection.
*
* <p>The returned collection isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered collection's methods, such as {@code size()},
* iterate across every element in the underlying collection and determine
* which elements satisfy the filter. When a live view is <i>not</i> needed,
* it may be faster to copy {@code Iterables.filter(unfiltered, predicate)}
* and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals. (See {@link Iterables#filter(Iterable, Class)} for related
* functionality.)
*/
// TODO(kevinb): how can we omit that Iterables link when building gwt
// javadoc?
public static <E> Collection<E> filter(
Collection<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredCollection) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
return ((FilteredCollection<E>) unfiltered).createCombined(predicate);
}
return new FilteredCollection<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Delegates to {@link Collection#contains}. Returns {@code false} if the
* {@code contains} method throws a {@code ClassCastException}.
*/
static boolean safeContains(Collection<?> collection, Object object) {
try {
return collection.contains(object);
} catch (ClassCastException e) {
return false;
}
}
static class FilteredCollection<E> implements Collection<E> {
final Collection<E> unfiltered;
final Predicate<? super E> predicate;
FilteredCollection(Collection<E> unfiltered,
Predicate<? super E> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) {
return new FilteredCollection<E>(unfiltered,
Predicates.<E>and(predicate, newPredicate));
// .<E> above needed to compile in JDK 5
}
@Override
public boolean add(E element) {
checkArgument(predicate.apply(element));
return unfiltered.add(element);
}
@Override
public boolean addAll(Collection<? extends E> collection) {
for (E element : collection) {
checkArgument(predicate.apply(element));
}
return unfiltered.addAll(collection);
}
@Override
public void clear() {
Iterables.removeIf(unfiltered, predicate);
}
@Override
public boolean contains(Object element) {
try {
// unsafe cast can result in a CCE from predicate.apply(), which we
// will catch
@SuppressWarnings("unchecked")
E e = (E) element;
/*
* We check whether e satisfies the predicate, when we really mean to
* check whether the element contained in the set does. This is ok as
* long as the predicate is consistent with equals, as required.
*/
return predicate.apply(e) && unfiltered.contains(element);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override
public boolean containsAll(Collection<?> collection) {
for (Object element : collection) {
if (!contains(element)) {
return false;
}
}
return true;
}
@Override
public boolean isEmpty() {
return !Iterators.any(unfiltered.iterator(), predicate);
}
@Override
public Iterator<E> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
@Override
public boolean remove(Object element) {
try {
// unsafe cast can result in a CCE from predicate.apply(), which we
// will catch
@SuppressWarnings("unchecked")
E e = (E) element;
// See comment in contains() concerning predicate.apply(e)
return predicate.apply(e) && unfiltered.remove(element);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override
public boolean removeAll(final Collection<?> collection) {
checkNotNull(collection);
Predicate<E> combinedPredicate = new Predicate<E>() {
@Override
public boolean apply(E input) {
return predicate.apply(input) && collection.contains(input);
}
};
return Iterables.removeIf(unfiltered, combinedPredicate);
}
@Override
public boolean retainAll(final Collection<?> collection) {
checkNotNull(collection);
Predicate<E> combinedPredicate = new Predicate<E>() {
@Override
public boolean apply(E input) {
// See comment in contains() concerning predicate.apply(e)
return predicate.apply(input) && !collection.contains(input);
}
};
return Iterables.removeIf(unfiltered, combinedPredicate);
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
@Override public String toString() {
return Iterators.toString(iterator());
}
}
/**
* Returns a collection that applies {@code function} to each element of
* {@code fromCollection}. The returned collection is a live view of {@code
* fromCollection}; changes to one affect the other.
*
* <p>The returned collection's {@code add()} and {@code addAll()} methods
* throw an {@link UnsupportedOperationException}. All other collection
* methods are supported, as long as {@code fromCollection} supports them.
*
* <p>The returned collection isn't threadsafe or serializable, even if
* {@code fromCollection} is.
*
* <p>When a live view is <i>not</i> needed, it may be faster to copy the
* transformed collection and use the copy.
*
* <p>If the input {@code Collection} is known to be a {@code List}, consider
* {@link Lists#transform}. If only an {@code Iterable} is available, use
* {@link Iterables#transform}.
*/
public static <F, T> Collection<T> transform(Collection<F> fromCollection,
Function<? super F, T> function) {
return new TransformedCollection<F, T>(fromCollection, function);
}
static class TransformedCollection<F, T> extends AbstractCollection<T> {
final Collection<F> fromCollection;
final Function<? super F, ? extends T> function;
TransformedCollection(Collection<F> fromCollection,
Function<? super F, ? extends T> function) {
this.fromCollection = checkNotNull(fromCollection);
this.function = checkNotNull(function);
}
@Override public void clear() {
fromCollection.clear();
}
@Override public boolean isEmpty() {
return fromCollection.isEmpty();
}
@Override public Iterator<T> iterator() {
return Iterators.transform(fromCollection.iterator(), function);
}
@Override public int size() {
return fromCollection.size();
}
}
/**
* Returns {@code true} if the collection {@code self} contains all of the
* elements in the collection {@code c}.
*
* <p>This method iterates over the specified collection {@code c}, checking
* each element returned by the iterator in turn to see if it is contained in
* the specified collection {@code self}. If all elements are so contained,
* {@code true} is returned, otherwise {@code false}.
*
* @param self a collection which might contain all elements in {@code c}
* @param c a collection whose elements might be contained by {@code self}
*/
static boolean containsAllImpl(Collection<?> self, Collection<?> c) {
checkNotNull(self);
for (Object o : c) {
if (!self.contains(o)) {
return false;
}
}
return true;
}
/**
* An implementation of {@link Collection#toString()}.
*/
static String toStringImpl(final Collection<?> collection) {
StringBuilder sb
= newStringBuilderForCollection(collection.size()).append('[');
STANDARD_JOINER.appendTo(
sb, Iterables.transform(collection, new Function<Object, Object>() {
@Override public Object apply(Object input) {
return input == collection ? "(this Collection)" : input;
}
}));
return sb.append(']').toString();
}
/**
* Returns best-effort-sized StringBuilder based on the given collection size.
*/
static StringBuilder newStringBuilderForCollection(int size) {
checkArgument(size >= 0, "size must be non-negative");
return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO));
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> Collection<T> cast(Iterable<T> iterable) {
return (Collection<T>) iterable;
}
static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null");
/**
* Returns a {@link Collection} of all the permutations of the specified
* {@link Iterable}.
*
* <p><i>Notes:</i> This is an implementation of the algorithm for
* Lexicographical Permutations Generation, described in Knuth's "The Art of
* Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The
* iteration order follows the lexicographical order. This means that
* the first permutation will be in ascending order, and the last will be in
* descending order.
*
* <p>Duplicate elements are considered equal. For example, the list [1, 1]
* will have only one permutation, instead of two. This is why the elements
* have to implement {@link Comparable}.
*
* <p>An empty iterable has only one permutation, which is an empty list.
*
* <p>This method is equivalent to
* {@code Collections2.orderedPermutations(list, Ordering.natural())}.
*
* @param elements the original iterable whose elements have to be permuted.
* @return an immutable {@link Collection} containing all the different
* permutations of the original iterable.
* @throws NullPointerException if the specified iterable is null or has any
* null elements.
* @since 12.0
*/
@Beta public static <E extends Comparable<? super E>>
Collection<List<E>> orderedPermutations(Iterable<E> elements) {
return orderedPermutations(elements, Ordering.natural());
}
/**
* Returns a {@link Collection} of all the permutations of the specified
* {@link Iterable} using the specified {@link Comparator} for establishing
* the lexicographical ordering.
*
* <p>Examples: <pre> {@code
*
* for (List<String> perm : orderedPermutations(asList("b", "c", "a"))) {
* println(perm);
* }
* // -> ["a", "b", "c"]
* // -> ["a", "c", "b"]
* // -> ["b", "a", "c"]
* // -> ["b", "c", "a"]
* // -> ["c", "a", "b"]
* // -> ["c", "b", "a"]
*
* for (List<Integer> perm : orderedPermutations(asList(1, 2, 2, 1))) {
* println(perm);
* }
* // -> [1, 1, 2, 2]
* // -> [1, 2, 1, 2]
* // -> [1, 2, 2, 1]
* // -> [2, 1, 1, 2]
* // -> [2, 1, 2, 1]
* // -> [2, 2, 1, 1]}</pre>
*
* <p><i>Notes:</i> This is an implementation of the algorithm for
* Lexicographical Permutations Generation, described in Knuth's "The Art of
* Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The
* iteration order follows the lexicographical order. This means that
* the first permutation will be in ascending order, and the last will be in
* descending order.
*
* <p>Elements that compare equal are considered equal and no new permutations
* are created by swapping them.
*
* <p>An empty iterable has only one permutation, which is an empty list.
*
* @param elements the original iterable whose elements have to be permuted.
* @param comparator a comparator for the iterable's elements.
* @return an immutable {@link Collection} containing all the different
* permutations of the original iterable.
* @throws NullPointerException If the specified iterable is null, has any
* null elements, or if the specified comparator is null.
* @since 12.0
*/
@Beta public static <E> Collection<List<E>> orderedPermutations(
Iterable<E> elements, Comparator<? super E> comparator) {
return new OrderedPermutationCollection<E>(elements, comparator);
}
private static final class OrderedPermutationCollection<E>
extends AbstractCollection<List<E>> {
final ImmutableList<E> inputList;
final Comparator<? super E> comparator;
final int size;
OrderedPermutationCollection(Iterable<E> input,
Comparator<? super E> comparator) {
this.inputList = Ordering.from(comparator).immutableSortedCopy(input);
this.comparator = comparator;
this.size = calculateSize(inputList, comparator);
}
/**
* The number of permutations with repeated elements is calculated as
* follows:
* <ul>
* <li>For an empty list, it is 1 (base case).</li>
* <li>When r numbers are added to a list of n-r elements, the number of
* permutations is increased by a factor of (n choose r).</li>
* </ul>
*/
private static <E> int calculateSize(
List<E> sortedInputList, Comparator<? super E> comparator) {
long permutations = 1;
int n = 1;
int r = 1;
while (n < sortedInputList.size()) {
int comparison = comparator.compare(
sortedInputList.get(n - 1), sortedInputList.get(n));
if (comparison < 0) {
// We move to the next non-repeated element.
permutations *= binomial(n, r);
r = 0;
if (!isPositiveInt(permutations)) {
return Integer.MAX_VALUE;
}
}
n++;
r++;
}
permutations *= binomial(n, r);
if (!isPositiveInt(permutations)) {
return Integer.MAX_VALUE;
}
return (int) permutations;
}
@Override public int size() {
return size;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Iterator<List<E>> iterator() {
return new OrderedPermutationIterator<E>(inputList, comparator);
}
@Override public boolean contains(@Nullable Object obj) {
if (obj instanceof List) {
List<?> list = (List<?>) obj;
return isPermutation(inputList, list);
}
return false;
}
@Override public String toString() {
return "orderedPermutationCollection(" + inputList + ")";
}
}
private static final class OrderedPermutationIterator<E>
extends AbstractIterator<List<E>> {
List<E> nextPermutation;
final Comparator<? super E> comparator;
OrderedPermutationIterator(List<E> list,
Comparator<? super E> comparator) {
this.nextPermutation = Lists.newArrayList(list);
this.comparator = comparator;
}
@Override protected List<E> computeNext() {
if (nextPermutation == null) {
return endOfData();
}
ImmutableList<E> next = ImmutableList.copyOf(nextPermutation);
calculateNextPermutation();
return next;
}
void calculateNextPermutation() {
int j = findNextJ();
if (j == -1) {
nextPermutation = null;
return;
}
int l = findNextL(j);
Collections.swap(nextPermutation, j, l);
int n = nextPermutation.size();
Collections.reverse(nextPermutation.subList(j + 1, n));
}
int findNextJ() {
for (int k = nextPermutation.size() - 2; k >= 0; k--) {
if (comparator.compare(nextPermutation.get(k),
nextPermutation.get(k + 1)) < 0) {
return k;
}
}
return -1;
}
int findNextL(int j) {
E ak = nextPermutation.get(j);
for (int l = nextPermutation.size() - 1; l > j; l--) {
if (comparator.compare(ak, nextPermutation.get(l)) < 0) {
return l;
}
}
throw new AssertionError("this statement should be unreachable");
}
}
/**
* Returns a {@link Collection} of all the permutations of the specified
* {@link Collection}.
*
* <p><i>Notes:</i> This is an implementation of the Plain Changes algorithm
* for permutations generation, described in Knuth's "The Art of Computer
* Programming", Volume 4, Chapter 7, Section 7.2.1.2.
*
* <p>If the input list contains equal elements, some of the generated
* permutations will be equal.
*
* <p>An empty collection has only one permutation, which is an empty list.
*
* @param elements the original collection whose elements have to be permuted.
* @return an immutable {@link Collection} containing all the different
* permutations of the original collection.
* @throws NullPointerException if the specified collection is null or has any
* null elements.
* @since 12.0
*/
@Beta public static <E> Collection<List<E>> permutations(
Collection<E> elements) {
return new PermutationCollection<E>(ImmutableList.copyOf(elements));
}
private static final class PermutationCollection<E>
extends AbstractCollection<List<E>> {
final ImmutableList<E> inputList;
PermutationCollection(ImmutableList<E> input) {
this.inputList = input;
}
@Override public int size() {
return IntMath.factorial(inputList.size());
}
@Override public boolean isEmpty() {
return false;
}
@Override public Iterator<List<E>> iterator() {
return new PermutationIterator<E>(inputList);
}
@Override public boolean contains(@Nullable Object obj) {
if (obj instanceof List) {
List<?> list = (List<?>) obj;
return isPermutation(inputList, list);
}
return false;
}
@Override public String toString() {
return "permutations(" + inputList + ")";
}
}
private static class PermutationIterator<E>
extends AbstractIterator<List<E>> {
final List<E> list;
final int[] c;
final int[] o;
int j;
PermutationIterator(List<E> list) {
this.list = new ArrayList<E>(list);
int n = list.size();
c = new int[n];
o = new int[n];
for (int i = 0; i < n; i++) {
c[i] = 0;
o[i] = 1;
}
j = Integer.MAX_VALUE;
}
@Override protected List<E> computeNext() {
if (j <= 0) {
return endOfData();
}
ImmutableList<E> next = ImmutableList.copyOf(list);
calculateNextPermutation();
return next;
}
void calculateNextPermutation() {
j = list.size() - 1;
int s = 0;
// Handle the special case of an empty list. Skip the calculation of the
// next permutation.
if (j == -1) {
return;
}
while (true) {
int q = c[j] + o[j];
if (q < 0) {
switchDirection();
continue;
}
if (q == j + 1) {
if (j == 0) {
break;
}
s++;
switchDirection();
continue;
}
Collections.swap(list, j - c[j] + s, j - q + s);
c[j] = q;
break;
}
}
void switchDirection() {
o[j] = -o[j];
j--;
}
}
/**
* Returns {@code true} if the second list is a permutation of the first.
*/
private static boolean isPermutation(List<?> first,
List<?> second) {
if (first.size() != second.size()) {
return false;
}
Multiset<?> firstSet = HashMultiset.create(first);
Multiset<?> secondSet = HashMultiset.create(second);
return firstSet.equals(secondSet);
}
private static boolean isPositiveInt(long n) {
return n >= 0 && n <= Integer.MAX_VALUE;
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
/**
* An abstract base class for implementing the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
* The {@link #delegate()} method must be overridden to return the instance
* being decorated.
*
* <p>This class does <i>not</i> forward the {@code hashCode} and {@code equals}
* methods through to the backing object, but relies on {@code Object}'s
* implementation. This is necessary to preserve the symmetry of {@code equals}.
* Custom definitions of equality are usually based on an interface, such as
* {@code Set} or {@code List}, so that the implementation of {@code equals} can
* cast the object being tested for equality to the custom interface. {@code
* ForwardingObject} implements no such custom interfaces directly; they
* are implemented only in subclasses. Therefore, forwarding {@code equals}
* would break symmetry, as the forwarding object might consider itself equal to
* the object being tested, but the reverse could not be true. This behavior is
* consistent with the JDK's collection wrappers, such as
* {@link java.util.Collections#unmodifiableCollection}. Use an
* interface-specific subclass of {@code ForwardingObject}, such as {@link
* ForwardingList}, to preserve equality behavior, or override {@code equals}
* directly.
*
* <p>The {@code toString} method is forwarded to the delegate. Although this
* class does not implement {@link Serializable}, a serializable subclass may be
* created since this class has a parameter-less constructor.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingObject {
/** Constructor for use by subclasses. */
protected ForwardingObject() {}
/**
* Returns the backing delegate instance that methods are forwarded to.
* Abstract subclasses generally override this method with an abstract method
* that has a more specific return type, such as {@link
* ForwardingSet#delegate}. Concrete subclasses override this method to supply
* the instance being decorated.
*/
protected abstract Object delegate();
/**
* Returns the string representation generated by the delegate's
* {@code toString} method.
*/
@Override public String toString() {
return delegate().toString();
}
/* No equals or hashCode. See class comments for details. */
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A multiset which forwards all its method calls to another multiset.
* Subclasses should override one or more methods to modify the behavior of the
* backing multiset as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingMultiset} forward
* <b>indiscriminately</b> to the methods of the delegate. For example,
* overriding {@link #add(Object, int)} alone <b>will not</b> change the
* behavior of {@link #add(Object)}, which can lead to unexpected behavior. In
* this case, you should override {@code add(Object)} as well, either providing
* your own implementation, or delegating to the provided {@code standardAdd}
* method.
*
* <p>The {@code standard} methods and any collection views they return are not
* guaranteed to be thread-safe, even when all of the methods that they depend
* on are thread-safe.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingMultiset<E> extends ForwardingCollection<E>
implements Multiset<E> {
/** Constructor for use by subclasses. */
protected ForwardingMultiset() {}
@Override protected abstract Multiset<E> delegate();
@Override
public int count(Object element) {
return delegate().count(element);
}
@Override
public int add(E element, int occurrences) {
return delegate().add(element, occurrences);
}
@Override
public int remove(Object element, int occurrences) {
return delegate().remove(element, occurrences);
}
@Override
public Set<E> elementSet() {
return delegate().elementSet();
}
@Override
public Set<Entry<E>> entrySet() {
return delegate().entrySet();
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
@Override
public int setCount(E element, int count) {
return delegate().setCount(element, count);
}
@Override
public boolean setCount(E element, int oldCount, int newCount) {
return delegate().setCount(element, oldCount, newCount);
}
/**
* A sensible definition of {@link #contains} in terms of {@link #count}. If
* you override {@link #count}, you may wish to override {@link #contains} to
* forward to this implementation.
*
* @since 7.0
*/
@Override @Beta protected boolean standardContains(@Nullable Object object) {
return count(object) > 0;
}
/**
* A sensible definition of {@link #clear} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #clear} to forward to this implementation.
*
* @since 7.0
*/
@Override @Beta protected void standardClear() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
while (entryIterator.hasNext()) {
entryIterator.next();
entryIterator.remove();
}
}
/**
* A sensible, albeit inefficient, definition of {@link #count} in terms of
* {@link #entrySet}. If you override {@link #entrySet}, you may wish to
* override {@link #count} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardCount(@Nullable Object object) {
for (Entry<?> entry : this.entrySet()) {
if (Objects.equal(entry.getElement(), object)) {
return entry.getCount();
}
}
return 0;
}
/**
* A sensible definition of {@link #add(Object)} in terms of {@link
* #add(Object, int)}. If you override {@link #add(Object, int)}, you may
* wish to override {@link #add(Object)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardAdd(E element) {
add(element, 1);
return true;
}
/**
* A sensible definition of {@link #addAll(Collection)} in terms of {@link
* #add(Object)} and {@link #add(Object, int)}. If you override either of
* these methods, you may wish to override {@link #addAll(Collection)} to
* forward to this implementation.
*
* @since 7.0
*/
@Beta @Override protected boolean standardAddAll(
Collection<? extends E> elementsToAdd) {
return Multisets.addAllImpl(this, elementsToAdd);
}
/**
* A sensible definition of {@link #remove(Object)} in terms of {@link
* #remove(Object, int)}. If you override {@link #remove(Object, int)}, you
* may wish to override {@link #remove(Object)} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta @Override protected boolean standardRemove(Object element) {
return remove(element, 1) > 0;
}
/**
* A sensible definition of {@link #removeAll} in terms of the {@code
* removeAll} method of {@link #elementSet}. If you override {@link
* #elementSet}, you may wish to override {@link #removeAll} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta @Override protected boolean standardRemoveAll(
Collection<?> elementsToRemove) {
return Multisets.removeAllImpl(this, elementsToRemove);
}
/**
* A sensible definition of {@link #retainAll} in terms of the {@code
* retainAll} method of {@link #elementSet}. If you override {@link
* #elementSet}, you may wish to override {@link #retainAll} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta @Override protected boolean standardRetainAll(
Collection<?> elementsToRetain) {
return Multisets.retainAllImpl(this, elementsToRetain);
}
/**
* A sensible definition of {@link #setCount(Object, int)} in terms of {@link
* #count(Object)}, {@link #add(Object, int)}, and {@link #remove(Object,
* int)}. {@link #entrySet()}. If you override any of these methods, you may
* wish to override {@link #setCount(Object, int)} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected int standardSetCount(E element, int count) {
return Multisets.setCountImpl(this, element, count);
}
/**
* A sensible definition of {@link #setCount(Object, int, int)} in terms of
* {@link #count(Object)} and {@link #setCount(Object, int)}. If you override
* either of these methods, you may wish to override {@link #setCount(Object,
* int, int)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardSetCount(
E element, int oldCount, int newCount) {
return Multisets.setCountImpl(this, element, oldCount, newCount);
}
/**
* A sensible implementation of {@link Multiset#elementSet} in terms of the
* following methods: {@link ForwardingMultiset#clear}, {@link
* ForwardingMultiset#contains}, {@link ForwardingMultiset#containsAll},
* {@link ForwardingMultiset#count}, {@link ForwardingMultiset#isEmpty}, the
* {@link Set#size} and {@link Set#iterator} methods of {@link
* ForwardingMultiset#entrySet}, and {@link ForwardingMultiset#remove(Object,
* int)}. In many situations, you may wish to override {@link
* ForwardingMultiset#elementSet} to forward to this implementation or a
* subclass thereof.
*
* @since 10.0
*/
@Beta
protected class StandardElementSet extends Multisets.ElementSet<E> {
/** Constructor for use by subclasses. */
public StandardElementSet() {}
@Override
Multiset<E> multiset() {
return ForwardingMultiset.this;
}
}
/**
* A sensible definition of {@link #iterator} in terms of {@link #entrySet}
* and {@link #remove(Object)}. If you override either of these methods, you
* may wish to override {@link #iterator} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected Iterator<E> standardIterator() {
return Multisets.iteratorImpl(this);
}
/**
* A sensible, albeit inefficient, definition of {@link #size} in terms of
* {@link #entrySet}. If you override {@link #entrySet}, you may wish to
* override {@link #size} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardSize() {
return Multisets.sizeImpl(this);
}
/**
* A sensible, albeit inefficient, definition of {@link #size} in terms of
* {@code entrySet().size()} and {@link #count}. If you override either of
* these methods, you may wish to override {@link #size} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected boolean standardEquals(@Nullable Object object) {
return Multisets.equalsImpl(this, object);
}
/**
* A sensible definition of {@link #hashCode} as {@code entrySet().hashCode()}
* . If you override {@link #entrySet}, you may wish to override {@link
* #hashCode} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardHashCode() {
return entrySet().hashCode();
}
/**
* A sensible definition of {@link #toString} as {@code entrySet().toString()}
* . If you override {@link #entrySet}, you may wish to override {@link
* #toString} to forward to this implementation.
*
* @since 7.0
*/
@Beta @Override protected String standardToString() {
return entrySet().toString();
}
}
| Java |
/*
* Copyright (C) 2010 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 com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* This class provides a skeletal implementation of the {@code Iterator}
* interface for sequences whose next element can always be derived from the
* previous element. Null elements are not supported, nor is the
* {@link #remove()} method.
*
* <p>Example: <pre> {@code
*
* Iterator<Integer> powersOfTwo =
* new AbstractSequentialIterator<Integer>(1) {
* protected Integer computeNext(Integer previous) {
* return (previous == 1 << 30) ? null : previous * 2;
* }
* };}</pre>
*
* @author Chris Povirk
* @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0)
*/
@GwtCompatible
public abstract class AbstractSequentialIterator<T>
extends UnmodifiableIterator<T> {
private T nextOrNull;
/**
* Creates a new iterator with the given first element, or, if {@code
* firstOrNull} is null, creates a new empty iterator.
*/
protected AbstractSequentialIterator(@Nullable T firstOrNull) {
this.nextOrNull = firstOrNull;
}
/**
* Returns the element that follows {@code previous}, or returns {@code null}
* if no elements remain. This method is invoked during each call to
* {@link #next()} in order to compute the result of a <i>future</i> call to
* {@code next()}.
*/
protected abstract T computeNext(T previous);
@Override
public final boolean hasNext() {
return nextOrNull != null;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return nextOrNull;
} finally {
nextOrNull = computeNext(nextOrNull);
}
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An object representing the differences between two maps.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface MapDifference<K, V> {
/**
* Returns {@code true} if there are no differences between the two maps;
* that is, if the maps are equal.
*/
boolean areEqual();
/**
* Returns an unmodifiable map containing the entries from the left map whose
* keys are not present in the right map.
*/
Map<K, V> entriesOnlyOnLeft();
/**
* Returns an unmodifiable map containing the entries from the right map whose
* keys are not present in the left map.
*/
Map<K, V> entriesOnlyOnRight();
/**
* Returns an unmodifiable map containing the entries that appear in both
* maps; that is, the intersection of the two maps.
*/
Map<K, V> entriesInCommon();
/**
* Returns an unmodifiable map describing keys that appear in both maps, but
* with different values.
*/
Map<K, ValueDifference<V>> entriesDiffering();
/**
* Compares the specified object with this instance for equality. Returns
* {@code true} if the given object is also a {@code MapDifference} and the
* values returned by the {@link #entriesOnlyOnLeft()}, {@link
* #entriesOnlyOnRight()}, {@link #entriesInCommon()} and {@link
* #entriesDiffering()} of the two instances are equal.
*/
@Override
boolean equals(@Nullable Object object);
/**
* Returns the hash code for this instance. This is defined as the hash code
* of <pre> {@code
*
* Arrays.asList(entriesOnlyOnLeft(), entriesOnlyOnRight(),
* entriesInCommon(), entriesDiffering())}</pre>
*/
@Override
int hashCode();
/**
* A difference between the mappings from two maps with the same key. The
* {@link #leftValue} and {@link #rightValue} are not equal, and one but not
* both of them may be null.
*
* @since 2.0 (imported from Google Collections Library)
*/
interface ValueDifference<V> {
/**
* Returns the value from the left map (possibly null).
*/
V leftValue();
/**
* Returns the value from the right map (possibly null).
*/
V rightValue();
/**
* Two instances are considered equal if their {@link #leftValue()}
* values are equal and their {@link #rightValue()} values are also equal.
*/
@Override boolean equals(@Nullable Object other);
/**
* The hash code equals the value
* {@code Arrays.asList(leftValue(), rightValue()).hashCode()}.
*/
@Override int hashCode();
}
}
| Java |
/*
* 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.checkNotNull;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A set of values of type {@code C} made up of zero or more <i>disjoint</i> {@linkplain Range
* ranges}.
*
* <p>It is guaranteed that {@linkplain Range#isConnected connected} ranges will be
* {@linkplain Range#span coalesced} together, and that {@linkplain Range#isEmpty empty} ranges
* will never be held in a {@code RangeSet}.
*
* <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
*/ abstract class RangeSet<C extends Comparable> {
RangeSet() {}
/**
* Determines whether any of this range set's member ranges contains {@code value}.
*/
public boolean contains(C value) {
return rangeContaining(value) != null;
}
/**
* Returns the unique range from this range set that {@linkplain Range#contains contains}
* {@code value}, or {@code null} if this range set does not contain {@code value}.
*/
public Range<C> rangeContaining(C value) {
checkNotNull(value);
for (Range<C> range : asRanges()) {
if (range.contains(value)) {
return range;
}
}
return null;
}
/**
* Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this
* range set. The returned set may be empty. The iterators returned by its
* {@link Iterable#iterator} method return the ranges in increasing order of lower bound
* (equivalently, of upper bound).
*/
public abstract Set<Range<C>> asRanges();
/**
* Returns {@code true} if this range set contains no ranges.
*/
public boolean isEmpty() {
return asRanges().isEmpty();
}
/**
* Returns a view of the complement of this {@code RangeSet}.
*
* <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports
* {@link #remove}, and vice versa.
*/
public abstract RangeSet<C> complement();
/**
* A basic, simple implementation of {@link #complement}. This is not efficient on all methods;
* for example, {@link #rangeContaining} and {@link #encloses} are linear-time.
*/
static class StandardComplement<C extends Comparable> extends RangeSet<C> {
final RangeSet<C> positive;
public StandardComplement(RangeSet<C> positive) {
this.positive = positive;
}
@Override
public boolean contains(C value) {
return !positive.contains(value);
}
@Override
public void add(Range<C> range) {
positive.remove(range);
}
@Override
public void remove(Range<C> range) {
positive.add(range);
}
private transient Set<Range<C>> asRanges;
@Override
public final Set<Range<C>> asRanges() {
Set<Range<C>> result = asRanges;
return (result == null) ? asRanges = createAsRanges() : result;
}
Set<Range<C>> createAsRanges() {
return new AbstractSet<Range<C>>() {
@Override
public Iterator<Range<C>> iterator() {
final Iterator<Range<C>> positiveIterator = positive.asRanges().iterator();
return new AbstractIterator<Range<C>>() {
Cut<C> prevCut = Cut.belowAll();
@Override
protected Range<C> computeNext() {
while (positiveIterator.hasNext()) {
Cut<C> oldCut = prevCut;
Range<C> positiveRange = positiveIterator.next();
prevCut = positiveRange.upperBound;
if (oldCut.compareTo(positiveRange.lowerBound) < 0) {
return new Range<C>(oldCut, positiveRange.lowerBound);
}
}
Cut<C> posInfinity = Cut.aboveAll();
if (prevCut.compareTo(posInfinity) < 0) {
Range<C> result = new Range<C>(prevCut, posInfinity);
prevCut = posInfinity;
return result;
}
return endOfData();
}
};
}
@Override
public int size() {
return Iterators.size(iterator());
}
};
}
@Override
public RangeSet<C> complement() {
return positive;
}
}
/**
* Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal
* range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal
* range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}.
*
* <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in
* the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover,
* if {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code add}
* operation
*/
public void add(Range<C> range) {
throw new UnsupportedOperationException();
}
/**
* Removes the specified range from this {@code RangeSet} (optional operation). After this
* operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}.
*
* <p>If {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code remove}
* operation
*/
public void remove(Range<C> range) {
throw new UnsupportedOperationException();
}
/**
* Returns {@code true} if there exists a member range in this range set which
* {@linkplain Range#encloses encloses} the specified range.
*/
public boolean encloses(Range<C> otherRange) {
for (Range<C> range : asRanges()) {
if (range.encloses(otherRange)) {
return true;
}
}
return false;
}
/**
* Returns {@code true} if for each member range in {@code other} there exists a member range in
* this range set which {@linkplain Range#encloses encloses} it. It follows that
* {@code this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if
* {@code other} is empty.
*
* <p>
* This is equivalent to checking if this range set {@link #encloses} each of the ranges in
* {@code other}.
*/
public boolean enclosesAll(RangeSet<C> other) {
for (Range<C> range : other.asRanges()) {
if (!encloses(range)) {
return false;
}
}
return true;
}
/**
* Adds all of the ranges from the specified range set to this range set (optional operation).
* After this operation, this range set is the minimal range set that
* {@linkplain #enclosesAll(RangeSet) encloses} both the original range set and {@code other}.
*
* <p>
* This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code addAll}
* operation
*/
public void addAll(RangeSet<C> other) {
for (Range<C> range : other.asRanges()) {
this.add(range);
}
}
/**
* Removes all of the ranges from the specified range set from this range set (optional
* operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will
* return {@code false}.
*
* <p>
* This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code removeAll}
* operation
*/
public void removeAll(RangeSet<C> other) {
for (Range<C> range : other.asRanges()) {
this.remove(range);
}
}
/**
* Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges
* according to {@link Range#equals(Object)}.
*/
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof RangeSet) {
RangeSet<?> other = (RangeSet<?>) obj;
return this.asRanges().equals(other.asRanges());
}
return false;
}
@Override
public final int hashCode() {
return asRanges().hashCode();
}
/**
* Returns a readable string representation of this range set. For example, if this
* {@code RangeSet} consisted of {@code Ranges.closed(1, 3)} and {@code Ranges.greaterThan(4)},
* this might return {@code " [1‥3](4‥+∞)}"}.
*/
@Override
public final String toString() {
StringBuilder builder = new StringBuilder();
builder.append('{');
for (Range<C> range : asRanges()) {
builder.append(range);
}
builder.append('}');
return builder.toString();
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Collection;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* A collection which forwards all its method calls to another collection.
* Subclasses should override one or more methods to modify the behavior of the
* backing collection as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingCollection} forward
* <b>indiscriminately</b> to the methods of the delegate. For example,
* overriding {@link #add} alone <b>will not</b> change the behavior of {@link
* #addAll}, which can lead to unexpected behavior. In this case, you should
* override {@code addAll} as well, either providing your own implementation, or
* delegating to the provided {@code standardAddAll} method.
*
* <p>The {@code standard} methods are not guaranteed to be thread-safe, even
* when all of the methods that they depend on are thread-safe.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingCollection<E> extends ForwardingObject
implements Collection<E> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingCollection() {}
@Override protected abstract Collection<E> delegate();
@Override
public Iterator<E> iterator() {
return delegate().iterator();
}
@Override
public int size() {
return delegate().size();
}
@Override
public boolean removeAll(Collection<?> collection) {
return delegate().removeAll(collection);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public boolean contains(Object object) {
return delegate().contains(object);
}
@Override
public boolean add(E element) {
return delegate().add(element);
}
@Override
public boolean remove(Object object) {
return delegate().remove(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return delegate().containsAll(collection);
}
@Override
public boolean addAll(Collection<? extends E> collection) {
return delegate().addAll(collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return delegate().retainAll(collection);
}
@Override
public void clear() {
delegate().clear();
}
@Override
public Object[] toArray() {
return delegate().toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return delegate().toArray(array);
}
/**
* A sensible definition of {@link #contains} in terms of {@link #iterator}.
* If you override {@link #iterator}, you may wish to override {@link
* #contains} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardContains(@Nullable Object object) {
return Iterators.contains(iterator(), object);
}
/**
* A sensible definition of {@link #containsAll} in terms of {@link #contains}
* . If you override {@link #contains}, you may wish to override {@link
* #containsAll} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardContainsAll(Collection<?> collection) {
for (Object o : collection) {
if (!contains(o)) {
return false;
}
}
return true;
}
/**
* A sensible definition of {@link #addAll} in terms of {@link #add}. If you
* override {@link #add}, you may wish to override {@link #addAll} to forward
* to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardAddAll(Collection<? extends E> collection) {
return Iterators.addAll(this, collection.iterator());
}
/**
* A sensible definition of {@link #remove} in terms of {@link #iterator},
* using the iterator's {@code remove} method. If you override {@link
* #iterator}, you may wish to override {@link #remove} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected boolean standardRemove(@Nullable Object object) {
Iterator<E> iterator = iterator();
while (iterator.hasNext()) {
if (Objects.equal(iterator.next(), object)) {
iterator.remove();
return true;
}
}
return false;
}
/**
* A sensible definition of {@link #removeAll} in terms of {@link #iterator},
* using the iterator's {@code remove} method. If you override {@link
* #iterator}, you may wish to override {@link #removeAll} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected boolean standardRemoveAll(Collection<?> collection) {
return Iterators.removeAll(iterator(), collection);
}
/**
* A sensible definition of {@link #retainAll} in terms of {@link #iterator},
* using the iterator's {@code remove} method. If you override {@link
* #iterator}, you may wish to override {@link #retainAll} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected boolean standardRetainAll(Collection<?> collection) {
return Iterators.retainAll(iterator(), collection);
}
/**
* A sensible definition of {@link #clear} in terms of {@link #iterator},
* using the iterator's {@code remove} method. If you override {@link
* #iterator}, you may wish to override {@link #clear} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected void standardClear() {
Iterator<E> iterator = iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
}
/**
* A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}.
* If you override {@link #isEmpty}, you may wish to override {@link #isEmpty}
* to forward to this implementation. Alternately, it may be more efficient to
* implement {@code isEmpty} as {@code size() == 0}.
*
* @since 7.0
*/
@Beta protected boolean standardIsEmpty() {
return !iterator().hasNext();
}
/**
* A sensible definition of {@link #toString} in terms of {@link #iterator}.
* If you override {@link #iterator}, you may wish to override {@link
* #toString} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected String standardToString() {
return Collections2.toStringImpl(this);
}
/**
* A sensible definition of {@link #toArray()} in terms of {@link
* #toArray(Object[])}. If you override {@link #toArray(Object[])}, you may
* wish to override {@link #toArray} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected Object[] standardToArray() {
Object[] newArray = new Object[size()];
return toArray(newArray);
}
/**
* A sensible definition of {@link #toArray(Object[])} in terms of {@link
* #size} and {@link #iterator}. If you override either of these methods, you
* may wish to override {@link #toArray} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected <T> T[] standardToArray(T[] array) {
return ObjectArrays.toArrayImpl(this, array);
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A high-performance, immutable {@code Set} with reliable, user-specified
* iteration order. Does not permit null elements.
*
* <p>Unlike {@link Collections#unmodifiableSet}, which is a <i>view</i> of a
* separate collection that can still change, an instance of this class contains
* its own private data and will <i>never</i> change. This class is convenient
* for {@code public static final} sets ("constant sets") and also lets you
* easily make a "defensive copy" of a set provided to your class by a caller.
*
* <p><b>Warning:</b> Like most sets, an {@code ImmutableSet} will not function
* correctly if an element is modified after being placed in the set. For this
* reason, and to avoid general confusion, it is strongly recommended to place
* only immutable objects into this collection.
*
* <p>This class has been observed to perform significantly better than {@link
* HashSet} for objects with very fast {@link Object#hashCode} implementations
* (as a well-behaved immutable object should). While this class's factory
* methods create hash-based instances, the {@link ImmutableSortedSet} subclass
* performs binary searches instead.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed
* outside its package as it has no public or protected constructors. Thus,
* instances of this type are guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @see ImmutableList
* @see ImmutableMap
* @author Kevin Bourrillion
* @author Nick Kralevich
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableSet<E> extends ImmutableCollection<E>
implements Set<E> {
/**
* Returns the empty immutable set. This set behaves and performs comparably
* to {@link Collections#emptySet}, and is preferable mainly for consistency
* and maintainability of your code.
*/
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings({"unchecked"})
public static <E> ImmutableSet<E> of() {
return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE;
}
/**
* Returns an immutable set containing a single element. This set behaves and
* performs comparably to {@link Collections#singleton}, but will not accept
* a null element. It is preferable mainly for consistency and
* maintainability of your code.
*/
public static <E> ImmutableSet<E> of(E element) {
return new SingletonImmutableSet<E>(element);
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableSet<E> of(E e1, E e2) {
return construct(2, e1, e2);
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3) {
return construct(3, e1, e2, e3);
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) {
return construct(4, e1, e2, e3, e4);
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) {
return construct(5, e1, e2, e3, e4, e5);
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6,
E... others) {
final int paramCount = 6;
Object[] elements = new Object[paramCount + others.length];
elements[0] = e1;
elements[1] = e2;
elements[2] = e3;
elements[3] = e4;
elements[4] = e5;
elements[5] = e6;
System.arraycopy(others, 0, elements, paramCount, others.length);
return construct(elements.length, elements);
}
/**
* Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array.
* If {@code k} is the size of the returned {@code ImmutableSet}, then the unique elements of
* {@code elements} will be in the first {@code k} positions, and {@code elements[i] == null} for
* {@code k <= i < n}.
*
* <p>This may modify {@code elements}. Additionally, if {@code n == elements.length} and
* {@code elements} contains no duplicates, {@code elements} may be used without copying in the
* returned {@code ImmutableSet}, in which case it may no longer be modified.
*
* <p>{@code elements} may contain only values of type {@code E}.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code elements} is
* null
*/
private static <E> ImmutableSet<E> construct(int n, Object... elements) {
switch (n) {
case 0:
return of();
case 1: {
@SuppressWarnings("unchecked") // safe; elements contains only E's
E elem = (E) elements[0];
return of(elem);
}
}
int tableSize = chooseTableSize(n);
Object[] table = new Object[tableSize];
int mask = tableSize - 1;
int hashCode = 0;
int uniques = 0;
for (int i = 0; i < n; i++) {
Object element = ObjectArrays.checkElementNotNull(elements[i], i);
int hash = element.hashCode();
for (int j = Hashing.smear(hash); ; j++) {
int index = j & mask;
Object value = table[index];
if (value == null) {
// Came to an empty slot. Put the element here.
elements[uniques++] = element;
table[index] = element;
hashCode += hash;
break;
} else if (value.equals(element)) {
break;
}
}
}
Arrays.fill(elements, uniques, n, null);
if (uniques == 1) {
// There is only one element or elements are all duplicates
@SuppressWarnings("unchecked") // we are careful to only pass in E
E element = (E) elements[0];
return new SingletonImmutableSet<E>(element, hashCode);
} else if (tableSize != chooseTableSize(uniques)) {
// Resize the table when the array includes too many duplicates.
// when this happens, we have already made a copy
return construct(uniques, elements);
} else {
Object[] uniqueElements = (uniques < elements.length)
? ObjectArrays.arraysCopyOf(elements, uniques)
: elements;
return new RegularImmutableSet<E>(uniqueElements, hashCode, table, mask);
}
}
// We use power-of-2 tables, and this is the highest int that's a power of 2
static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;
// Represents how tightly we can pack things, as a maximum.
private static final double DESIRED_LOAD_FACTOR = 0.7;
// If the set has this many elements, it will "max out" the table size
private static final int CUTOFF =
(int) Math.floor(MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR);
/**
* Returns an array size suitable for the backing array of a hash table that
* uses open addressing with linear probing in its implementation. The
* returned size is the smallest power of two that can hold setSize elements
* with the desired load factor.
*
* <p>Do not call this method with setSize < 2.
*/
@VisibleForTesting static int chooseTableSize(int setSize) {
// Correct the size for open addressing to match desired load factor.
if (setSize < CUTOFF) {
// Round up to the next highest power of 2.
int tableSize = Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize <<= 1;
}
return tableSize;
}
// The table can't be completely full or we'll get infinite reprobes
checkArgument(setSize < MAX_TABLE_SIZE, "collection too large");
return MAX_TABLE_SIZE;
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E> ImmutableSet<E> copyOf(E[] elements) {
// TODO(benyu): could we delegate to
// copyFromCollection(Arrays.asList(elements))?
switch (elements.length) {
case 0:
return of();
case 1:
return of(elements[0]);
default:
return construct(elements.length, elements.clone());
}
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored. This method iterates over {@code elements} at most once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code
* ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing
* each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns
* a {@code ImmutableSet<Set<String>>} containing one element (the given set
* itself).
*
* <p>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 NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? copyOf(Collections2.cast(elements))
: copyOf(elements.iterator());
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) {
// We special-case for 0 or 1 elements, but anything further is madness.
if (!elements.hasNext()) {
return of();
}
E first = elements.next();
if (!elements.hasNext()) {
return of(first);
} else {
return new ImmutableSet.Builder<E>()
.add(first)
.addAll(elements)
.build();
}
}
/**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored. This method iterates over {@code elements} at most
* once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code
* ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing
* each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns
* a {@code ImmutableSet<Set<String>>} containing one element (the given set
* itself).
*
* <p><b>Note:</b> Despite what the method name suggests, {@code copyOf} will
* return constant-space views, rather than linear-space copies, of some
* inputs known to be immutable. For some other immutable inputs, such as key
* sets of an {@code ImmutableMap}, it still performs a copy in order to avoid
* holding references to the values of the map. The heuristics used in this
* decision are undocumented and subject to change except that:
* <ul>
* <li>A full copy will be done of any {@code ImmutableSortedSet}.</li>
* <li>{@code ImmutableSet.copyOf()} is idempotent with respect to pointer
* equality.</li>
* </ul>
*
* <p>This method is safe to use even when {@code elements} is a synchronized
* or concurrent collection that is currently being modified by another
* thread.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
if (elements instanceof ImmutableSet
&& !(elements instanceof ImmutableSortedSet)) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableSet<E> set = (ImmutableSet<E>) elements;
if (!set.isPartialView()) {
return set;
}
}
return copyFromCollection(elements);
}
private static <E> ImmutableSet<E> copyFromCollection(
Collection<? extends E> collection) {
Object[] elements = collection.toArray();
switch (elements.length) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") // collection had only Es in it
E onlyElement = (E) elements[0];
return of(onlyElement);
default:
// safe to use the array without copying it
// as specified by Collection.toArray().
return construct(elements.length, elements);
}
}
ImmutableSet() {}
/** Returns {@code true} if the {@code hashCode()} method runs quickly. */
boolean isHashCodeFast() {
return false;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof ImmutableSet
&& isHashCodeFast()
&& ((ImmutableSet<?>) object).isHashCodeFast()
&& hashCode() != object.hashCode()) {
return false;
}
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
// This declaration is needed to make Set.iterator() and
// ImmutableCollection.iterator() consistent.
@Override public abstract UnmodifiableIterator<E> iterator();
abstract static class ArrayImmutableSet<E> extends ImmutableSet<E> {
// the elements (two or more) in the desired order.
final transient Object[] elements;
ArrayImmutableSet(Object[] elements) {
this.elements = elements;
}
@Override
public int size() {
return elements.length;
}
@Override public boolean isEmpty() {
return false;
}
@Override public UnmodifiableIterator<E> iterator() {
return asList().iterator();
}
@Override public Object[] toArray() {
return asList().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return asList().toArray(array);
}
@Override public boolean containsAll(Collection<?> targets) {
if (targets == this) {
return true;
}
if (!(targets instanceof ArrayImmutableSet)) {
return super.containsAll(targets);
}
if (targets.size() > size()) {
return false;
}
for (Object target : ((ArrayImmutableSet<?>) targets).elements) {
if (!contains(target)) {
return false;
}
}
return true;
}
@Override boolean isPartialView() {
return false;
}
@Override ImmutableList<E> createAsList() {
return new RegularImmutableAsList<E>(this, elements);
}
}
/*
* This class is used to serialize all ImmutableSet instances, except for
* ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It
* captures their "logical contents" and they are reconstructed using public
* static factories. This is necessary to ensure that the existence of a
* particular implementation type is an implementation detail.
*/
private static class SerializedForm implements Serializable {
final Object[] elements;
SerializedForm(Object[] elements) {
this.elements = elements;
}
Object readResolve() {
return copyOf(elements);
}
private static final long serialVersionUID = 0;
}
@Override Object writeReplace() {
return new SerializedForm(toArray());
}
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<E>();
}
/**
* A builder for creating immutable set instances, especially {@code public
* static final} sets ("constant sets"). Example: <pre> {@code
*
* public static final ImmutableSet<Color> GOOGLE_COLORS =
* new ImmutableSet.Builder<Color>()
* .addAll(WEBSAFE_COLORS)
* .add(new Color(0, 191, 255))
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple sets in series. Each set is a superset of the set
* created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
Object[] contents;
int size;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSet#builder}.
*/
public Builder() {
this(DEFAULT_INITIAL_CAPACITY);
}
Builder(int capacity) {
checkArgument(capacity >= 0, "capacity must be >= 0 but was %s", capacity);
this.contents = new Object[capacity];
this.size = 0;
}
/**
* Expand capacity to allow the specified number of elements to be added.
*/
Builder<E> expandFor(int count) {
int minCapacity = size + count;
if (contents.length < minCapacity) {
contents = ObjectArrays.arraysCopyOf(
contents, expandedCapacity(contents.length, minCapacity));
}
return this;
}
/**
* Adds {@code element} to the {@code ImmutableSet}. If the {@code
* ImmutableSet} already contains {@code element}, then {@code add} has no
* effect (only the previously added element is retained).
*
* @param element the element to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
*/
@Override public Builder<E> add(E element) {
expandFor(1);
contents[size++] = checkNotNull(element);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> add(E... elements) {
for (int i = 0; i < elements.length; i++) {
ObjectArrays.checkElementNotNull(elements[i], i);
}
expandFor(elements.length);
System.arraycopy(elements, 0, contents, size, elements.length);
size += elements.length;
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the {@code Iterable} to add to the {@code ImmutableSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
Collection<?> collection = (Collection<?>) elements;
expandFor(collection.size());
}
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code 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 {@code ImmutableSet} based on the contents of
* the {@code Builder}.
*/
@Override public ImmutableSet<E> build() {
ImmutableSet<E> result = construct(size, contents);
// construct has the side effect of deduping contents, so we update size
// accordingly.
size = result.size();
return result;
}
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code keySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class ImmutableMapKeySet<K, V> extends TransformedImmutableSet<Entry<K, V>, K> {
ImmutableMapKeySet(ImmutableSet<Entry<K, V>> entrySet) {
super(entrySet);
}
ImmutableMapKeySet(ImmutableSet<Entry<K, V>> entrySet, int hashCode) {
super(entrySet, hashCode);
}
abstract ImmutableMap<K, V> map();
@Override
K transform(Entry<K, V> entry) {
return entry.getKey();
}
@Override
public boolean contains(@Nullable Object object) {
return map().containsKey(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
ImmutableList<K> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map().entrySet().asList();
return new ImmutableAsList<K>() {
@Override
public K get(int index) {
return entryList.get(index).getKey();
}
@Override
ImmutableCollection<K> delegateCollection() {
return ImmutableMapKeySet.this;
}
};
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new KeySetSerializedForm<K>(map());
}
@GwtIncompatible("serialization")
private static class KeySetSerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
KeySetSerializedForm(ImmutableMap<K, ?> map) {
this.map = map;
}
Object readResolve() {
return map.keySet();
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Workaround for
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6312706">
* EnumMap bug</a>. If you want to pass an {@code EnumMap}, with the
* intention of using its {@code entrySet()} method, you should
* wrap the {@code EnumMap} in this class instead.
*
* <p>This class is not thread-safe even if the underlying map is.
*
* @author Dimitris Andreou
*/
@GwtCompatible
final class WellBehavedMap<K, V> extends ForwardingMap<K, V> {
private final Map<K, V> delegate;
private Set<Entry<K, V>> entrySet;
private WellBehavedMap(Map<K, V> delegate) {
this.delegate = delegate;
}
/**
* Wraps the given map into a {@code WellBehavedEntriesMap}, which
* intercepts its {@code entrySet()} method by taking the
* {@code Set<K> keySet()} and transforming it to
* {@code Set<Entry<K, V>>}. All other invocations are delegated as-is.
*/
static <K, V> WellBehavedMap<K, V> wrap(Map<K, V> delegate) {
return new WellBehavedMap<K, V>(delegate);
}
@Override protected Map<K, V> delegate() {
return delegate;
}
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> es = entrySet;
if (es != null) {
return es;
}
return entrySet = new EntrySet();
}
private final class EntrySet extends Maps.EntrySet<K, V> {
@Override
Map<K, V> map() {
return WellBehavedMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new TransformedIterator<K, Entry<K, V>>(keySet().iterator()) {
@Override
Entry<K, V> transform(final K key) {
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return get(key);
}
@Override
public V setValue(V value) {
return put(key, value);
}
};
}
};
}
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMap} with exactly one entry.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class SingletonImmutableMap<K, V> extends ImmutableMap<K, V> {
final transient K singleKey;
final transient V singleValue;
SingletonImmutableMap(K singleKey, V singleValue) {
this.singleKey = singleKey;
this.singleValue = singleValue;
}
SingletonImmutableMap(Entry<K, V> entry) {
this(entry.getKey(), entry.getValue());
}
@Override public V get(@Nullable Object key) {
return singleKey.equals(key) ? singleValue : null;
}
@Override
public int size() {
return 1;
}
@Override public boolean isEmpty() {
return false;
}
@Override public boolean containsKey(@Nullable Object key) {
return singleKey.equals(key);
}
@Override public boolean containsValue(@Nullable Object value) {
return singleValue.equals(value);
}
@Override boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return ImmutableSet.of(Maps.immutableEntry(singleKey, singleValue));
}
@Override
ImmutableSet<K> createKeySet() {
return ImmutableSet.of(singleKey);
}
@Override
ImmutableCollection<V> createValues() {
return ImmutableList.of(singleValue);
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Map) {
Map<?, ?> that = (Map<?, ?>) object;
if (that.size() == 1) {
Entry<?, ?> entry = that.entrySet().iterator().next();
return singleKey.equals(entry.getKey())
&& singleValue.equals(entry.getValue());
}
}
return false;
}
@Override public int hashCode() {
return singleKey.hashCode() ^ singleValue.hashCode();
}
}
| Java |
/*
* 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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* Implementation of {@code Table} whose row keys and column keys are ordered
* by their natural ordering or by supplied comparators. When constructing a
* {@code TreeBasedTable}, you may provide comparators for the row keys and
* the column keys, or you may use natural ordering for both.
*
* <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link
* #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and
* {@link Map} specified by the {@link Table} interface.
*
* <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link
* #columnMap()} have iterators that don't support {@code remove()}. Otherwise,
* all optional operations are supported. Null row keys, columns keys, and
* values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because
* the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code
* column(columnKey).get(rowKey)} still runs quickly, since the row key is
* provided. However, {@code column(columnKey).size()} takes longer, since an
* iteration across all row keys occurs.
*
* <p>Because a {@code TreeBasedTable} has unique sorted values for a given
* row, both {@code row(rowKey)} and {@code rowMap().get(rowKey)} are {@link
* SortedMap} instances, instead of the {@link Map} specified in the {@link
* Table} interface.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access this table concurrently and one of the threads modifies the table, it
* must be synchronized externally.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table">
* {@code Table}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 7.0
*/
@GwtCompatible(serializable = true)
@Beta
public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> {
private final Comparator<? super C> columnComparator;
private static class Factory<C, V>
implements Supplier<TreeMap<C, V>>, Serializable {
final Comparator<? super C> comparator;
Factory(Comparator<? super C> comparator) {
this.comparator = comparator;
}
@Override
public TreeMap<C, V> get() {
return new TreeMap<C, V>(comparator);
}
private static final long serialVersionUID = 0;
}
/**
* Creates an empty {@code TreeBasedTable} that uses the natural orderings
* of both row and column keys.
*
* <p>The method signature specifies {@code R extends Comparable} with a raw
* {@link Comparable}, instead of {@code R extends Comparable<? super R>},
* and the same for {@code C}. That's necessary to support classes defined
* without generics.
*/
public static <R extends Comparable, C extends Comparable, V>
TreeBasedTable<R, C, V> create() {
return new TreeBasedTable<R, C, V>(Ordering.natural(),
Ordering.natural());
}
/**
* Creates an empty {@code TreeBasedTable} that is ordered by the specified
* comparators.
*
* @param rowComparator the comparator that orders the row keys
* @param columnComparator the comparator that orders the column keys
*/
public static <R, C, V> TreeBasedTable<R, C, V> create(
Comparator<? super R> rowComparator,
Comparator<? super C> columnComparator) {
checkNotNull(rowComparator);
checkNotNull(columnComparator);
return new TreeBasedTable<R, C, V>(rowComparator, columnComparator);
}
/**
* Creates a {@code TreeBasedTable} with the same mappings and sort order
* as the specified {@code TreeBasedTable}.
*/
public static <R, C, V> TreeBasedTable<R, C, V> create(
TreeBasedTable<R, C, ? extends V> table) {
TreeBasedTable<R, C, V> result
= new TreeBasedTable<R, C, V>(
table.rowComparator(), table.columnComparator());
result.putAll(table);
return result;
}
TreeBasedTable(Comparator<? super R> rowComparator,
Comparator<? super C> columnComparator) {
super(new TreeMap<R, Map<C, V>>(rowComparator),
new Factory<C, V>(columnComparator));
this.columnComparator = columnComparator;
}
// TODO(jlevy): Move to StandardRowSortedTable?
/**
* Returns the comparator that orders the rows. With natural ordering,
* {@link Ordering#natural()} is returned.
*/
public Comparator<? super R> rowComparator() {
return rowKeySet().comparator();
}
/**
* Returns the comparator that orders the columns. With natural ordering,
* {@link Ordering#natural()} is returned.
*/
public Comparator<? super C> columnComparator() {
return columnComparator;
}
// TODO(user): make column return a SortedMap
/**
* {@inheritDoc}
*
* <p>Because a {@code TreeBasedTable} has unique sorted values for a given
* row, this method returns a {@link SortedMap}, instead of the {@link Map}
* specified in the {@link Table} interface.
* @since 10.0
* (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
* >mostly source-compatible</a> since 7.0)
*/
@Override
public SortedMap<C, V> row(R rowKey) {
return new TreeRow(rowKey);
}
private class TreeRow extends Row implements SortedMap<C, V> {
@Nullable final C lowerBound;
@Nullable final C upperBound;
TreeRow(R rowKey) {
this(rowKey, null, null);
}
TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) {
super(rowKey);
this.lowerBound = lowerBound;
this.upperBound = upperBound;
checkArgument(lowerBound == null || upperBound == null
|| compare(lowerBound, upperBound) <= 0);
}
@Override public Comparator<? super C> comparator() {
return columnComparator();
}
int compare(Object a, Object b) {
// pretend we can compare anything
@SuppressWarnings({"rawtypes", "unchecked"})
Comparator<Object> cmp = (Comparator) comparator();
return cmp.compare(a, b);
}
boolean rangeContains(@Nullable Object o) {
return o != null && (lowerBound == null || compare(lowerBound, o) <= 0)
&& (upperBound == null || compare(upperBound, o) > 0);
}
@Override public SortedMap<C, V> subMap(C fromKey, C toKey) {
checkArgument(rangeContains(checkNotNull(fromKey))
&& rangeContains(checkNotNull(toKey)));
return new TreeRow(rowKey, fromKey, toKey);
}
@Override public SortedMap<C, V> headMap(C toKey) {
checkArgument(rangeContains(checkNotNull(toKey)));
return new TreeRow(rowKey, lowerBound, toKey);
}
@Override public SortedMap<C, V> tailMap(C fromKey) {
checkArgument(rangeContains(checkNotNull(fromKey)));
return new TreeRow(rowKey, fromKey, upperBound);
}
@Override public C firstKey() {
SortedMap<C, V> backing = backingRowMap();
if (backing == null) {
throw new NoSuchElementException();
}
return backingRowMap().firstKey();
}
@Override public C lastKey() {
SortedMap<C, V> backing = backingRowMap();
if (backing == null) {
throw new NoSuchElementException();
}
return backingRowMap().lastKey();
}
transient SortedMap<C, V> wholeRow;
/*
* If the row was previously empty, we check if there's a new row here every
* time we're queried.
*/
SortedMap<C, V> wholeRow() {
if (wholeRow == null
|| (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) {
wholeRow = (SortedMap<C, V>) backingMap.get(rowKey);
}
return wholeRow;
}
@Override
SortedMap<C, V> backingRowMap() {
return (SortedMap<C, V>) super.backingRowMap();
}
@Override
SortedMap<C, V> computeBackingRowMap() {
SortedMap<C, V> map = wholeRow();
if (map != null) {
if (lowerBound != null) {
map = map.tailMap(lowerBound);
}
if (upperBound != null) {
map = map.headMap(upperBound);
}
return map;
}
return null;
}
@Override
void maintainEmptyInvariant() {
if (wholeRow() != null && wholeRow.isEmpty()) {
backingMap.remove(rowKey);
wholeRow = null;
backingRowMap = null;
}
}
@Override public boolean containsKey(Object key) {
return rangeContains(key) && super.containsKey(key);
}
@Override public V put(C key, V value) {
checkArgument(rangeContains(checkNotNull(key)));
return super.put(key, value);
}
}
// rowKeySet() and rowMap() are defined here so they appear in the Javadoc.
@Override public SortedSet<R> rowKeySet() {
return super.rowKeySet();
}
@Override public SortedMap<R, Map<C, V>> rowMap() {
return super.rowMap();
}
// Overriding so NullPointerTester test passes.
@Override public boolean contains(
@Nullable Object rowKey, @Nullable Object columnKey) {
return super.contains(rowKey, columnKey);
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return super.containsColumn(columnKey);
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return super.containsRow(rowKey);
}
@Override public boolean containsValue(@Nullable Object value) {
return super.containsValue(value);
}
@Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
return super.get(rowKey, columnKey);
}
@Override public boolean equals(@Nullable Object obj) {
return super.equals(obj);
}
@Override public V remove(
@Nullable Object rowKey, @Nullable Object columnKey) {
return super.remove(rowKey, columnKey);
}
/**
* Overridden column iterator to return columns values in globally sorted
* order.
*/
@Override
Iterator<C> createColumnKeyIterator() {
final Comparator<? super C> comparator = columnComparator();
final Iterator<C> merged =
Iterators.mergeSorted(Iterables.transform(backingMap.values(),
new Function<Map<C, V>, Iterator<C>>() {
@Override
public Iterator<C> apply(Map<C, V> input) {
return input.keySet().iterator();
}
}), comparator);
return new AbstractIterator<C>() {
C lastValue;
@Override
protected C computeNext() {
while (merged.hasNext()) {
C next = merged.next();
boolean duplicate =
lastValue != null && comparator.compare(next, lastValue) == 0;
// Keep looping till we find a non-duplicate value.
if (!duplicate) {
lastValue = next;
return lastValue;
}
}
lastValue = null; // clear reference to unused data
return endOfData();
}
};
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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 com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
* Static utility methods pertaining to {@link Queue} and {@link Deque} instances.
* Also see this class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}.
*
* @author Kurt Alfred Kluever
* @since 11.0
*/
public final class Queues {
private Queues() {}
// ArrayBlockingQueue
/**
* Creates an empty {@code ArrayBlockingQueue} instance.
*
* @return a new, empty {@code ArrayBlockingQueue}
*/
public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) {
return new ArrayBlockingQueue<E>(capacity);
}
// ArrayDeque
/**
* Creates an empty {@code ArrayDeque} instance.
*
* @return a new, empty {@code ArrayDeque}
* @since 12.0
*/
public static <E> ArrayDeque<E> newArrayDeque() {
return new ArrayDeque<E>();
}
/**
* Creates an {@code ArrayDeque} instance containing the given elements.
*
* @param elements the elements that the queue should contain, in order
* @return a new {@code ArrayDeque} containing those elements
* @since 12.0
*/
public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new ArrayDeque<E>(Collections2.cast(elements));
}
ArrayDeque<E> deque = new ArrayDeque<E>();
Iterables.addAll(deque, elements);
return deque;
}
// ConcurrentLinkedQueue
/**
* Creates an empty {@code ConcurrentLinkedQueue} instance.
*
* @return a new, empty {@code ConcurrentLinkedQueue}
*/
public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() {
return new ConcurrentLinkedQueue<E>();
}
/**
* Creates an {@code ConcurrentLinkedQueue} instance containing the given elements.
*
* @param elements the elements that the queue should contain, in order
* @return a new {@code ConcurrentLinkedQueue} containing those elements
*/
public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new ConcurrentLinkedQueue<E>(Collections2.cast(elements));
}
ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<E>();
Iterables.addAll(queue, elements);
return queue;
}
// LinkedBlockingDeque
/**
* Creates an empty {@code LinkedBlockingDeque} instance.
*
* @return a new, empty {@code LinkedBlockingDeque}
* @since 12.0
*/
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() {
return new LinkedBlockingDeque<E>();
}
/**
* Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
*
* @param capacity the capacity of this deque
* @return a new, empty {@code LinkedBlockingDeque}
* @throws IllegalArgumentException if {@code capacity} is less than 1
* @since 12.0
*/
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) {
return new LinkedBlockingDeque<E>(capacity);
}
/**
* Creates an {@code LinkedBlockingDeque} instance containing the given elements.
*
* @param elements the elements that the queue should contain, in order
* @return a new {@code LinkedBlockingDeque} containing those elements
* @since 12.0
*/
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedBlockingDeque<E>(Collections2.cast(elements));
}
LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<E>();
Iterables.addAll(deque, elements);
return deque;
}
// LinkedBlockingQueue
/**
* Creates an empty {@code LinkedBlockingQueue} instance.
*
* @return a new, empty {@code LinkedBlockingQueue}
*/
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() {
return new LinkedBlockingQueue<E>();
}
/**
* Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
*
* @param capacity the capacity of this queue
* @return a new, empty {@code LinkedBlockingQueue}
* @throws IllegalArgumentException if {@code capacity} is less than 1
*/
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) {
return new LinkedBlockingQueue<E>(capacity);
}
/**
* Creates an {@code LinkedBlockingQueue} instance containing the given elements.
*
* @param elements the elements that the queue should contain, in order
* @return a new {@code LinkedBlockingQueue} containing those elements
*/
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedBlockingQueue<E>(Collections2.cast(elements));
}
LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<E>();
Iterables.addAll(queue, elements);
return queue;
}
// LinkedList: see {@link com.google.common.collect.Lists}
// PriorityBlockingQueue
/**
* Creates an empty {@code PriorityBlockingQueue} instance.
*
* @return a new, empty {@code PriorityBlockingQueue}
*/
public static <E> PriorityBlockingQueue<E> newPriorityBlockingQueue() {
return new PriorityBlockingQueue<E>();
}
/**
* Creates an {@code PriorityBlockingQueue} instance containing the given elements.
*
* @param elements the elements that the queue should contain, in order
* @return a new {@code PriorityBlockingQueue} containing those elements
*/
public static <E> PriorityBlockingQueue<E> newPriorityBlockingQueue(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new PriorityBlockingQueue<E>(Collections2.cast(elements));
}
PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>();
Iterables.addAll(queue, elements);
return queue;
}
// PriorityQueue
/**
* Creates an empty {@code PriorityQueue} instance.
*
* @return a new, empty {@code PriorityQueue}
*/
public static <E> PriorityQueue<E> newPriorityQueue() {
return new PriorityQueue<E>();
}
/**
* Creates an {@code PriorityQueue} instance containing the given elements.
*
* @param elements the elements that the queue should contain, in order
* @return a new {@code PriorityQueue} containing those elements
*/
public static <E> PriorityQueue<E> newPriorityQueue(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new PriorityQueue<E>(Collections2.cast(elements));
}
PriorityQueue<E> queue = new PriorityQueue<E>();
Iterables.addAll(queue, elements);
return queue;
}
// SynchronousQueue
/**
* Creates an empty {@code SynchronousQueue} instance.
*
* @return a new, empty {@code SynchronousQueue}
*/
public static <E> SynchronousQueue<E> newSynchronousQueue() {
return new SynchronousQueue<E>();
}
/**
* Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested
* {@code numElements} elements are not available, it will wait for them up to the specified
* timeout.
*
* @param q the blocking queue to be drained
* @param buffer where to add the transferred elements
* @param numElements the number of elements to be waited for
* @param timeout how long to wait before giving up, in units of {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
* @return the number of elements transferred
* @throws InterruptedException if interrupted while waiting
*/
@Beta
public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements,
long timeout, TimeUnit unit) throws InterruptedException {
Preconditions.checkNotNull(buffer);
/*
* This code performs one System.nanoTime() more than necessary, and in return, the time to
* execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
* the timeout arbitrarily inaccurate, given a queue that is slow to drain).
*/
long deadline = System.nanoTime() + unit.toNanos(timeout);
int added = 0;
while (added < numElements) {
// we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
// elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
added += q.drainTo(buffer, numElements - added);
if (added < numElements) { // not enough elements immediately available; will have to poll
E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
if (e == null) {
break; // we already waited enough, and there are no more elements in sight
}
buffer.add(e);
added++;
}
}
return added;
}
/**
* Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)},
* but with a different behavior in case it is interrupted while waiting. In that case, the
* operation will continue as usual, and in the end the thread's interruption status will be set
* (no {@code InterruptedException} is thrown).
*
* @param q the blocking queue to be drained
* @param buffer where to add the transferred elements
* @param numElements the number of elements to be waited for
* @param timeout how long to wait before giving up, in units of {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
* @return the number of elements transferred
*/
@Beta
public static <E> int drainUninterruptibly(BlockingQueue<E> q, Collection<? super E> buffer,
int numElements, long timeout, TimeUnit unit) {
Preconditions.checkNotNull(buffer);
long deadline = System.nanoTime() + unit.toNanos(timeout);
int added = 0;
boolean interrupted = false;
try {
while (added < numElements) {
// we could rely solely on #poll, but #drainTo might be more efficient when there are
// multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
added += q.drainTo(buffer, numElements - added);
if (added < numElements) { // not enough elements immediately available; will have to poll
E e; // written exactly once, by a successful (uninterrupted) invocation of #poll
while (true) {
try {
e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
break;
} catch (InterruptedException ex) {
interrupted = true; // note interruption and retry
}
}
if (e == null) {
break; // we already waited enough, and there are no more elements in sight
}
buffer.add(e);
added++;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
return added;
}
/**
* Returns a synchronized (thread-safe) queue backed by the specified queue. In order to
* guarantee serial access, it is critical that <b>all</b> access to the backing queue is
* accomplished through the returned queue.
*
* <p>It is imperative that the user manually synchronize on the returned queue when accessing
* the queue's iterator: <pre> {@code
*
* Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue<E>.create());
* ...
* queue.add(element); // Needn't be in synchronized block
* ...
* synchronized (queue) { // Must synchronize on queue!
* Iterator<E> i = queue.iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }}</pre>
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned queue will be serializable if the specified queue is serializable.
*
* @param queue the queue to be wrapped in a synchronized view
* @return a synchronized view of the specified queue
* @since 14.0
*/
@Beta
public static <E> Queue<E> synchronizedQueue(Queue<E> queue) {
return Synchronized.queue(queue, null);
}
}
| Java |
/*
* Copyright (C) 2007 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 static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.annotation.Nullable;
/**
* This class contains static utility methods that operate on or return objects
* of type {@link Iterator}. Except as noted, each method has a corresponding
* {@link Iterable}-based method in the {@link Iterables} class.
*
* <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators
* produced in this class are <i>lazy</i>, which means that they only advance
* the backing iteration when absolutely necessary.
*
* <p>See the Guava User Guide section on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables">
* {@code Iterators}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Iterators {
private Iterators() {}
static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR
= new UnmodifiableListIterator<Object>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
@Override
public boolean hasPrevious() {
return false;
}
@Override
public Object previous() {
throw new NoSuchElementException();
}
@Override
public int nextIndex() {
return 0;
}
@Override
public int previousIndex() {
return -1;
}
};
/**
* Returns the empty iterator.
*
* <p>The {@link Iterable} equivalent of this method is {@link
* ImmutableSet#of()}.
*/
public static <T> UnmodifiableIterator<T> emptyIterator() {
return emptyListIterator();
}
/**
* Returns the empty iterator.
*
* <p>The {@link Iterable} equivalent of this method is {@link
* ImmutableSet#of()}.
*/
// Casting to any type is safe since there are no actual elements.
@SuppressWarnings("unchecked")
static <T> UnmodifiableListIterator<T> emptyListIterator() {
return (UnmodifiableListIterator<T>) EMPTY_LIST_ITERATOR;
}
private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR =
new Iterator<Object>() {
@Override public boolean hasNext() {
return false;
}
@Override public Object next() {
throw new NoSuchElementException();
}
@Override public void remove() {
throw new IllegalStateException();
}
};
/**
* Returns the empty {@code Iterator} that throws
* {@link IllegalStateException} instead of
* {@link UnsupportedOperationException} on a call to
* {@link Iterator#remove()}.
*/
// Casting to any type is safe since there are no actual elements.
@SuppressWarnings("unchecked")
static <T> Iterator<T> emptyModifiableIterator() {
return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR;
}
/** Returns an unmodifiable view of {@code iterator}. */
public static <T> UnmodifiableIterator<T> unmodifiableIterator(
final Iterator<T> iterator) {
checkNotNull(iterator);
if (iterator instanceof UnmodifiableIterator) {
return (UnmodifiableIterator<T>) iterator;
}
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
};
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator(
UnmodifiableIterator<T> iterator) {
return checkNotNull(iterator);
}
/** Returns an unmodifiable view of {@code iterator}. */
static <T> UnmodifiableListIterator<T> unmodifiableListIterator(
final ListIterator<T> iterator) {
checkNotNull(iterator);
if (iterator instanceof UnmodifiableListIterator) {
return (UnmodifiableListIterator<T>) iterator;
}
return new UnmodifiableListIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public boolean hasPrevious() {
return iterator.hasPrevious();
}
@Override
public T next() {
return iterator.next();
}
@Override
public T previous() {
return iterator.previous();
}
@Override
public int nextIndex() {
return iterator.nextIndex();
}
@Override
public int previousIndex() {
return iterator.previousIndex();
}
};
}
/**
* Returns the number of elements remaining in {@code iterator}. The iterator
* will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*/
public static int size(Iterator<?> iterator) {
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
/**
* Returns {@code true} if {@code iterator} contains {@code element}.
*/
public static boolean contains(Iterator<?> iterator, @Nullable Object element)
{
if (element == null) {
while (iterator.hasNext()) {
if (iterator.next() == null) {
return true;
}
}
} else {
while (iterator.hasNext()) {
if (element.equals(iterator.next())) {
return true;
}
}
}
return false;
}
/**
* Traverses an iterator and removes every element that belongs to the
* provided collection. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param elementsToRemove the elements to remove
* @return {@code true} if any element was removed from {@code iterator}
*/
public static boolean removeAll(
Iterator<?> removeFrom, Collection<?> elementsToRemove) {
checkNotNull(elementsToRemove);
boolean modified = false;
while (removeFrom.hasNext()) {
if (elementsToRemove.contains(removeFrom.next())) {
removeFrom.remove();
modified = true;
}
}
return modified;
}
/**
* Removes every element that satisfies the provided predicate from the
* iterator. The iterator will be left exhausted: its {@code hasNext()}
* method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param predicate a predicate that determines whether an element should
* be removed
* @return {@code true} if any elements were removed from the iterator
* @since 2.0
*/
public static <T> boolean removeIf(
Iterator<T> removeFrom, Predicate<? super T> predicate) {
checkNotNull(predicate);
boolean modified = false;
while (removeFrom.hasNext()) {
if (predicate.apply(removeFrom.next())) {
removeFrom.remove();
modified = true;
}
}
return modified;
}
/**
* Traverses an iterator and removes every element that does not belong to the
* provided collection. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param elementsToRetain the elements to retain
* @return {@code true} if any element was removed from {@code iterator}
*/
public static boolean retainAll(
Iterator<?> removeFrom, Collection<?> elementsToRetain) {
checkNotNull(elementsToRetain);
boolean modified = false;
while (removeFrom.hasNext()) {
if (!elementsToRetain.contains(removeFrom.next())) {
removeFrom.remove();
modified = true;
}
}
return modified;
}
/**
* Determines whether two iterators contain equal elements in the same order.
* More specifically, this method returns {@code true} if {@code iterator1}
* and {@code iterator2} contain the same number of elements and every element
* of {@code iterator1} is equal to the corresponding element of
* {@code iterator2}.
*
* <p>Note that this will modify the supplied iterators, since they will have
* been advanced some number of elements forward.
*/
public static boolean elementsEqual(
Iterator<?> iterator1, Iterator<?> iterator2) {
while (iterator1.hasNext()) {
if (!iterator2.hasNext()) {
return false;
}
Object o1 = iterator1.next();
Object o2 = iterator2.next();
if (!Objects.equal(o1, o2)) {
return false;
}
}
return !iterator2.hasNext();
}
/**
* Returns a string representation of {@code iterator}, with the format
* {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*/
public static String toString(Iterator<?> iterator) {
return Joiner.on(", ")
.useForNull("null")
.appendTo(new StringBuilder().append('['), iterator)
.append(']')
.toString();
}
/**
* Returns the single element contained in {@code iterator}.
*
* @throws NoSuchElementException if the iterator is empty
* @throws IllegalArgumentException if the iterator contains multiple
* elements. The state of the iterator is unspecified.
*/
public static <T> T getOnlyElement(Iterator<T> iterator) {
T first = iterator.next();
if (!iterator.hasNext()) {
return first;
}
StringBuilder sb = new StringBuilder();
sb.append("expected one element but was: <" + first);
for (int i = 0; i < 4 && iterator.hasNext(); i++) {
sb.append(", " + iterator.next());
}
if (iterator.hasNext()) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}
/**
* Returns the single element contained in {@code iterator}, or {@code
* defaultValue} if the iterator is empty.
*
* @throws IllegalArgumentException if the iterator contains multiple
* elements. The state of the iterator is unspecified.
*/
@Nullable
public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
}
/**
* Copies an iterator's elements into an array. The iterator will be left
* exhausted: its {@code hasNext()} method will return {@code false}.
*
* @param iterator the iterator to copy
* @param type the type of the elements
* @return a newly-allocated array into which all the elements of the iterator
* have been copied
*/
@GwtIncompatible("Array.newInstance(Class, int)")
public static <T> T[] toArray(
Iterator<? extends T> iterator, Class<T> type) {
List<T> list = Lists.newArrayList(iterator);
return Iterables.toArray(list, type);
}
/**
* Adds all elements in {@code iterator} to {@code collection}. The iterator
* will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*
* @return {@code true} if {@code collection} was modified as a result of this
* operation
*/
public static <T> boolean addAll(
Collection<T> addTo, Iterator<? extends T> iterator) {
checkNotNull(addTo);
boolean wasModified = false;
while (iterator.hasNext()) {
wasModified |= addTo.add(iterator.next());
}
return wasModified;
}
/**
* Returns the number of elements in the specified iterator that equal the
* specified object. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @see Collections#frequency
*/
public static int frequency(Iterator<?> iterator, @Nullable Object element) {
int result = 0;
if (element == null) {
while (iterator.hasNext()) {
if (iterator.next() == null) {
result++;
}
}
} else {
while (iterator.hasNext()) {
if (element.equals(iterator.next())) {
result++;
}
}
}
return result;
}
/**
* Returns an iterator that cycles indefinitely over the elements of {@code
* iterable}.
*
* <p>The returned iterator supports {@code remove()} if the provided iterator
* does. After {@code remove()} is called, subsequent cycles omit the removed
* element, which is no longer in {@code iterable}. The iterator's
* {@code hasNext()} method returns {@code true} until {@code iterable} is
* empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*/
public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
checkNotNull(iterable);
return new Iterator<T>() {
Iterator<T> iterator = emptyIterator();
Iterator<T> removeFrom;
@Override
public boolean hasNext() {
if (!iterator.hasNext()) {
iterator = iterable.iterator();
}
return iterator.hasNext();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
removeFrom = iterator;
return iterator.next();
}
@Override
public void remove() {
checkState(removeFrom != null,
"no calls to next() since last call to remove()");
removeFrom.remove();
removeFrom = null;
}
};
}
/**
* Returns an iterator that cycles indefinitely over the provided elements.
*
* <p>The returned iterator supports {@code remove()} if the provided iterator
* does. After {@code remove()} is called, subsequent cycles omit the removed
* element, but {@code elements} does not change. The iterator's
* {@code hasNext()} method returns {@code true} until all of the original
* elements have been removed.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*/
public static <T> Iterator<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
}
/**
* Combines two iterators into a single iterator. The returned iterator
* iterates across the elements in {@code a}, followed by the elements in
* {@code b}. The source iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
@SuppressWarnings("unchecked")
public static <T> Iterator<T> concat(Iterator<? extends T> a,
Iterator<? extends T> b) {
checkNotNull(a);
checkNotNull(b);
return concat(Arrays.asList(a, b).iterator());
}
/**
* Combines three iterators into a single iterator. The returned iterator
* iterates across the elements in {@code a}, followed by the elements in
* {@code b}, followed by the elements in {@code c}. The source iterators
* are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
@SuppressWarnings("unchecked")
public static <T> Iterator<T> concat(Iterator<? extends T> a,
Iterator<? extends T> b, Iterator<? extends T> c) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
return concat(Arrays.asList(a, b, c).iterator());
}
/**
* Combines four iterators into a single iterator. The returned iterator
* iterates across the elements in {@code a}, followed by the elements in
* {@code b}, followed by the elements in {@code c}, followed by the elements
* in {@code d}. The source iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
@SuppressWarnings("unchecked")
public static <T> Iterator<T> concat(Iterator<? extends T> a,
Iterator<? extends T> b, Iterator<? extends T> c,
Iterator<? extends T> d) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
checkNotNull(d);
return concat(Arrays.asList(a, b, c, d).iterator());
}
/**
* Combines multiple iterators into a single iterator. The returned iterator
* iterates across the elements of each iterator in {@code inputs}. The input
* iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*
* @throws NullPointerException if any of the provided iterators is null
*/
public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
return concat(ImmutableList.copyOf(inputs).iterator());
}
/**
* Combines multiple iterators into a single iterator. The returned iterator
* iterates across the elements of each iterator in {@code inputs}. The input
* iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it. The methods of the returned iterator may throw
* {@code NullPointerException} if any of the input iterators is null.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
public static <T> Iterator<T> concat(
final Iterator<? extends Iterator<? extends T>> inputs) {
checkNotNull(inputs);
return new Iterator<T>() {
Iterator<? extends T> current = emptyIterator();
Iterator<? extends T> removeFrom;
@Override
public boolean hasNext() {
// http://code.google.com/p/google-collections/issues/detail?id=151
// current.hasNext() might be relatively expensive, worth minimizing.
boolean currentHasNext;
// checkNotNull eager for GWT
// note: it must be here & not where 'current' is assigned,
// because otherwise we'll have called inputs.next() before throwing
// the first NPE, and the next time around we'll call inputs.next()
// again, incorrectly moving beyond the error.
while (!(currentHasNext = checkNotNull(current).hasNext())
&& inputs.hasNext()) {
current = inputs.next();
}
return currentHasNext;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
removeFrom = current;
return current.next();
}
@Override
public void remove() {
checkState(removeFrom != null,
"no calls to next() since last call to remove()");
removeFrom.remove();
removeFrom = null;
}
};
}
/**
* Divides an iterator into unmodifiable sublists of the given size (the final
* list may be smaller). For example, partitioning an iterator containing
* {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
* [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of
* three and two elements, all in the original order.
*
* <p>The returned lists implement {@link java.util.RandomAccess}.
*
* @param iterator the iterator to return a partitioned view of
* @param size the desired size of each partition (the last may be smaller)
* @return an iterator of immutable lists containing the elements of {@code
* iterator} divided into partitions
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> UnmodifiableIterator<List<T>> partition(
Iterator<T> iterator, int size) {
return partitionImpl(iterator, size, false);
}
/**
* Divides an iterator into unmodifiable sublists of the given size, padding
* the final iterator with null values if necessary. For example, partitioning
* an iterator containing {@code [a, b, c, d, e]} with a partition size of 3
* yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing
* two inner lists of three elements each, all in the original order.
*
* <p>The returned lists implement {@link java.util.RandomAccess}.
*
* @param iterator the iterator to return a partitioned view of
* @param size the desired size of each partition
* @return an iterator of immutable lists containing the elements of {@code
* iterator} divided into partitions (the final iterable may have
* trailing null elements)
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> UnmodifiableIterator<List<T>> paddedPartition(
Iterator<T> iterator, int size) {
return partitionImpl(iterator, size, true);
}
private static <T> UnmodifiableIterator<List<T>> partitionImpl(
final Iterator<T> iterator, final int size, final boolean pad) {
checkNotNull(iterator);
checkArgument(size > 0);
return new UnmodifiableIterator<List<T>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public List<T> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Object[] array = new Object[size];
int count = 0;
for (; count < size && iterator.hasNext(); count++) {
array[count] = iterator.next();
}
for (int i = count; i < size; i++) {
array[i] = null; // for GWT
}
@SuppressWarnings("unchecked") // we only put Ts in it
List<T> list = Collections.unmodifiableList(
(List<T>) Arrays.asList(array));
return (pad || count == size) ? list : list.subList(0, count);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate.
*/
public static <T> UnmodifiableIterator<T> filter(
final Iterator<T> unfiltered, final Predicate<? super T> predicate) {
checkNotNull(unfiltered);
checkNotNull(predicate);
return new AbstractIterator<T>() {
@Override protected T computeNext() {
while (unfiltered.hasNext()) {
T element = unfiltered.next();
if (predicate.apply(element)) {
return element;
}
}
return endOfData();
}
};
}
/**
* Returns all instances of class {@code type} in {@code unfiltered}. The
* returned iterator has elements whose class is {@code type} or a subclass of
* {@code type}.
*
* @param unfiltered an iterator containing objects of any type
* @param type the type of elements desired
* @return an unmodifiable iterator containing all elements of the original
* iterator that were of the requested type
*/
@SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
@GwtIncompatible("Class.isInstance")
public static <T> UnmodifiableIterator<T> filter(
Iterator<?> unfiltered, Class<T> type) {
return (UnmodifiableIterator<T>)
filter(unfiltered, Predicates.instanceOf(type));
}
/**
* Returns {@code true} if one or more elements returned by {@code iterator}
* satisfy the given predicate.
*/
public static <T> boolean any(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate);
while (iterator.hasNext()) {
T element = iterator.next();
if (predicate.apply(element)) {
return true;
}
}
return false;
}
/**
* Returns {@code true} if every element returned by {@code iterator}
* satisfies the given predicate. If {@code iterator} is empty, {@code true}
* is returned.
*/
public static <T> boolean all(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate);
while (iterator.hasNext()) {
T element = iterator.next();
if (!predicate.apply(element)) {
return false;
}
}
return true;
}
/**
* Returns the first element in {@code iterator} that satisfies the given
* predicate; use this method only when such an element is known to exist. If
* no such element is found, the iterator will be left exhausted: its {@code
* hasNext()} method will return {@code false}. If it is possible that
* <i>no</i> element will match, use {@link #tryFind} or {@link
* #find(Iterator, Predicate, Object)} instead.
*
* @throws NoSuchElementException if no element in {@code iterator} matches
* the given predicate
*/
public static <T> T find(
Iterator<T> iterator, Predicate<? super T> predicate) {
return filter(iterator, predicate).next();
}
/**
* Returns the first element in {@code iterator} that satisfies the given
* predicate. If no such element is found, {@code defaultValue} will be
* returned from this method and the iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}. Note that this can
* usually be handled more naturally using {@code
* tryFind(iterator, predicate).or(defaultValue)}.
*
* @since 7.0
*/
@Nullable
public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate,
@Nullable T defaultValue) {
UnmodifiableIterator<? extends T> filteredIterator = filter(iterator, predicate);
return filteredIterator.hasNext() ? filteredIterator.next() : defaultValue;
}
/**
* Returns an {@link Optional} containing the first element in {@code
* iterator} that satisfies the given predicate, if such an element exists. If
* no such element is found, an empty {@link Optional} will be returned from
* this method and the the iterator will be left exhausted: its {@code
* hasNext()} method will return {@code false}.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
* null}. If {@code null} is matched in {@code iterator}, a
* NullPointerException will be thrown.
*
* @since 11.0
*/
public static <T> Optional<T> tryFind(
Iterator<T> iterator, Predicate<? super T> predicate) {
UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate);
return filteredIterator.hasNext()
? Optional.of(filteredIterator.next())
: Optional.<T>absent();
}
/**
* Returns the index in {@code iterator} of the first element that satisfies
* the provided {@code predicate}, or {@code -1} if the Iterator has no such
* elements.
*
* <p>More formally, returns the lowest index {@code i} such that
* {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true},
* or {@code -1} if there is no such index.
*
* <p>If -1 is returned, the iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}. Otherwise,
* the iterator will be set to the element which satisfies the
* {@code predicate}.
*
* @since 2.0
*/
public static <T> int indexOf(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate, "predicate");
int i = 0;
while (iterator.hasNext()) {
T current = iterator.next();
if (predicate.apply(current)) {
return i;
}
i++;
}
return -1;
}
/**
* Returns an iterator that applies {@code function} to each element of {@code
* fromIterator}.
*
* <p>The returned iterator supports {@code remove()} if the provided iterator
* does. After a successful {@code remove()} call, {@code fromIterator} no
* longer contains the corresponding element.
*/
public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator,
final Function<? super F, ? extends T> function) {
checkNotNull(function);
return new TransformedIterator<F, T>(fromIterator) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
/**
* Advances {@code iterator} {@code position + 1} times, returning the
* element at the {@code position}th position.
*
* @param position position of the element to return
* @return the element at the specified position in {@code iterator}
* @throws IndexOutOfBoundsException if {@code position} is negative or
* greater than or equal to the number of elements remaining in
* {@code iterator}
*/
public static <T> T get(Iterator<T> iterator, int position) {
checkNonnegative(position);
int skipped = 0;
while (iterator.hasNext()) {
T t = iterator.next();
if (skipped++ == position) {
return t;
}
}
throw new IndexOutOfBoundsException("position (" + position
+ ") must be less than the number of elements that remained ("
+ skipped + ")");
}
private static void checkNonnegative(int position) {
if (position < 0) {
throw new IndexOutOfBoundsException("position (" + position
+ ") must not be negative");
}
}
/**
* Advances {@code iterator} {@code position + 1} times, returning the
* element at the {@code position}th position or {@code defaultValue}
* otherwise.
*
* @param position position of the element to return
* @param defaultValue the default value to return if the iterator is empty
* or if {@code position} is greater than the number of elements
* remaining in {@code iterator}
* @return the element at the specified position in {@code iterator} or
* {@code defaultValue} if {@code iterator} produces fewer than
* {@code position + 1} elements.
* @throws IndexOutOfBoundsException if {@code position} is negative
* @since 4.0
*/
@Nullable
public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) {
checkNonnegative(position);
try {
return get(iterator, position);
} catch (IndexOutOfBoundsException e) {
return defaultValue;
}
}
/**
* Returns the next element in {@code iterator} or {@code defaultValue} if
* the iterator is empty. The {@link Iterables} analog to this method is
* {@link Iterables#getFirst}.
*
* @param defaultValue the default value to return if the iterator is empty
* @return the next element of {@code iterator} or the default value
* @since 7.0
*/
@Nullable
public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? iterator.next() : defaultValue;
}
/**
* Advances {@code iterator} to the end, returning the last element.
*
* @return the last element of {@code iterator}
* @throws NoSuchElementException if the iterator is empty
*/
public static <T> T getLast(Iterator<T> iterator) {
while (true) {
T current = iterator.next();
if (!iterator.hasNext()) {
return current;
}
}
}
/**
* Advances {@code iterator} to the end, returning the last element or
* {@code defaultValue} if the iterator is empty.
*
* @param defaultValue the default value to return if the iterator is empty
* @return the last element of {@code iterator}
* @since 3.0
*/
@Nullable
public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? getLast(iterator) : defaultValue;
}
/**
* Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times
* or until {@code hasNext()} returns {@code false}, whichever comes first.
*
* @return the number of elements the iterator was advanced
* @since 13.0 (since 3.0 as {@code Iterators.skip})
*/
public static int advance(Iterator<?> iterator, int numberToAdvance) {
checkNotNull(iterator);
checkArgument(numberToAdvance >= 0, "number to advance cannot be negative");
int i;
for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
iterator.next();
}
return i;
}
/**
* Creates an iterator returning the first {@code limitSize} elements of the
* given iterator. If the original iterator does not contain that many
* elements, the returned iterator will have the same behavior as the original
* iterator. The returned iterator supports {@code remove()} if the original
* iterator does.
*
* @param iterator the iterator to limit
* @param limitSize the maximum number of elements in the returned iterator
* @throws IllegalArgumentException if {@code limitSize} is negative
* @since 3.0
*/
public static <T> Iterator<T> limit(
final Iterator<T> iterator, final int limitSize) {
checkNotNull(iterator);
checkArgument(limitSize >= 0, "limit is negative");
return new Iterator<T>() {
private int count;
@Override
public boolean hasNext() {
return count < limitSize && iterator.hasNext();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
count++;
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
};
}
/**
* Returns a view of the supplied {@code iterator} that removes each element
* from the supplied {@code iterator} as it is returned.
*
* <p>The provided iterator must support {@link Iterator#remove()} or
* else the returned iterator will fail on the first call to {@code
* next}.
*
* @param iterator the iterator to remove and return elements from
* @return an iterator that removes and returns elements from the
* supplied iterator
* @since 2.0
*/
public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
checkNotNull(iterator);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
T next = iterator.next();
iterator.remove();
return next;
}
};
}
// Methods only in Iterators, not in Iterables
/**
* Clears the iterator using its remove method.
*/
static void clear(Iterator<?> iterator) {
checkNotNull(iterator);
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
}
/**
* Returns an iterator containing the elements of {@code array} in order. The
* returned iterator is a view of the array; subsequent changes to the array
* will be reflected in the iterator.
*
* <p><b>Note:</b> It is often preferable to represent your data using a
* collection type, for example using {@link Arrays#asList(Object[])}, making
* this method unnecessary.
*
* <p>The {@code Iterable} equivalent of this method is either {@link
* Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}},
* or {@link ImmutableList#of}.
*/
public static <T> UnmodifiableIterator<T> forArray(final T... array) {
// TODO(kevinb): compare performance with Arrays.asList(array).iterator().
checkNotNull(array); // eager for GWT.
return new AbstractIndexedListIterator<T>(array.length) {
@Override protected T get(int index) {
return array[index];
}
};
}
/**
* Returns a list iterator containing the elements in the specified range of
* {@code array} in order, starting at the specified index.
*
* <p>The {@code Iterable} equivalent of this method is {@code
* Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.
*/
static <T> UnmodifiableListIterator<T> forArray(
final T[] array, final int offset, int length, int index) {
checkArgument(length >= 0);
int end = offset + length;
// Technically we should give a slightly more descriptive error on overflow
Preconditions.checkPositionIndexes(offset, end, array.length);
/*
* We can't use call the two-arg constructor with arguments (offset, end)
* because the returned Iterator is a ListIterator that may be moved back
* past the beginning of the iteration.
*/
return new AbstractIndexedListIterator<T>(length, index) {
@Override protected T get(int index) {
return array[offset + index];
}
};
}
/**
* Returns an iterator containing only {@code value}.
*
* <p>The {@link Iterable} equivalent of this method is {@link
* Collections#singleton}.
*/
public static <T> UnmodifiableIterator<T> singletonIterator(
@Nullable final T value) {
return new UnmodifiableIterator<T>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public T next() {
if (done) {
throw new NoSuchElementException();
}
done = true;
return value;
}
};
}
/**
* Adapts an {@code Enumeration} to the {@code Iterator} interface.
*
* <p>This method has no equivalent in {@link Iterables} because viewing an
* {@code Enumeration} as an {@code Iterable} is impossible. However, the
* contents can be <i>copied</i> into a collection using {@link
* Collections#list}.
*/
public static <T> UnmodifiableIterator<T> forEnumeration(
final Enumeration<T> enumeration) {
checkNotNull(enumeration);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return enumeration.hasMoreElements();
}
@Override
public T next() {
return enumeration.nextElement();
}
};
}
/**
* Adapts an {@code Iterator} to the {@code Enumeration} interface.
*
* <p>The {@code Iterable} equivalent of this method is either {@link
* Collections#enumeration} (if you have a {@link Collection}), or
* {@code Iterators.asEnumeration(collection.iterator())}.
*/
public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
checkNotNull(iterator);
return new Enumeration<T>() {
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public T nextElement() {
return iterator.next();
}
};
}
/**
* Implementation of PeekingIterator that avoids peeking unless necessary.
*/
private static class PeekingImpl<E> implements PeekingIterator<E> {
private final Iterator<? extends E> iterator;
private boolean hasPeeked;
private E peekedElement;
public PeekingImpl(Iterator<? extends E> iterator) {
this.iterator = checkNotNull(iterator);
}
@Override
public boolean hasNext() {
return hasPeeked || iterator.hasNext();
}
@Override
public E next() {
if (!hasPeeked) {
return iterator.next();
}
E result = peekedElement;
hasPeeked = false;
peekedElement = null;
return result;
}
@Override
public void remove() {
checkState(!hasPeeked, "Can't remove after you've peeked at next");
iterator.remove();
}
@Override
public E peek() {
if (!hasPeeked) {
peekedElement = iterator.next();
hasPeeked = true;
}
return peekedElement;
}
}
/**
* Returns a {@code PeekingIterator} backed by the given iterator.
*
* <p>Calls to the {@code peek} method with no intervening calls to {@code
* next} do not affect the iteration, and hence return the same object each
* time. A subsequent call to {@code next} is guaranteed to return the same
* object again. For example: <pre> {@code
*
* PeekingIterator<String> peekingIterator =
* Iterators.peekingIterator(Iterators.forArray("a", "b"));
* String a1 = peekingIterator.peek(); // returns "a"
* String a2 = peekingIterator.peek(); // also returns "a"
* String a3 = peekingIterator.next(); // also returns "a"}</pre>
*
* Any structural changes to the underlying iteration (aside from those
* performed by the iterator's own {@link PeekingIterator#remove()} method)
* will leave the iterator in an undefined state.
*
* <p>The returned iterator does not support removal after peeking, as
* explained by {@link PeekingIterator#remove()}.
*
* <p>Note: If the given iterator is already a {@code PeekingIterator},
* it <i>might</i> be returned to the caller, although this is neither
* guaranteed to occur nor required to be consistent. For example, this
* method <i>might</i> choose to pass through recognized implementations of
* {@code PeekingIterator} when the behavior of the implementation is
* known to meet the contract guaranteed by this method.
*
* <p>There is no {@link Iterable} equivalent to this method, so use this
* method to wrap each individual iterator as it is generated.
*
* @param iterator the backing iterator. The {@link PeekingIterator} assumes
* ownership of this iterator, so users should cease making direct calls
* to it after calling this method.
* @return a peeking iterator backed by that iterator. Apart from the
* additional {@link PeekingIterator#peek()} method, this iterator behaves
* exactly the same as {@code iterator}.
*/
public static <T> PeekingIterator<T> peekingIterator(
Iterator<? extends T> iterator) {
if (iterator instanceof PeekingImpl) {
// Safe to cast <? extends T> to <T> because PeekingImpl only uses T
// covariantly (and cannot be subclassed to add non-covariant uses).
@SuppressWarnings("unchecked")
PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
return peeking;
}
return new PeekingImpl<T>(iterator);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <T> PeekingIterator<T> peekingIterator(
PeekingIterator<T> iterator) {
return checkNotNull(iterator);
}
/**
* Returns an iterator over the merged contents of all given
* {@code iterators}, traversing every element of the input iterators.
* Equivalent entries will not be de-duplicated.
*
* <p>Callers must ensure that the source {@code iterators} are in
* non-descending order as this method does not sort its input.
*
* <p>For any equivalent elements across all {@code iterators}, it is
* undefined which element is returned first.
*
* @since 11.0
*/
@Beta
public static <T> UnmodifiableIterator<T> mergeSorted(
Iterable<? extends Iterator<? extends T>> iterators,
Comparator<? super T> comparator) {
checkNotNull(iterators, "iterators");
checkNotNull(comparator, "comparator");
return new MergingIterator<T>(iterators, comparator);
}
/**
* An iterator that performs a lazy N-way merge, calculating the next value
* each time the iterator is polled. This amortizes the sorting cost over the
* iteration and requires less memory than sorting all elements at once.
*
* <p>Retrieving a single element takes approximately O(log(M)) time, where M
* is the number of iterators. (Retrieving all elements takes approximately
* O(N*log(M)) time, where N is the total number of elements.)
*/
private static class MergingIterator<T> extends AbstractIterator<T> {
final Queue<PeekingIterator<T>> queue;
final Comparator<? super T> comparator;
public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators,
Comparator<? super T> itemComparator) {
this.comparator = itemComparator;
// A comparator that's used by the heap, allowing the heap
// to be sorted based on the top of each iterator.
Comparator<PeekingIterator<T>> heapComparator =
new Comparator<PeekingIterator<T>>() {
@Override
public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
return comparator.compare(o1.peek(), o2.peek());
}
};
queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator);
for (Iterator<? extends T> iterator : iterators) {
if (iterator.hasNext()) {
queue.add(Iterators.peekingIterator(iterator));
}
}
}
@Override
protected T computeNext() {
if (queue.isEmpty()) {
return endOfData();
}
PeekingIterator<T> nextIter = queue.poll();
T next = nextIter.next();
if (nextIter.hasNext()) {
queue.add(nextIter);
}
return next;
}
}
/**
* Precondition tester for {@code Iterator.remove()} that throws an exception with a consistent
* error message.
*/
static void checkRemove(boolean canRemove) {
checkState(canRemove, "no calls to next() since the last call to remove()");
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> ListIterator<T> cast(Iterator<T> iterator) {
return (ListIterator<T>) iterator;
}
}
| Java |
/*
* Copyright (C) 2010 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 com.google.common.annotations.GwtCompatible;
import java.util.List;
import javax.annotation.Nullable;
/**
* A list multimap which forwards all its method calls to another list multimap.
* Subclasses should override one or more methods to modify the behavior of
* the backing multimap as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Kurt Alfred Kluever
* @since 3.0
*/
@GwtCompatible
public abstract class ForwardingListMultimap<K, V>
extends ForwardingMultimap<K, V> implements ListMultimap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingListMultimap() {}
@Override protected abstract ListMultimap<K, V> delegate();
@Override public List<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override public List<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@Override public List<V> replaceValues(K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
}
| Java |
/*
* Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible;
/**
* Unused stub class, unreferenced under Java and manually emulated under GWT.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
abstract class ForwardingImmutableList<E> {
private ForwardingImmutableList() {}
}
| Java |
/*
* 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.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* An implementation of {@link RangeSet} backed by a {@link TreeMap}.
*
* @author Louis Wasserman
*/
@GwtIncompatible("uses NavigableMap") final class TreeRangeSet<C extends Comparable>
extends RangeSet<C> {
// TODO(user): override inefficient defaults
private final NavigableMap<Cut<C>, Range<C>> rangesByLowerCut;
/**
* Creates an empty {@code TreeRangeSet} instance.
*/
public static <C extends Comparable> TreeRangeSet<C> create() {
return new TreeRangeSet<C>(new TreeMap<Cut<C>, Range<C>>());
}
private TreeRangeSet(NavigableMap<Cut<C>, Range<C>> rangesByLowerCut) {
this.rangesByLowerCut = rangesByLowerCut;
}
private transient Set<Range<C>> asRanges;
@Override
public Set<Range<C>> asRanges() {
Set<Range<C>> result = asRanges;
return (result == null) ? asRanges = new AsRanges() : result;
}
final class AsRanges extends ForwardingCollection<Range<C>> implements Set<Range<C>> {
@Override
protected Collection<Range<C>> delegate() {
return rangesByLowerCut.values();
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override
public boolean equals(@Nullable Object o) {
return Sets.equalsImpl(this, o);
}
}
@Override
@Nullable
public Range<C> rangeContaining(C value) {
checkNotNull(value);
Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerCut.floorEntry(Cut.belowValue(value));
if (floorEntry != null && floorEntry.getValue().contains(value)) {
return floorEntry.getValue();
} else {
// TODO(kevinb): revisit this design choice
return null;
}
}
@Override
public boolean encloses(Range<C> range) {
checkNotNull(range);
Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerCut.floorEntry(range.lowerBound);
return floorEntry != null && floorEntry.getValue().encloses(range);
}
@Override
public void add(Range<C> rangeToAdd) {
checkNotNull(rangeToAdd);
if (rangeToAdd.isEmpty()) {
return;
}
// We will use { } to illustrate ranges currently in the range set, and < >
// to illustrate rangeToAdd.
Cut<C> lbToAdd = rangeToAdd.lowerBound;
Cut<C> ubToAdd = rangeToAdd.upperBound;
Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerCut.lowerEntry(lbToAdd);
if (entryBelowLB != null) {
// { <
Range<C> rangeBelowLB = entryBelowLB.getValue();
if (rangeBelowLB.upperBound.compareTo(lbToAdd) >= 0) {
// { < }, and we will need to coalesce
if (rangeBelowLB.upperBound.compareTo(ubToAdd) >= 0) {
// { < > }
ubToAdd = rangeBelowLB.upperBound;
/*
* TODO(cpovirk): can we just "return;" here? Or, can we remove this if() entirely? If
* not, add tests to demonstrate the problem with each approach
*/
}
lbToAdd = rangeBelowLB.lowerBound;
}
}
Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerCut.floorEntry(ubToAdd);
if (entryBelowUB != null) {
// { >
Range<C> rangeBelowUB = entryBelowUB.getValue();
if (rangeBelowUB.upperBound.compareTo(ubToAdd) >= 0) {
// { > }, and we need to coalesce
ubToAdd = rangeBelowUB.upperBound;
}
}
// Remove ranges which are strictly enclosed.
rangesByLowerCut.subMap(lbToAdd, ubToAdd).clear();
replaceRangeWithSameLowerBound(new Range<C>(lbToAdd, ubToAdd));
}
@Override
public void remove(Range<C> rangeToRemove) {
checkNotNull(rangeToRemove);
if (rangeToRemove.isEmpty()) {
return;
}
// We will use { } to illustrate ranges currently in the range set, and < >
// to illustrate rangeToRemove.
Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerCut.lowerEntry(rangeToRemove.lowerBound);
if (entryBelowLB != null) {
// { <
Range<C> rangeBelowLB = entryBelowLB.getValue();
if (rangeBelowLB.upperBound.compareTo(rangeToRemove.lowerBound) >= 0) {
// { < }, and we will need to subdivide
if (rangeBelowLB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) {
// { < > }
replaceRangeWithSameLowerBound(
new Range<C>(rangeToRemove.upperBound, rangeBelowLB.upperBound));
}
replaceRangeWithSameLowerBound(
new Range<C>(rangeBelowLB.lowerBound, rangeToRemove.lowerBound));
}
}
Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerCut.floorEntry(rangeToRemove.upperBound);
if (entryBelowUB != null) {
// { >
Range<C> rangeBelowUB = entryBelowUB.getValue();
if (rangeBelowUB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) {
// { > }
replaceRangeWithSameLowerBound(
new Range<C>(rangeToRemove.upperBound, rangeBelowUB.upperBound));
}
}
rangesByLowerCut.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void replaceRangeWithSameLowerBound(Range<C> range) {
if (range.isEmpty()) {
rangesByLowerCut.remove(range.lowerBound);
} else {
rangesByLowerCut.put(range.lowerBound, range);
}
}
private transient RangeSet<C> complement;
@Override
public RangeSet<C> complement() {
RangeSet<C> result = complement;
return (result == null) ? complement = createComplement() : result;
}
private RangeSet<C> createComplement() {
return new StandardComplement<C>(this);
}
}
| Java |
/*
* Copyright (C) 2007 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 java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.annotation.Nullable;
/** An ordering for a pre-existing comparator. */
@GwtCompatible(serializable = true)
final class ComparatorOrdering<T> extends Ordering<T> implements Serializable {
final Comparator<T> comparator;
ComparatorOrdering(Comparator<T> comparator) {
this.comparator = checkNotNull(comparator);
}
@Override public int compare(T a, T b) {
return comparator.compare(a, b);
}
// Override just to remove a level of indirection from inner loops
@Override public int binarySearch(List<? extends T> sortedList, T key) {
return Collections.binarySearch(sortedList, key, comparator);
}
// Override just to remove a level of indirection from inner loops
@Override public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
List<E> list = Lists.newArrayList(iterable);
Collections.sort(list, comparator);
return list;
}
// Override just to remove a level of indirection from inner loops
@Override public <E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
@SuppressWarnings("unchecked") // we'll only ever have E's in here
E[] elements = (E[]) Iterables.toArray(iterable);
for (E e : elements) {
checkNotNull(e);
}
Arrays.sort(elements, comparator);
return ImmutableList.asImmutableList(elements);
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof ComparatorOrdering) {
ComparatorOrdering<?> that = (ComparatorOrdering<?>) object;
return this.comparator.equals(that.comparator);
}
return false;
}
@Override public int hashCode() {
return comparator.hashCode();
}
@Override public String toString() {
return comparator.toString();
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2012 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 javax.annotation.Nullable;
/**
* An implementation of an immutable sorted map with one or more entries.
*
* @author Louis Wasserman
*/
@SuppressWarnings("serial") // uses writeReplace, not default serialization
final class RegularImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> {
private final transient RegularImmutableSortedSet<K> keySet;
private final transient ImmutableList<V> valueList;
RegularImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) {
this.keySet = keySet;
this.valueList = valueList;
}
RegularImmutableSortedMap(
RegularImmutableSortedSet<K> keySet,
ImmutableList<V> valueList,
ImmutableSortedMap<K, V> descendingMap) {
super(descendingMap);
this.keySet = keySet;
this.valueList = valueList;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
private class EntrySet extends ImmutableMapEntrySet<K, V> {
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<K, V>> createAsList() {
return new ImmutableAsList<Entry<K, V>>() {
// avoid additional indirection
private final ImmutableList<K> keyList = keySet().asList();
private final ImmutableList<V> valueList = values().asList();
@Override
public Entry<K, V> get(int index) {
return Maps.immutableEntry(keyList.get(index), valueList.get(index));
}
@Override
ImmutableCollection<Entry<K, V>> delegateCollection() {
return EntrySet.this;
}
};
}
@Override
ImmutableMap<K, V> map() {
return RegularImmutableSortedMap.this;
}
}
@Override
public ImmutableSortedSet<K> keySet() {
return keySet;
}
@Override
public ImmutableCollection<V> values() {
return valueList;
}
@Override
public V get(@Nullable Object key) {
int index = keySet.indexOf(key);
return (index == -1) ? null : valueList.get(index);
}
private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) {
if (fromIndex == 0 && toIndex == size()) {
return this;
} else if (fromIndex == toIndex) {
return emptyMap(comparator());
} else {
return from(
keySet.getSubSet(fromIndex, toIndex),
valueList.subList(fromIndex, toIndex));
}
}
@Override
public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive));
}
@Override
public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size());
}
@Override
ImmutableSortedMap<K, V> createDescendingMap() {
return new RegularImmutableSortedMap<K, V>(
(RegularImmutableSortedSet<K>) keySet.descendingSet(),
valueList.reverse(),
this);
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Implementation of {@link Multimap} using hash tables.
*
* <p>The multimap does not store duplicate key-value pairs. Adding a new
* key-value pair equal to an existing key-value pair has no effect.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedSetMultimap}.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class HashMultimap<K, V> extends AbstractSetMultimap<K, V> {
private static final int DEFAULT_VALUES_PER_KEY = 2;
@VisibleForTesting
transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
/**
* Creates a new, empty {@code HashMultimap} with the default initial
* capacities.
*/
public static <K, V> HashMultimap<K, V> create() {
return new HashMultimap<K, V>();
}
/**
* Constructs an empty {@code HashMultimap} with enough capacity to hold the
* specified numbers of keys and values without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> HashMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new HashMultimap<K, V>(expectedKeys, expectedValuesPerKey);
}
/**
* Constructs a {@code HashMultimap} with the same mappings as the specified
* multimap. If a key-value mapping appears multiple times in the input
* multimap, it only appears once in the constructed multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> HashMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new HashMultimap<K, V>(multimap);
}
private HashMultimap() {
super(new HashMap<K, Collection<V>>());
}
private HashMultimap(int expectedKeys, int expectedValuesPerKey) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
Preconditions.checkArgument(expectedValuesPerKey >= 0);
this.expectedValuesPerKey = expectedValuesPerKey;
}
private HashMultimap(Multimap<? extends K, ? extends V> multimap) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(
multimap.keySet().size()));
putAll(multimap);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code HashSet} for a collection of values for one key.
*
* @return a new {@code HashSet} containing a collection of values for one key
*/
@Override Set<V> createCollection() {
return Sets.<V>newHashSetWithExpectedSize(expectedValuesPerKey);
}
/**
* @serialData expectedValuesPerKey, number of distinct keys, and then for
* each distinct key: the key, number of values for that key, and the
* key's values
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(expectedValuesPerKey);
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = stream.readInt();
int distinctKeys = Serialization.readCount(stream);
Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys);
setMap(map);
Serialization.populateMultimap(this, stream, distinctKeys);
}
@GwtIncompatible("Not needed in emulated source")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 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.Objects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Throwables;
import com.google.common.base.Ticker;
import com.google.common.collect.MapMakerInternalMap.Strength;
import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* <p>A builder of {@link ConcurrentMap} instances having any combination of the following features:
*
* <ul>
* <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain
* SoftReference soft} references
* <li>notification of evicted (or otherwise removed) entries
* <li>on-demand computation of values for keys not already present
* </ul>
*
* <p>Usage example: <pre> {@code
*
* ConcurrentMap<Key, Graph> graphs = new MapMaker()
* .concurrencyLevel(4)
* .weakKeys()
* .makeComputingMap(
* new Function<Key, Graph>() {
* public Graph apply(Key key) {
* return createExpensiveGraph(key);
* }
* });}</pre>
*
* These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent map
* that behaves similarly to a {@link ConcurrentHashMap}.
*
* <p>The returned map is implemented as a hash table with similar performance characteristics to
* {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap}
* interface. It does not permit null keys or values.
*
* <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals
* equals} method) to determine equality for keys or values. However, if {@link #weakKeys} or {@link
* #softKeys} was specified, the map uses identity ({@code ==}) comparisons instead for keys.
* Likewise, if {@link #weakValues} or {@link #softValues} was specified, the map uses identity
* comparisons for values.
*
* <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means
* that they are safe for concurrent use, but if other threads modify the map after the iterator is
* created, it is undefined which of these changes, if any, are reflected in that iterator. These
* iterators never throw {@link ConcurrentModificationException}.
*
* <p>If soft or weak references were requested, it is possible for a key or value present in the
* the map to be reclaimed by the garbage collector. If this happens, the entry automatically
* disappears from the map. A partially-reclaimed entry is never exposed to the user. Any {@link
* java.util.Map.Entry} instance retrieved from the map's {@linkplain Map#entrySet entry set} is a
* snapshot of that entry's state at the time of retrieval; such entries do, however, support {@link
* java.util.Map.Entry#setValue}, which simply calls {@link Map#put} on the entry's key.
*
* <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all
* the configuration properties of the original map. During deserialization, if the original map had
* used soft or weak references, the entries are reconstructed as they were, but it's not unlikely
* they'll be quickly garbage-collected before they are ever accessed.
*
* <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link
* java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code
* WeakHashMap} uses {@link Object#equals}.
*
* @author Bob Lee
* @author Charles Fry
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class MapMaker extends GenericMapMaker<Object, Object> {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
private static final int DEFAULT_EXPIRATION_NANOS = 0;
static final int UNSET_INT = -1;
// TODO(kevinb): dispense with this after benchmarking
boolean useCustomMap;
int initialCapacity = UNSET_INT;
int concurrencyLevel = UNSET_INT;
int maximumSize = UNSET_INT;
Strength keyStrength;
Strength valueStrength;
long expireAfterWriteNanos = UNSET_INT;
long expireAfterAccessNanos = UNSET_INT;
RemovalCause nullRemovalCause;
Equivalence<Object> keyEquivalence;
Ticker ticker;
/**
* Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong
* values, and no automatic eviction of any kind.
*/
public MapMaker() {}
/**
* Sets a custom {@code Equivalence} strategy for comparing keys.
*
* <p>By default, the map uses {@link Equivalence#identity} to determine key equality when
* {@link #weakKeys} or {@link #softKeys} is specified, and {@link Equivalence#equals()}
* otherwise. The only place this is used is in {@link Interners.WeakInterner}.
*/
@GwtIncompatible("To be supported")
@Override
MapMaker keyEquivalence(Equivalence<Object> equivalence) {
checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = checkNotNull(equivalence);
this.useCustomMap = true;
return this;
}
Equivalence<Object> getKeyEquivalence() {
return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
}
/**
* Sets the minimum total size for the internal hash tables. For example, if the initial capacity
* is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
* having a hash table of size eight. Providing a large enough estimate at construction time
* avoids the need for expensive resizing operations later, but setting this value unnecessarily
* high wastes memory.
*
* @throws IllegalArgumentException if {@code initialCapacity} is negative
* @throws IllegalStateException if an initial capacity was already set
*/
@Override
public MapMaker initialCapacity(int initialCapacity) {
checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
this.initialCapacity);
checkArgument(initialCapacity >= 0);
this.initialCapacity = initialCapacity;
return this;
}
int getInitialCapacity() {
return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
}
/**
* Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an
* entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map
* evicts entries that are less likely to be used again. For example, the map may evict an entry
* because it hasn't been used recently or very often.
*
* <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted
* immediately. This has the same effect as invoking {@link #expireAfterWrite
* expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0,
* unit)}. It can be useful in testing, or to disable caching temporarily without a code change.
*
* <p>Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}.
*
* @param size the maximum size of the map
* @throws IllegalArgumentException if {@code size} is negative
* @throws IllegalStateException if a maximum size was already set
* @deprecated Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being
* replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@Override
MapMaker maximumSize(int size) {
checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
this.maximumSize);
checkArgument(size >= 0, "maximum size must not be negative");
this.maximumSize = size;
this.useCustomMap = true;
if (maximumSize == 0) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.SIZE;
}
return this;
}
/**
* Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
* table is internally partitioned to try to permit the indicated number of concurrent updates
* without contention. Because assignment of entries to these partitions is not necessarily
* uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
* accommodate as many threads as will ever concurrently modify the table. Using a significantly
* higher value than you need can waste space and time, and a significantly lower value can lead
* to thread contention. But overestimates and underestimates within an order of magnitude do not
* usually have much noticeable impact. A value of one permits only one thread to modify the map
* at a time, but since read operations can proceed concurrently, this still yields higher
* concurrency than full synchronization. Defaults to 4.
*
* <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will
* change again in the future. If you care about this value, you should always choose it
* explicitly.
*
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
@Override
public MapMaker concurrencyLevel(int concurrencyLevel) {
checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
this.concurrencyLevel);
checkArgument(concurrencyLevel > 0);
this.concurrencyLevel = concurrencyLevel;
return this;
}
int getConcurrencyLevel() {
return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
}
/**
* Specifies that each key (not value) stored in the map should be wrapped in a {@link
* WeakReference} (by default, strong references are used).
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of keys, which is a technical violation of the {@link Map}
* specification, and may not be what you expect.
*
* @throws IllegalStateException if the key strength was already set
* @see WeakReference
*/
@GwtIncompatible("java.lang.ref.WeakReference")
@Override
public MapMaker weakKeys() {
return setKeyStrength(Strength.WEAK);
}
/**
* <b>This method is broken.</b> Maps with soft keys offer no functional advantage over maps with
* weak keys, and they waste memory by keeping unreachable elements in the map. If your goal is to
* create a memory-sensitive map, then consider using soft values instead.
*
* <p>Specifies that each key (not value) stored in the map should be wrapped in a
* {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
* be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
* demand.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of keys, which is a technical violation of the {@link Map}
* specification, and may not be what you expect.
*
* @throws IllegalStateException if the key strength was already set
* @see SoftReference
* @deprecated use {@link #softValues} to create a memory-sensitive map, or {@link #weakKeys} to
* create a map that doesn't hold strong references to the keys.
* <b>This method is scheduled for deletion in January 2013.</b>
*/
@Deprecated
@GwtIncompatible("java.lang.ref.SoftReference")
@Override
public MapMaker softKeys() {
return setKeyStrength(Strength.SOFT);
}
MapMaker setKeyStrength(Strength strength) {
checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = checkNotNull(strength);
if (strength != Strength.STRONG) {
// STRONG could be used during deserialization.
useCustomMap = true;
}
return this;
}
Strength getKeyStrength() {
return firstNonNull(keyStrength, Strength.STRONG);
}
/**
* Specifies that each value (not key) stored in the map should be wrapped in a
* {@link WeakReference} (by default, strong references are used).
*
* <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
* candidate for caching; consider {@link #softValues} instead.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of values. This technically violates the specifications of
* the methods {@link Map#containsValue containsValue},
* {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
* {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
* expect.
*
* @throws IllegalStateException if the value strength was already set
* @see WeakReference
*/
@GwtIncompatible("java.lang.ref.WeakReference")
@Override
public MapMaker weakValues() {
return setValueStrength(Strength.WEAK);
}
/**
* Specifies that each value (not key) stored in the map should be wrapped in a
* {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
* be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
* demand.
*
* <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
* #maximumSize maximum size} instead of using soft references. You should only use this method if
* you are well familiar with the practical consequences of soft references.
*
* <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==})
* comparison to determine equality of values. This technically violates the specifications of
* the methods {@link Map#containsValue containsValue},
* {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and
* {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you
* expect.
*
* @throws IllegalStateException if the value strength was already set
* @see SoftReference
*/
@GwtIncompatible("java.lang.ref.SoftReference")
@Override
public MapMaker softValues() {
return setValueStrength(Strength.SOFT);
}
MapMaker setValueStrength(Strength strength) {
checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = checkNotNull(strength);
if (strength != Strength.STRONG) {
// STRONG could be used during deserialization.
useCustomMap = true;
}
return this;
}
Strength getValueStrength() {
return firstNonNull(valueStrength, Strength.STRONG);
}
/**
* Specifies that each entry should be automatically removed from the map once a fixed duration
* has elapsed after the entry's creation, or the most recent replacement of its value.
*
* <p>When {@code duration} is zero, elements can be successfully added to the map, but are
* evicted immediately. This has a very similar effect to invoking {@link #maximumSize
* maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
* a code change.
*
* <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
* write operations. Expired entries are currently cleaned up during write operations, or during
* occasional read operations in the absense of writes; though this behavior may change in the
* future.
*
* @param duration the length of time after an entry is created that it should be automatically
* removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to live or time to idle was already set
* @deprecated Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being
* replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@Override
MapMaker expireAfterWrite(long duration, TimeUnit unit) {
checkExpiration(duration, unit);
this.expireAfterWriteNanos = unit.toNanos(duration);
if (duration == 0 && this.nullRemovalCause == null) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.EXPIRED;
}
useCustomMap = true;
return this;
}
private void checkExpiration(long duration, TimeUnit unit) {
checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
expireAfterWriteNanos);
checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
expireAfterAccessNanos);
checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
}
long getExpireAfterWriteNanos() {
return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
}
/**
* Specifies that each entry should be automatically removed from the map once a fixed duration
* has elapsed after the entry's last read or write access.
*
* <p>When {@code duration} is zero, elements can be successfully added to the map, but are
* evicted immediately. This has a very similar effect to invoking {@link #maximumSize
* maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without
* a code change.
*
* <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or
* write operations. Expired entries are currently cleaned up during write operations, or during
* occasional read operations in the absense of writes; though this behavior may change in the
* future.
*
* @param duration the length of time after an entry is last accessed that it should be
* automatically removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to idle or time to live was already set
* @deprecated Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being
* replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that
* {@code CacheBuilder} is simply an enhanced API for an implementation which was branched
* from {@code MapMaker}.
*/
@Deprecated
@GwtIncompatible("To be supported")
@Override
MapMaker expireAfterAccess(long duration, TimeUnit unit) {
checkExpiration(duration, unit);
this.expireAfterAccessNanos = unit.toNanos(duration);
if (duration == 0 && this.nullRemovalCause == null) {
// SIZE trumps EXPIRED
this.nullRemovalCause = RemovalCause.EXPIRED;
}
useCustomMap = true;
return this;
}
long getExpireAfterAccessNanos() {
return (expireAfterAccessNanos == UNSET_INT)
? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
}
Ticker getTicker() {
return firstNonNull(ticker, Ticker.systemTicker());
}
/**
* Specifies a listener instance, which all maps built using this {@code MapMaker} will notify
* each time an entry is removed from the map by any means.
*
* <p>Each map built by this map maker after this method is called invokes the supplied listener
* after removing an element for any reason (see removal causes in {@link RemovalCause}). It will
* invoke the listener during invocations of any of that map's public methods (even read-only
* methods).
*
* <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance,
* this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original
* reference or the returned reference may be used to complete configuration and build the map,
* but only the "generic" one is type-safe. That is, it will properly prevent you from building
* maps whose key or value types are incompatible with the types accepted by the listener already
* provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard
* method-chaining idiom, as illustrated in the documentation at top, configuring a {@code
* MapMaker} and building your {@link Map} all in a single statement.
*
* <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map
* or cache whose key or value type is incompatible with the listener, you will likely experience
* a {@link ClassCastException} at some <i>undefined</i> point in the future.
*
* @throws IllegalStateException if a removal listener was already set
* @deprecated Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being
* replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code
* CacheBuilder} is simply an enhanced API for an implementation which was branched from
* {@code MapMaker}.
*/
@Deprecated
@GwtIncompatible("To be supported")
<K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) {
checkState(this.removalListener == null);
// safely limiting the kinds of maps this can produce
@SuppressWarnings("unchecked")
GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this;
me.removalListener = checkNotNull(listener);
useCustomMap = true;
return me;
}
/**
* Builds a thread-safe map, without on-demand computation of values. This method does not alter
* the state of this {@code MapMaker} instance, so it can be invoked again to create multiple
* independent maps.
*
* <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
* be performed atomically on the returned map. Additionally, {@code size} and {@code
* containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
* writes.
*
* @return a serializable concurrent map having the requested features
*/
@Override
public <K, V> ConcurrentMap<K, V> makeMap() {
if (!useCustomMap) {
return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
}
return (nullRemovalCause == null)
? new MapMakerInternalMap<K, V>(this)
: new NullConcurrentMap<K, V>(this);
}
/**
* Returns a MapMakerInternalMap for the benefit of internal callers that use features of
* that class not exposed through ConcurrentMap.
*/
@Override
@GwtIncompatible("MapMakerInternalMap")
<K, V> MapMakerInternalMap<K, V> makeCustomMap() {
return new MapMakerInternalMap<K, V>(this);
}
/**
* Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either
* returns an already-computed value for the given key, atomically computes it using the supplied
* function, or, if another thread is currently computing the value for this key, simply waits for
* that thread to finish and returns its computed value. Note that the function may be executed
* concurrently by multiple threads, but only for distinct keys.
*
* <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports
* {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the
* {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache
* (allowing checked exceptions to be thrown in the process), and more cleanly separates
* computation from the cache's {@code Map} view.
*
* <p>If an entry's value has not finished computing yet, query methods besides {@code get} return
* immediately as if an entry doesn't exist. In other words, an entry isn't externally visible
* until the value's computation completes.
*
* <p>{@link Map#get} on the returned map will never return {@code null}. It may throw:
*
* <ul>
* <li>{@link NullPointerException} if the key is null or the computing function returns a null
* result
* <li>{@link ComputationException} if an exception was thrown by the computing function. If that
* exception is already of type {@link ComputationException} it is propagated directly; otherwise
* it is wrapped.
* </ul>
*
* <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type
* {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at
* compile time. Passing an object of a type other than {@code K} can result in that object being
* unsafely passed to the computing function as type {@code K}, and unsafely stored in the map.
*
* <p>If {@link Map#put} is called before a computation completes, other threads waiting on the
* computation will wake up and return the stored value.
*
* <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked
* again to create multiple independent maps.
*
* <p>Insertion, removal, update, and access operations on the returned map safely execute
* concurrently by multiple threads. Iterators on the returned map are weakly consistent,
* returning elements reflecting the state of the map at some point at or since the creation of
* the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed
* concurrently with other operations.
*
* <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to
* be performed atomically on the returned map. Additionally, {@code size} and {@code
* containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent
* writes.
*
* @param computingFunction the function used to compute new values
* @return a serializable concurrent map having the requested features
* @deprecated Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced
* by {@link com.google.common.cache.CacheBuilder#build}. See the
* <a href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker
* Migration Guide</a> for more details.
* <b>This method is scheduled for deletion in February 2013.</b>
*/
@Deprecated
@Override
public <K, V> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction) {
return (nullRemovalCause == null)
? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction)
: new NullComputingConcurrentMap<K, V>(this, computingFunction);
}
/**
* Returns a string representation for this MapMaker instance. The exact form of the returned
* string is not specificed.
*/
@Override
public String toString() {
Objects.ToStringHelper s = Objects.toStringHelper(this);
if (initialCapacity != UNSET_INT) {
s.add("initialCapacity", initialCapacity);
}
if (concurrencyLevel != UNSET_INT) {
s.add("concurrencyLevel", concurrencyLevel);
}
if (maximumSize != UNSET_INT) {
s.add("maximumSize", maximumSize);
}
if (expireAfterWriteNanos != UNSET_INT) {
s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
}
if (expireAfterAccessNanos != UNSET_INT) {
s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
}
if (keyStrength != null) {
s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
}
if (valueStrength != null) {
s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
}
if (keyEquivalence != null) {
s.addValue("keyEquivalence");
}
if (removalListener != null) {
s.addValue("removalListener");
}
return s.toString();
}
/**
* An object that can receive a notification when an entry is removed from a map. The removal
* resulting in notification could have occured to an entry being manually removed or replaced, or
* due to eviction resulting from timed expiration, exceeding a maximum size, or garbage
* collection.
*
* <p>An instance may be called concurrently by multiple threads to process different entries.
* Implementations of this interface should avoid performing blocking calls or synchronizing on
* shared resources.
*
* @param <K> the most general type of keys this listener can listen for; for
* example {@code Object} if any key is acceptable
* @param <V> the most general type of values this listener can listen for; for
* example {@code Object} if any key is acceptable
*/
interface RemovalListener<K, V> {
/**
* Notifies the listener that a removal occurred at some point in the past.
*/
void onRemoval(RemovalNotification<K, V> notification);
}
/**
* A notification of the removal of a single entry. The key or value may be null if it was already
* garbage collected.
*
* <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong
* references to the key and value, regardless of the type of references the map may be using.
*/
static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> {
private static final long serialVersionUID = 0;
private final RemovalCause cause;
RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
super(key, value);
this.cause = cause;
}
/**
* Returns the cause for which the entry was removed.
*/
public RemovalCause getCause() {
return cause;
}
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
*/
public boolean wasEvicted() {
return cause.wasEvicted();
}
}
/**
* The reason why an entry was removed.
*/
enum RemovalCause {
/**
* The entry was manually removed by the user. This can result from the user invoking
* {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}.
*/
EXPLICIT {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry itself was not actually removed, but its value was replaced by the user. This can
* result from the user invoking {@link Map#put}, {@link Map#putAll},
* {@link ConcurrentMap#replace(Object, Object)}, or
* {@link ConcurrentMap#replace(Object, Object, Object)}.
*/
REPLACED {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry was removed automatically because its key or value was garbage-collected. This
* can occur when using {@link #softKeys}, {@link #softValues}, {@link #weakKeys}, or {@link
* #weakValues}.
*/
COLLECTED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry's expiration timestamp has passed. This can occur when using {@link
* #expireAfterWrite} or {@link #expireAfterAccess}.
*/
EXPIRED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry was evicted due to size constraints. This can occur when using {@link
* #maximumSize}.
*/
SIZE {
@Override
boolean wasEvicted() {
return true;
}
};
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link #EXPLICIT} nor {@link #REPLACED}).
*/
abstract boolean wasEvicted();
}
/** A map that is always empty and evicts on insertion. */
static class NullConcurrentMap<K, V> extends AbstractMap<K, V>
implements ConcurrentMap<K, V>, Serializable {
private static final long serialVersionUID = 0;
private final RemovalListener<K, V> removalListener;
private final RemovalCause removalCause;
NullConcurrentMap(MapMaker mapMaker) {
removalListener = mapMaker.getRemovalListener();
removalCause = mapMaker.nullRemovalCause;
}
// implements ConcurrentMap
@Override
public boolean containsKey(@Nullable Object key) {
return false;
}
@Override
public boolean containsValue(@Nullable Object value) {
return false;
}
@Override
public V get(@Nullable Object key) {
return null;
}
void notifyRemoval(K key, V value) {
RemovalNotification<K, V> notification =
new RemovalNotification<K, V>(key, value, removalCause);
removalListener.onRemoval(notification);
}
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
notifyRemoval(key, value);
return null;
}
@Override
public V putIfAbsent(K key, V value) {
return put(key, value);
}
@Override
public V remove(@Nullable Object key) {
return null;
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
return false;
}
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
return null;
}
@Override
public boolean replace(K key, @Nullable V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
return false;
}
@Override
public Set<Entry<K, V>> entrySet() {
return Collections.emptySet();
}
}
/** Computes on retrieval and evicts the result. */
static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> {
private static final long serialVersionUID = 0;
final Function<? super K, ? extends V> computingFunction;
NullComputingConcurrentMap(
MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) {
super(mapMaker);
this.computingFunction = checkNotNull(computingFunction);
}
@SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred
@Override
public V get(Object k) {
K key = (K) k;
V value = compute(key);
checkNotNull(value, computingFunction + " returned null for key " + key + ".");
notifyRemoval(key, value);
return value;
}
private V compute(K key) {
checkNotNull(key);
try {
return computingFunction.apply(key);
} catch (ComputationException e) {
throw e;
} catch (Throwable t) {
throw new ComputationException(t);
}
}
}
/**
* Overrides get() to compute on demand. Also throws an exception when {@code null} is returned
* from a computation.
*/
/*
* This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some
* cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950
*/
static final class ComputingMapAdapter<K, V>
extends ComputingConcurrentHashMap<K, V> implements Serializable {
private static final long serialVersionUID = 0;
ComputingMapAdapter(MapMaker mapMaker,
Function<? super K, ? extends V> computingFunction) {
super(mapMaker, computingFunction);
}
@SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map
@Override
public V get(Object key) {
V value;
try {
value = getOrCompute((K) key);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
Throwables.propagateIfInstanceOf(cause, ComputationException.class);
throw new ComputationException(cause);
}
if (value == null) {
throw new NullPointerException(computingFunction + " returned null for key " + key + ".");
}
return value;
}
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* A map entry which forwards all its method calls to another map entry.
* Subclasses should override one or more methods to modify the behavior of the
* backing map entry as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingMapEntry} forward
* <i>indiscriminately</i> to the methods of the delegate. For example,
* overriding {@link #getValue} alone <i>will not</i> change the behavior of
* {@link #equals}, which can lead to unexpected behavior. In this case, you
* should override {@code equals} as well, either providing your own
* implementation, or delegating to the provided {@code standardEquals} method.
*
* <p>Each of the {@code standard} methods, where appropriate, use {@link
* Objects#equal} to test equality for both keys and values. This may not be
* the desired behavior for map implementations that use non-standard notions of
* key equality, such as the entry of a {@code SortedMap} whose comparator is
* not consistent with {@code equals}.
*
* <p>The {@code standard} methods are not guaranteed to be thread-safe, even
* when all of the methods that they depend on are thread-safe.
*
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingMapEntry<K, V>
extends ForwardingObject implements Map.Entry<K, V> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingMapEntry() {}
@Override protected abstract Map.Entry<K, V> delegate();
@Override
public K getKey() {
return delegate().getKey();
}
@Override
public V getValue() {
return delegate().getValue();
}
@Override
public V setValue(V value) {
return delegate().setValue(value);
}
@Override public boolean equals(@Nullable Object object) {
return delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
/**
* A sensible definition of {@link #equals(Object)} in terms of {@link
* #getKey()} and {@link #getValue()}. If you override either of these
* methods, you may wish to override {@link #equals(Object)} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardEquals(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return Objects.equal(this.getKey(), that.getKey())
&& Objects.equal(this.getValue(), that.getValue());
}
return false;
}
/**
* A sensible definition of {@link #hashCode()} in terms of {@link #getKey()}
* and {@link #getValue()}. If you override either of these methods, you may
* wish to override {@link #hashCode()} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardHashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* A sensible definition of {@link #toString} in terms of {@link
* #getKey} and {@link #getValue}. If you override either of these
* methods, you may wish to override {@link #equals} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected String standardToString() {
return getKey() + "=" + getValue();
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* Static methods pertaining to {@link Range} instances. Each of the
* {@link Range nine types of ranges} can be constructed with a corresponding
* factory method:
*
* <dl>
* <dt>{@code (a..b)}
* <dd>{@link #open}
* <dt>{@code [a..b]}
* <dd>{@link #closed}
* <dt>{@code [a..b)}
* <dd>{@link #closedOpen}
* <dt>{@code (a..b]}
* <dd>{@link #openClosed}
* <dt>{@code (a..+∞)}
* <dd>{@link #greaterThan}
* <dt>{@code [a..+∞)}
* <dd>{@link #atLeast}
* <dt>{@code (-∞..b)}
* <dd>{@link #lessThan}
* <dt>{@code (-∞..b]}
* <dd>{@link #atMost}
* <dt>{@code (-∞..+∞)}
* <dd>{@link #all}
* </dl>
*
* <p>Additionally, {@link Range} instances can be constructed by passing the
* {@link BoundType bound types} explicitly.
*
* <dl>
* <dt>Bounded on both ends
* <dd>{@link #range}
* <dt>Unbounded on top ({@code (a..+∞)} or {@code (a..+∞)})
* <dd>{@link #downTo}
* <dt>Unbounded on bottom ({@code (-∞..b)} or {@code (-∞..b]})
* <dd>{@link #upTo}
* </dl>
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/RangesExplained">
* {@code Range}</a>.
*
* @author Kevin Bourrillion
* @author Gregory Kick
* @since 10.0
* @deprecated Use the corresponding method in {@link Range}.
*/
@Deprecated
@GwtCompatible
@Beta
public final class Ranges {
private Ranges() {}
/**
* Returns a range that contains all values strictly greater than {@code
* lower} and strictly less than {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than <i>or
* equal to</i> {@code upper}
*/
public static <C extends Comparable<?>> Range<C> open(C lower, C upper) {
return Range.open(lower, upper);
}
/**
* Returns a range that contains all values greater than or equal to
* {@code lower} and less than or equal to {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
*/
public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) {
return Range.closed(lower, upper);
}
/**
* Returns a range that contains all values greater than or equal to
* {@code lower} and strictly less than {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
*/
public static <C extends Comparable<?>> Range<C> closedOpen(
C lower, C upper) {
return Range.closedOpen(lower, upper);
}
/**
* Returns a range that contains all values strictly greater than {@code
* lower} and less than or equal to {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
*/
public static <C extends Comparable<?>> Range<C> openClosed(
C lower, C upper) {
return Range.openClosed(lower, upper);
}
/**
* Returns a range that contains any value from {@code lower} to {@code
* upper}, where each endpoint may be either inclusive (closed) or exclusive
* (open).
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code
* upper}
*/
public static <C extends Comparable<?>> Range<C> range(
C lower, BoundType lowerType, C upper, BoundType upperType) {
return Range.range(lower, lowerType, upper, upperType);
}
/**
* Returns a range that contains all values strictly less than {@code
* endpoint}.
*/
public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) {
return Range.lessThan(endpoint);
}
/**
* Returns a range that contains all values less than or equal to
* {@code endpoint}.
*/
public static <C extends Comparable<?>> Range<C> atMost(C endpoint) {
return Range.atMost(endpoint);
}
/**
* Returns a range with no lower bound up to the given endpoint, which may be
* either inclusive (closed) or exclusive (open).
*/
public static <C extends Comparable<?>> Range<C> upTo(
C endpoint, BoundType boundType) {
return Range.upTo(endpoint, boundType);
}
/**
* Returns a range that contains all values strictly greater than {@code
* endpoint}.
*/
public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) {
return Range.greaterThan(endpoint);
}
/**
* Returns a range that contains all values greater than or equal to
* {@code endpoint}.
*/
public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) {
return Range.atLeast(endpoint);
}
/**
* Returns a range from the given endpoint, which may be either inclusive
* (closed) or exclusive (open), with no upper bound.
*/
public static <C extends Comparable<?>> Range<C> downTo(
C endpoint, BoundType boundType) {
return Range.downTo(endpoint, boundType);
}
/** Returns a range that contains every value of type {@code C}. */
public static <C extends Comparable<?>> Range<C> all() {
return Range.all();
}
/**
* Returns a range that {@linkplain Range#contains(Comparable) contains} only
* the given value. The returned range is {@linkplain BoundType#CLOSED closed}
* on both ends.
*/
public static <C extends Comparable<?>> Range<C> singleton(C value) {
return Range.singleton(value);
}
/**
* Returns the minimal range that
* {@linkplain Range#contains(Comparable) contains} all of the given values.
* The returned range is {@linkplain BoundType#CLOSED closed} on both ends.
*
* @throws ClassCastException if the parameters are not <i>mutually
* comparable</i>
* @throws NoSuchElementException if {@code values} is empty
* @throws NullPointerException if any of {@code values} is null
*/
public static <C extends Comparable<?>> Range<C> encloseAll(
Iterable<C> values) {
return Range.encloseAll(values);
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.util.ListIterator;
/**
* A list iterator which forwards all its method calls to another list
* iterator. Subclasses should override one or more methods to modify the
* behavior of the backing iterator as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingListIterator<E> extends ForwardingIterator<E>
implements ListIterator<E> {
/** Constructor for use by subclasses. */
protected ForwardingListIterator() {}
@Override protected abstract ListIterator<E> delegate();
@Override
public void add(E element) {
delegate().add(element);
}
@Override
public boolean hasPrevious() {
return delegate().hasPrevious();
}
@Override
public int nextIndex() {
return delegate().nextIndex();
}
@Override
public E previous() {
return delegate().previous();
}
@Override
public int previousIndex() {
return delegate().previousIndex();
}
@Override
public void set(E element) {
delegate().set(element);
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* Implementation of the {@code equals}, {@code hashCode}, and {@code toString}
* methods of {@code Entry}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractMapEntry<K, V> implements Entry<K, V> {
@Override
public abstract K getKey();
@Override
public abstract V getValue();
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return Objects.equal(this.getKey(), that.getKey())
&& Objects.equal(this.getValue(), that.getValue());
}
return false;
}
@Override public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* Returns a string representation of the form {@code {key}={value}}.
*/
@Override public String toString() {
return getKey() + "=" + getValue();
}
}
| Java |
/*
* 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.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* {@code FluentIterable} provides a rich interface for manipulating {@code Iterable}s in a chained
* fashion. A {@code FluentIterable} can be created from an {@code Iterable}, or from a set of
* elements. The following types of methods are provided on {@code FluentIterable}:
* <ul>
* <li>chained methods which return a new {@code FluentIterable} based in some way on the contents
* of the current one (for example {@link #transform})
* <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection or
* array (for example {@link #toList})
* <li>element extraction methods which facilitate the retrieval of certain elements (for example
* {@link #last})
* <li>query methods which answer questions about the {@code FluentIterable}'s contents (for example
* {@link #anyMatch})
* </ul>
*
* <p>Here is an example that merges the lists returned by two separate database calls, transforms
* it by invoking {@code toString()} on each element, and returns the first 10 elements as an
* {@code ImmutableList}: <pre> {@code
*
* FluentIterable
* .from(database.getClientList())
* .filter(activeInLastMonth())
* .transform(Functions.toStringFunction())
* .limit(10)
* .toList();}</pre>
*
* Anything which can be done using {@code FluentIterable} could be done in a different fashion
* (often with {@link Iterables}), however the use of {@code FluentIterable} makes many sets of
* operations significantly more concise.
*
* @author Marcin Mikosik
* @since 12.0
*/
@Beta
@GwtCompatible(emulated = true)
public abstract class FluentIterable<E> implements Iterable<E> {
// We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
// checks on the _original_ iterable when FluentIterable.from is used.
private final Iterable<E> iterable;
/** Constructor for use by subclasses. */
protected FluentIterable() {
this.iterable = this;
}
FluentIterable(Iterable<E> iterable) {
this.iterable = checkNotNull(iterable);
}
/**
* Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it
* is already a {@code FluentIterable}.
*/
public static <E> FluentIterable<E> from(final Iterable<E> iterable) {
return (iterable instanceof FluentIterable) ? (FluentIterable<E>) iterable
: new FluentIterable<E>(iterable) {
@Override
public Iterator<E> iterator() {
return iterable.iterator();
}
};
}
/**
* Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
* but is intended to help call out cases where one migration from {@code Iterable} to
* {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
*
* @deprecated instances of {@code FluentIterable} don't need to be converted to
* {@code FluentIterable}
*/
@Deprecated
public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
return checkNotNull(iterable);
}
/**
* Returns a string representation of this fluent iterable, with the format
* {@code [e1, e2, ..., en]}.
*/
@Override
public String toString() {
return Iterables.toString(iterable);
}
/**
* Returns the number of elements in this fluent iterable.
*/
public final int size() {
return Iterables.size(iterable);
}
/**
* Returns {@code true} if this fluent iterable contains any object for which
* {@code equals(element)} is true.
*/
public final boolean contains(@Nullable Object element) {
return Iterables.contains(iterable, element);
}
/**
* Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of
* this fluent iterable.
*
* <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After
* {@code remove()} is called, subsequent cycles omit the removed element, which is no longer in
* this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until
* this fluent iterable is empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
* should use an explicit {@code break} or be certain that you will eventually remove all the
* elements.
*/
public final FluentIterable<E> cycle() {
return from(Iterables.cycle(iterable));
}
/**
* Returns the elements from this fluent iterable that satisfy a predicate. The
* resulting fluent iterable's iterator does not support {@code remove()}.
*/
public final FluentIterable<E> filter(Predicate<? super E> predicate) {
return from(Iterables.filter(iterable, predicate));
}
/**
* Returns the elements from this fluent iterable that are instances of class {@code type}.
*
* @param type the type of elements desired
*/
@GwtIncompatible("Class.isInstance")
public final <T> FluentIterable<T> filter(Class<T> type) {
return from(Iterables.filter(iterable, type));
}
/**
* Returns {@code true} if any element in this fluent iterable satisfies the predicate.
*/
public final boolean anyMatch(Predicate<? super E> predicate) {
return Iterables.any(iterable, predicate);
}
/**
* Returns {@code true} if every element in this fluent iterable satisfies the predicate.
* If this fluent iterable is empty, {@code true} is returned.
*/
public final boolean allMatch(Predicate<? super E> predicate) {
return Iterables.all(iterable, predicate);
}
/**
* Returns an {@link Optional} containing the first element in this fluent iterable that
* satisfies the given predicate, if such an element exists.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
* is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
*/
public final Optional<E> firstMatch(Predicate<? super E> predicate) {
return Iterables.tryFind(iterable, predicate);
}
/**
* Returns a fluent iterable that applies {@code function} to each element of this
* fluent iterable.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's
* iterator does. After a successful {@code remove()} call, this fluent iterable no longer
* contains the corresponding element.
*/
public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
return from(Iterables.transform(iterable, function));
}
/**
* Applies {@code function} to each element of this fluent iterable and returns
* a fluent iterable with the concatenated combination of results. {@code function}
* returns an Iterable of results.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if this
* function-returned iterables' iterator does. After a successful {@code remove()} call,
* the returned fluent iterable no longer contains the corresponding element.
*
* @since 13.0
*/
public <T> FluentIterable<T> transformAndConcat(
Function<? super E, ? extends Iterable<T>> function) {
return from(Iterables.concat(transform(function)));
}
/**
* Returns an {@link Optional} containing the first element in this fluent iterable.
* If the iterable is empty, {@code Optional.absent()} is returned.
*
* @throws NullPointerException if the first element is null; if this is a possibility, use
* {@code iterator().next()} or {@link Iterables#getFirst} instead.
*/
public final Optional<E> first() {
Iterator<E> iterator = iterable.iterator();
return iterator.hasNext()
? Optional.of(iterator.next())
: Optional.<E>absent();
}
/**
* Returns an {@link Optional} containing the last element in this fluent iterable.
* If the iterable is empty, {@code Optional.absent()} is returned.
*
* @throws NullPointerException if the last element is null; if this is a possibility, use
* {@link Iterables#getLast} instead.
*/
public final Optional<E> last() {
// Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
// TODO(kevinb): Support a concurrently modified collection?
if (iterable instanceof List) {
List<E> list = (List<E>) iterable;
if (list.isEmpty()) {
return Optional.absent();
}
return Optional.of(list.get(list.size() - 1));
}
Iterator<E> iterator = iterable.iterator();
if (!iterator.hasNext()) {
return Optional.absent();
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<E> sortedSet = (SortedSet<E>) iterable;
return Optional.of(sortedSet.last());
}
while (true) {
E current = iterator.next();
if (!iterator.hasNext()) {
return Optional.of(current);
}
}
}
/**
* Returns a view of this fluent iterable that skips its first {@code numberToSkip}
* elements. If this fluent iterable contains fewer than {@code numberToSkip} elements,
* the returned fluent iterable skips all of its elements.
*
* <p>Modifications to this fluent iterable before a call to {@code iterator()} are
* reflected in the returned fluent iterable. That is, the its iterator skips the first
* {@code numberToSkip} elements that exist when the iterator is created, not when {@code skip()}
* is called.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if the
* {@code Iterator} of this fluent iterable supports it. Note that it is <i>not</i>
* possible to delete the last skipped element by immediately calling {@code remove()} on the
* returned fluent iterable's iterator, as the {@code Iterator} contract states that a call
* to {@code * remove()} before a call to {@code next()} will throw an
* {@link IllegalStateException}.
*/
public final FluentIterable<E> skip(int numberToSkip) {
return from(Iterables.skip(iterable, numberToSkip));
}
/**
* Creates a fluent iterable with the first {@code size} elements of this
* fluent iterable. If this fluent iterable does not contain that many elements,
* the returned fluent iterable will have the same behavior as this fluent iterable.
* The returned fluent iterable's iterator supports {@code remove()} if this
* fluent iterable's iterator does.
*
* @param size the maximum number of elements in the returned fluent iterable
* @throws IllegalArgumentException if {@code size} is negative
*/
public final FluentIterable<E> limit(int size) {
return from(Iterables.limit(iterable, size));
}
/**
* Determines whether this fluent iterable is empty.
*/
public final boolean isEmpty() {
return !iterable.iterator().hasNext();
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
* proper sequence.
*
* @since 14.0 (since 12.0 as {@code toImmutableList()}).
*/
public final ImmutableList<E> toList() {
return ImmutableList.copyOf(iterable);
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this {@code
* FluentIterable} in the order specified by {@code comparator}. To produce an {@code
* ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
*
* @param comparator the function by which to sort list elements
* @throws NullPointerException if any element is null
* @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
*/
public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
return Ordering.from(comparator).immutableSortedCopy(iterable);
}
/**
* Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
* duplicates removed.
*
* @since 14.0 (since 12.0 as {@code toImmutableSet()}).
*/
public final ImmutableSet<E> toSet() {
return ImmutableSet.copyOf(iterable);
}
/**
* Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
* FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
* {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
* by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
*
* @param comparator the function by which to sort set elements
* @throws NullPointerException if any element is null
* @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
*/
public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
return ImmutableSortedSet.copyOf(comparator, iterable);
}
/**
* Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in
* the same order, mapped to values by the given function. If this iterable contains duplicate
* elements, the returned map will contain each distinct element once in the order it first
* appears.
*
* @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
return Maps.toMap(iterable, valueFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of applying a
* specified function to each item in this {@code FluentIterable} of values. Each element of this
* iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
* size as this iterable. The key used to store that value in the multimap will be the result of
* calling the function on that value. The resulting multimap is created as an immutable snapshot.
* In the returned multimap, keys appear in the order they are first encountered, and the values
* corresponding to each key appear in the same order as they are encountered.
*
* @param keyFunction the function used to produce the key for each value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code keyFunction} is null
* <li>An element in this fluent iterable is null
* <li>{@code keyFunction} returns {@code null} for any element of this iterable
* </ul>
* @since 14.0
*/
public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
return Multimaps.index(iterable, keyFunction);
}
/**
* Returns an immutable map for which the {@link java.util.Map#values} are the elements of this
* {@code FluentIterable} in the given order, and each key is the product of invoking a supplied
* function on its corresponding value.
*
* @param keyFunction the function used to produce the key for each value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in this fluent iterable
* @throws NullPointerException if any element of this fluent iterable is null, or if
* {@code keyFunction} produces {@code null} for any value
* @since 14.0
*/
public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
return Maps.uniqueIndex(iterable, keyFunction);
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this
* fluent iterable in proper sequence.
*
* @deprecated Use {@link #toList()} instead. This method is scheduled for removal in Guava 15.0.
*/
@Deprecated
public final ImmutableList<E> toImmutableList() {
return toList();
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this
* {@code FluentIterable} in the order specified by {@code comparator}. To produce an
* {@code ImmutableList} sorted by its natural ordering, use
* {@code toSortedImmutableList(Ordering.natural())}.
*
* @param comparator the function by which to sort list elements
* @throws NullPointerException if any element is null
* @since 13.0
* @deprecated Use {@link #toSortedList(Comparator)} instead. This method is scheduled for removal
* in Guava 15.0.
*/
@Deprecated
public final ImmutableList<E> toSortedImmutableList(Comparator<? super E> comparator) {
return toSortedList(comparator);
}
/**
* Returns an {@code ImmutableSet} containing all of the elements from this
* fluent iterable with duplicates removed.
*
* @deprecated Use {@link #toSet()} instead. This method is scheduled for removal in Guava 15.0.
*/
@Deprecated
public final ImmutableSet<E> toImmutableSet() {
return toSet();
}
/**
* Returns an {@code ImmutableSortedSet} containing all of the elements from this
* {@code FluentIterable} in the order specified by {@code comparator}, with duplicates
* (determined by {@code comparator.compare(x, y) == 0}) removed. To produce an
* {@code ImmutableSortedSet} sorted by its natural ordering, use
* {@code toImmutableSortedSet(Ordering.natural())}.
*
* @param comparator the function by which to sort set elements
* @throws NullPointerException if any element is null
* @deprecated Use {@link #toSortedSet(Comparator)} instead. This method is scheduled for removal
* in Guava 15.0.
*/
@Deprecated
public final ImmutableSortedSet<E> toImmutableSortedSet(Comparator<? super E> comparator) {
return toSortedSet(comparator);
}
/**
* Returns an array containing all of the elements from this fluent iterable in iteration order.
*
* @param type the type of the elements
* @return a newly-allocated array into which all the elements of this fluent iterable have
* been copied
*/
@GwtIncompatible("Array.newArray(Class, int)")
public final E[] toArray(Class<E> type) {
return Iterables.toArray(iterable, type);
}
/**
* Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
* calling {@code Iterables.addAll(collection, this)}.
*
* @param collection the collection to copy elements to
* @return {@code collection}, for convenience
* @since 14.0
*/
public final <C extends Collection<? super E>> C copyInto(C collection) {
checkNotNull(collection);
if (iterable instanceof Collection) {
collection.addAll(Collections2.cast(iterable));
} else {
for (E item : iterable) {
collection.add(item);
}
}
return collection;
}
/**
* Returns the element at the specified position in this fluent iterable.
*
* @param position position of the element to return
* @return the element at the specified position in this fluent iterable
* @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
* the size of this fluent iterable
*/
public final E get(int position) {
return Iterables.get(iterable, position);
}
/**
* Function that transforms {@code Iterable<E>} into a fluent iterable.
*/
private static class FromIterableFunction<E>
implements Function<Iterable<E>, FluentIterable<E>> {
@Override
public FluentIterable<E> apply(Iterable<E> fromObject) {
return FluentIterable.from(fromObject);
}
}
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedHashMap;
/**
* A {@code Multiset} implementation with predictable iteration order. Its
* iterator orders elements according to when the first occurrence of the
* element was added. When the multiset contains multiple instances of an
* element, those instances are consecutive in the iteration order. If all
* occurrences of an element are removed, after which that element is added to
* the multiset, the element will appear at the end of the iteration.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> {
/**
* Creates a new, empty {@code LinkedHashMultiset} using the default initial
* capacity.
*/
public static <E> LinkedHashMultiset<E> create() {
return new LinkedHashMultiset<E>();
}
/**
* Creates a new, empty {@code LinkedHashMultiset} with the specified expected
* number of distinct elements.
*
* @param distinctElements the expected number of distinct elements
* @throws IllegalArgumentException if {@code distinctElements} is negative
*/
public static <E> LinkedHashMultiset<E> create(int distinctElements) {
return new LinkedHashMultiset<E>(distinctElements);
}
/**
* Creates a new {@code LinkedHashMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself
* a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
*/
public static <E> LinkedHashMultiset<E> create(
Iterable<? extends E> elements) {
LinkedHashMultiset<E> multiset =
create(Multisets.inferDistinctElements(elements));
Iterables.addAll(multiset, elements);
return multiset;
}
private LinkedHashMultiset() {
super(new LinkedHashMap<E, Count>());
}
private LinkedHashMultiset(int distinctElements) {
// Could use newLinkedHashMapWithExpectedSize() if it existed
super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements)));
}
/**
* @serialData the number of distinct elements, the first element, its count,
* the second element, its count, and so on
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultiset(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int distinctElements = Serialization.readCount(stream);
setBackingMap(new LinkedHashMap<E, Count>(
Maps.capacity(distinctElements)));
Serialization.populateMultiset(this, stream, distinctElements);
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A multimap which forwards all its method calls to another multimap.
* Subclasses should override one or more methods to modify the behavior of
* the backing multimap as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Robert Konigsberg
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingMultimap<K, V> extends ForwardingObject
implements Multimap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingMultimap() {}
@Override protected abstract Multimap<K, V> delegate();
@Override
public Map<K, Collection<V>> asMap() {
return delegate().asMap();
}
@Override
public void clear() {
delegate().clear();
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
return delegate().containsEntry(key, value);
}
@Override
public boolean containsKey(@Nullable Object key) {
return delegate().containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return delegate().containsValue(value);
}
@Override
public Collection<Entry<K, V>> entries() {
return delegate().entries();
}
@Override
public Collection<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public Multiset<K> keys() {
return delegate().keys();
}
@Override
public Set<K> keySet() {
return delegate().keySet();
}
@Override
public boolean put(K key, V value) {
return delegate().put(key, value);
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
return delegate().putAll(key, values);
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
return delegate().putAll(multimap);
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
return delegate().remove(key, value);
}
@Override
public Collection<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@Override
public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
@Override
public int size() {
return delegate().size();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
}
| Java |
/*
* Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
*
* @author Mike Ward
*/
@GwtCompatible(serializable = true)
class EmptyImmutableSetMultimap extends ImmutableSetMultimap<Object, Object> {
static final EmptyImmutableSetMultimap INSTANCE
= new EmptyImmutableSetMultimap();
private EmptyImmutableSetMultimap() {
super(ImmutableMap.<Object, ImmutableSet<Object>>of(), 0, null);
}
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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.base.Function;
import com.google.common.base.Objects;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* An ordering that orders elements by applying an order to the result of a
* function on those elements.
*/
@GwtCompatible(serializable = true)
final class ByFunctionOrdering<F, T>
extends Ordering<F> implements Serializable {
final Function<F, ? extends T> function;
final Ordering<T> ordering;
ByFunctionOrdering(
Function<F, ? extends T> function, Ordering<T> ordering) {
this.function = checkNotNull(function);
this.ordering = checkNotNull(ordering);
}
@Override public int compare(F left, F right) {
return ordering.compare(function.apply(left), function.apply(right));
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof ByFunctionOrdering) {
ByFunctionOrdering<?, ?> that = (ByFunctionOrdering<?, ?>) object;
return this.function.equals(that.function)
&& this.ordering.equals(that.ordering);
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(function, ordering);
}
@Override public String toString() {
return ordering + ".onResultOf(" + function + ")";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import javax.annotation.Nullable;
/**
* Captures a free type variable that can be used in {@link TypeToken#where}.
* For example: <pre> {@code
*
* static <T> TypeToken<List<T>> listOf(Class<T> elementType) {
* return new TypeToken<List<T>>() {}
* .where(new TypeParameter<T>() {}, elementType);
* }
* }</pre>
*
* @author Ben Yu
* @since 12.0
*/
@Beta
public abstract class TypeParameter<T> extends TypeCapture<T> {
final TypeVariable<?> typeVariable;
private TypeParameter(TypeVariable<?> typeVariable) {
this.typeVariable = checkNotNull(typeVariable);
}
protected TypeParameter() {
Type type = capture();
checkArgument(type instanceof TypeVariable, "%s should be a type variable.", type);
this.typeVariable = (TypeVariable<?>) type;
}
@Override public final int hashCode() {
return typeVariable.hashCode();
}
@Override public final boolean equals(@Nullable Object o) {
if (o instanceof TypeParameter) {
TypeParameter<?> that = (TypeParameter<?>) o;
return typeVariable.equals(that.typeVariable);
}
return false;
}
@Override public String toString() {
return typeVariable.toString();
}
}
| Java |
/*
* Copyright (C) 2012 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.
*/
/**
* This package contains utilities to work with Java reflection.
* It is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
@javax.annotation.ParametersAreNonnullByDefault
package com.google.common.reflect;
| Java |
/*
* Copyright (C) 2006 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.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A {@link Type} with generics.
*
* <p>Operations that are otherwise only available in {@link Class} are implemented to support
* {@code Type}, for example {@link #isAssignableFrom}, {@link #isArray} and {@link
* #getComponentType}. It also provides additional utilities such as {@link #getTypes} and {@link
* #resolveType} etc.
*
* <p>There are three ways to get a {@code TypeToken} instance: <ul>
* <li>Wrap a {@code Type} obtained via reflection. For example: {@code
* TypeToken.of(method.getGenericReturnType())}.
* <li>Capture a generic type with a (usually anonymous) subclass. For example: <pre> {@code
*
* new TypeToken<List<String>>() {}
* }</pre>
* Note that it's critical that the actual type argument is carried by a subclass.
* The following code is wrong because it only captures the {@code <T>} type variable
* of the {@code listType()} method signature; while {@code <String>} is lost in erasure:
* <pre> {@code
*
* class Util {
* static <T> TypeToken<List<T>> listType() {
* return new TypeToken<List<T>>() {};
* }
* }
*
* TypeToken<List<String>> stringListType = Util.<String>listType();
* }</pre>
* <li>Capture a generic type with a (usually anonymous) subclass and resolve it against
* a context class that knows what the type parameters are. For example: <pre> {@code
* abstract class IKnowMyType<T> {
* TypeToken<T> type = new TypeToken<T>(getClass()) {};
* }
* new IKnowMyType<String>() {}.type => String
* }</pre>
* </ul>
*
* <p>{@code TypeToken} is serializable when no type variable is contained in the type.
*
* <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class,
* but with one important difference: it supports non-reified types such as {@code T},
* {@code List<T>} or even {@code List<? extends Number>}; while TypeLiteral does not.
* TypeToken is also serializable and offers numerous additional utility methods.
*
* @author Bob Lee
* @author Sven Mawson
* @author Ben Yu
* @since 12.0
*/
@Beta
@SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
private final Type runtimeType;
/** Resolver for resolving types with {@link #runtimeType} as context. */
private transient TypeResolver typeResolver;
/**
* Constructs a new type token of {@code T}.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute
* it at runtime despite erasure.
*
* <p>For example: <pre> {@code
*
* TypeToken<List<String>> t = new TypeToken<List<String>>() {};
* }</pre>
*/
protected TypeToken() {
this.runtimeType = capture();
checkState(!(runtimeType instanceof TypeVariable),
"Cannot construct a TypeToken for a type variable.\n" +
"You probably meant to call new TypeToken<%s>(getClass()) " +
"that can resolve the type variable for you.\n" +
"If you do need to create a TypeToken of a type variable, " +
"please use TypeToken.of() instead.", runtimeType);
}
/**
* Constructs a new type token of {@code T} while resolving free type variables in the context of
* {@code declaringClass}.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute
* it at runtime despite erasure.
*
* <p>For example: <pre> {@code
*
* abstract class IKnowMyType<T> {
* TypeToken<T> getMyType() {
* return new TypeToken<T>(getClass()) {};
* }
* }
*
* new IKnowMyType<String>() {}.getMyType() => String
* }</pre>
*/
protected TypeToken(Class<?> declaringClass) {
Type captured = super.capture();
if (captured instanceof Class) {
this.runtimeType = captured;
} else {
this.runtimeType = of(declaringClass).resolveType(captured).runtimeType;
}
}
private TypeToken(Type type) {
this.runtimeType = checkNotNull(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static <T> TypeToken<T> of(Class<T> type) {
return new SimpleTypeToken<T>(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static TypeToken<?> of(Type type) {
return new SimpleTypeToken<Object>(type);
}
/**
* Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by
* {@link java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by
* {@link java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
* <ul>
* <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned.
* <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
* returned.
* <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
* class. For example: {@code List<Integer>[] => List[]}.
* <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
* is returned. For example: {@code <X extends Foo> => Foo}.
* </ul>
*/
public final Class<? super T> getRawType() {
Class<?> rawType = getRawType(runtimeType);
@SuppressWarnings("unchecked") // raw type is |T|
Class<? super T> result = (Class<? super T>) rawType;
return result;
}
/**
* Returns the raw type of the class or parameterized type; if {@code T} is type variable or
* wildcard type, the raw types of all its upper bounds are returned.
*/
private ImmutableSet<Class<? super T>> getImmediateRawTypes() {
// Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>>
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableSet<Class<? super T>> result = (ImmutableSet) getRawTypes(runtimeType);
return result;
}
/** Returns the represented type. */
public final Type getType() {
return runtimeType;
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
* are substituted by {@code typeArg}. For example, it can be used to construct
* {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code
*
* static <K, V> TypeToken<Map<K, V>> mapOf(
* TypeToken<K> keyType, TypeToken<V> valueType) {
* return new TypeToken<Map<K, V>>() {}
* .where(new TypeParameter<K>() {}, keyType)
* .where(new TypeParameter<V>() {}, valueType);
* }
* }</pre>
*
* @param <X> The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
TypeResolver resolver = new TypeResolver()
.where(ImmutableMap.of(typeParam.typeVariable, typeArg.runtimeType));
// If there's any type error, we'd report now rather than later.
return new SimpleTypeToken<T>(resolver.resolveType(runtimeType));
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
* are substituted by {@code typeArg}. For example, it can be used to construct
* {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code
*
* static <K, V> TypeToken<Map<K, V>> mapOf(
* Class<K> keyType, Class<V> valueType) {
* return new TypeToken<Map<K, V>>() {}
* .where(new TypeParameter<K>() {}, keyType)
* .where(new TypeParameter<V>() {}, valueType);
* }
* }</pre>
*
* @param <X> The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
return where(typeParam, of(typeArg));
}
/**
* Resolves the given {@code type} against the type context represented by this type.
* For example: <pre> {@code
*
* new TypeToken<List<String>>() {}.resolveType(
* List.class.getMethod("get", int.class).getGenericReturnType())
* => String.class
* }</pre>
*/
public final TypeToken<?> resolveType(Type type) {
checkNotNull(type);
TypeResolver resolver = typeResolver;
if (resolver == null) {
resolver = (typeResolver = TypeResolver.accordingTo(runtimeType));
}
return of(resolver.resolveType(type));
}
private Type[] resolveInPlace(Type[] types) {
for (int i = 0; i < types.length; i++) {
types[i] = resolveType(types[i]).getType();
}
return types;
}
private TypeToken<?> resolveSupertype(Type type) {
TypeToken<?> supertype = resolveType(type);
// super types' type mapping is a subset of type mapping of this type.
supertype.typeResolver = typeResolver;
return supertype;
}
/**
* Returns the generic superclass of this type or {@code null} if the type represents
* {@link Object} or an interface. This method is similar but different from {@link
* Class#getGenericSuperclass}. For example, {@code
* new TypeToken<StringArrayList>() {}.getGenericSuperclass()} will return {@code
* new TypeToken<ArrayList<String>>() {}}; while {@code
* StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where {@code E}
* is the type variable declared by class {@code ArrayList}.
*
* <p>If this type is a type variable or wildcard, its first upper bound is examined and returned
* if the bound is a class or extends from a class. This means that the returned type could be a
* type variable too.
*/
@Nullable
final TypeToken<? super T> getGenericSuperclass() {
if (runtimeType instanceof TypeVariable) {
// First bound is always the super class, if one exists.
return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
}
if (runtimeType instanceof WildcardType) {
// wildcard has one and only one upper bound.
return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
}
Type superclass = getRawType().getGenericSuperclass();
if (superclass == null) {
return null;
}
@SuppressWarnings("unchecked") // super class of T
TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
return superToken;
}
@Nullable private TypeToken<? super T> boundAsSuperclass(Type bound) {
TypeToken<?> token = of(bound);
if (token.getRawType().isInterface()) {
return null;
}
@SuppressWarnings("unchecked") // only upper bound of T is passed in.
TypeToken<? super T> superclass = (TypeToken<? super T>) token;
return superclass;
}
/**
* Returns the generic interfaces that this type directly {@code implements}. This method is
* similar but different from {@link Class#getGenericInterfaces()}. For example, {@code
* new TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains
* {@code new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()}
* will return an array that contains {@code Iterable<T>}, where the {@code T} is the type
* variable declared by interface {@code Iterable}.
*
* <p>If this type is a type variable or wildcard, its upper bounds are examined and those that
* are either an interface or upper-bounded only by interfaces are returned. This means that the
* returned types could include type variables too.
*/
final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
if (runtimeType instanceof TypeVariable) {
return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
}
ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
for (Type interfaceType : getRawType().getGenericInterfaces()) {
@SuppressWarnings("unchecked") // interface of T
TypeToken<? super T> resolvedInterface = (TypeToken<? super T>)
resolveSupertype(interfaceType);
builder.add(resolvedInterface);
}
return builder.build();
}
private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
for (Type bound : bounds) {
@SuppressWarnings("unchecked") // upper bound of T
TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
if (boundType.getRawType().isInterface()) {
builder.add(boundType);
}
}
return builder.build();
}
/**
* Returns the set of interfaces and classes that this type is or is a subtype of. The returned
* types are parameterized with proper type arguments.
*
* <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
* necessarily a subtype of all the types following. Order between types without subtype
* relationship is arbitrary and not guaranteed.
*
* <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables
* aren't included (their super interfaces and superclasses are).
*/
public final TypeSet getTypes() {
return new TypeSet();
}
/**
* Returns the generic form of {@code superclass}. For example, if this is
* {@code ArrayList<String>}, {@code Iterable<String>} is returned given the
* input {@code Iterable.class}.
*/
public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
checkArgument(superclass.isAssignableFrom(getRawType()),
"%s is not a super class of %s", superclass, this);
if (runtimeType instanceof TypeVariable) {
return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
}
if (superclass.isArray()) {
return getArraySupertype(superclass);
}
@SuppressWarnings("unchecked") // resolved supertype
TypeToken<? super T> supertype = (TypeToken<? super T>)
resolveSupertype(toGenericType(superclass).runtimeType);
return supertype;
}
/**
* Returns subtype of {@code this} with {@code subclass} as the raw class.
* For example, if this is {@code Iterable<String>} and {@code subclass} is {@code List},
* {@code List<String>} is returned.
*/
public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
checkArgument(!(runtimeType instanceof TypeVariable),
"Cannot get subtype of type variable <%s>", this);
if (runtimeType instanceof WildcardType) {
return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
}
checkArgument(getRawType().isAssignableFrom(subclass),
"%s isn't a subclass of %s", subclass, this);
// unwrap array type if necessary
if (isArray()) {
return getArraySubtype(subclass);
}
@SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
TypeToken<? extends T> subtype = (TypeToken<? extends T>)
of(resolveTypeArgsForSubclass(subclass));
return subtype;
}
/** Returns true if this type is assignable from the given {@code type}. */
public final boolean isAssignableFrom(TypeToken<?> type) {
return isAssignableFrom(type.runtimeType);
}
/** Check if this type is assignable from the given {@code type}. */
public final boolean isAssignableFrom(Type type) {
return isAssignable(checkNotNull(type), runtimeType);
}
/**
* Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
* {@code <? extends Map<String, Integer>[]>} etc.
*/
public final boolean isArray() {
return getComponentType() != null;
}
/**
* Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
* {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned.
*/
@Nullable public final TypeToken<?> getComponentType() {
Type componentType = Types.getComponentType(runtimeType);
if (componentType == null) {
return null;
}
return of(componentType);
}
/**
* Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable<T, Object> method(Method method) {
checkArgument(of(method.getDeclaringClass()).isAssignableFrom(this),
"%s not declared by %s", method, this);
return new Invokable.MethodInvokable<T>(method) {
@Override Type getGenericReturnType() {
return resolveType(super.getGenericReturnType()).getType();
}
@Override Type[] getGenericParameterTypes() {
return resolveInPlace(super.getGenericParameterTypes());
}
@Override Type[] getGenericExceptionTypes() {
return resolveInPlace(super.getGenericExceptionTypes());
}
};
}
/**
* Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable<T, T> constructor(Constructor<?> constructor) {
checkArgument(constructor.getDeclaringClass() == getRawType(),
"%s not declared by %s", constructor, getRawType());
return new Invokable.ConstructorInvokable<T>(constructor) {
@Override Type getGenericReturnType() {
return resolveType(super.getGenericReturnType()).getType();
}
@Override Type[] getGenericParameterTypes() {
return resolveInPlace(super.getGenericParameterTypes());
}
@Override Type[] getGenericExceptionTypes() {
return resolveInPlace(super.getGenericExceptionTypes());
}
};
}
/**
* The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
* included in the set if this type is an interface.
*/
public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {
private transient ImmutableSet<TypeToken<? super T>> types;
TypeSet() {}
/** Returns the types that are interfaces implemented by this type. */
public TypeSet interfaces() {
return new InterfaceSet(this);
}
/** Returns the types that are classes. */
public TypeSet classes() {
return new ClassSet();
}
@Override protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> filteredTypes = types;
if (filteredTypes == null) {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList)
TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
return (types = FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return filteredTypes;
}
}
/** Returns the raw types of the types in this set, in the same order. */
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes = (ImmutableList)
TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
private static final long serialVersionUID = 0;
}
private final class InterfaceSet extends TypeSet {
private transient final TypeSet allTypes;
private transient ImmutableSet<TypeToken<? super T>> interfaces;
InterfaceSet(TypeSet allTypes) {
this.allTypes = allTypes;
}
@Override protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> result = interfaces;
if (result == null) {
return (interfaces = FluentIterable.from(allTypes)
.filter(TypeFilter.INTERFACE_ONLY)
.toSet());
} else {
return result;
}
}
@Override public TypeSet interfaces() {
return this;
}
@Override public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes = (ImmutableList)
TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes());
return FluentIterable.from(collectedTypes)
.filter(new Predicate<Class<?>>() {
@Override public boolean apply(Class<?> type) {
return type.isInterface();
}
})
.toSet();
}
@Override public TypeSet classes() {
throw new UnsupportedOperationException("interfaces().classes() not supported.");
}
private Object readResolve() {
return getTypes().interfaces();
}
private static final long serialVersionUID = 0;
}
private final class ClassSet extends TypeSet {
private transient ImmutableSet<TypeToken<? super T>> classes;
@Override protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> result = classes;
if (result == null) {
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList)
TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
return (classes = FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return result;
}
}
@Override public TypeSet classes() {
return this;
}
@Override public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes = (ImmutableList)
TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getImmediateRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
@Override public TypeSet interfaces() {
throw new UnsupportedOperationException("classes().interfaces() not supported.");
}
private Object readResolve() {
return getTypes().classes();
}
private static final long serialVersionUID = 0;
}
private enum TypeFilter implements Predicate<TypeToken<?>> {
IGNORE_TYPE_VARIABLE_OR_WILDCARD {
@Override public boolean apply(TypeToken<?> type) {
return !(type.runtimeType instanceof TypeVariable
|| type.runtimeType instanceof WildcardType);
}
},
INTERFACE_ONLY {
@Override public boolean apply(TypeToken<?> type) {
return type.getRawType().isInterface();
}
}
}
/**
* Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
*/
@Override public boolean equals(@Nullable Object o) {
if (o instanceof TypeToken) {
TypeToken<?> that = (TypeToken<?>) o;
return runtimeType.equals(that.runtimeType);
}
return false;
}
@Override public int hashCode() {
return runtimeType.hashCode();
}
@Override public String toString() {
return Types.toString(runtimeType);
}
/** Implemented to support serialization of subclasses. */
protected Object writeReplace() {
// TypeResolver just transforms the type to our own impls that are Serializable
// except TypeVariable.
return of(new TypeResolver().resolveType(runtimeType));
}
/**
* Ensures that this type token doesn't contain type variables, which can cause unchecked type
* errors for callers like {@link TypeToInstanceMap}.
*/
final TypeToken<T> rejectTypeVariables() {
checkArgument(!Types.containsTypeVariable(runtimeType),
"%s contains a type variable and is not safe for the operation");
return this;
}
private static boolean isAssignable(Type from, Type to) {
if (to.equals(from)) {
return true;
}
if (to instanceof WildcardType) {
return isAssignableToWildcardType(from, (WildcardType) to);
}
// if "from" is type variable, it's assignable if any of its "extends"
// bounds is assignable to "to".
if (from instanceof TypeVariable) {
return isAssignableFromAny(((TypeVariable<?>) from).getBounds(), to);
}
// if "from" is wildcard, it'a assignable to "to" if any of its "extends"
// bounds is assignable to "to".
if (from instanceof WildcardType) {
return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to);
}
if (from instanceof GenericArrayType) {
return isAssignableFromGenericArrayType((GenericArrayType) from, to);
}
// Proceed to regular Type assignability check
if (to instanceof Class) {
return isAssignableToClass(from, (Class<?>) to);
} else if (to instanceof ParameterizedType) {
return isAssignableToParameterizedType(from, (ParameterizedType) to);
} else if (to instanceof GenericArrayType) {
return isAssignableToGenericArrayType(from, (GenericArrayType) to);
} else { // to instanceof TypeVariable
return false;
}
}
private static boolean isAssignableFromAny(Type[] fromTypes, Type to) {
for (Type from : fromTypes) {
if (isAssignable(from, to)) {
return true;
}
}
return false;
}
private static boolean isAssignableToClass(Type from, Class<?> to) {
return to.isAssignableFrom(getRawType(from));
}
private static boolean isAssignableToWildcardType(
Type from, WildcardType to) {
// if "to" is <? extends Foo>, "from" can be:
// Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
// <T extends SubFoo>.
// if "to" is <? super Foo>, "from" can be:
// Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to);
}
private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) {
Type toSubtypeBound = subtypeBound(to);
if (toSubtypeBound == null) {
return true;
}
Type fromSubtypeBound = subtypeBound(from);
if (fromSubtypeBound == null) {
return false;
}
return isAssignable(toSubtypeBound, fromSubtypeBound);
}
private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) {
Class<?> matchedClass = getRawType(to);
if (!matchedClass.isAssignableFrom(getRawType(from))) {
return false;
}
Type[] typeParams = matchedClass.getTypeParameters();
Type[] toTypeArgs = to.getActualTypeArguments();
TypeToken<?> fromTypeToken = of(from);
for (int i = 0; i < typeParams.length; i++) {
// If "to" is "List<? extends CharSequence>"
// and "from" is StringArrayList,
// First step is to figure out StringArrayList "is-a" List<E> and <E> is
// String.
// typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to
// String.
// String is then matched against <? extends CharSequence>.
Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType;
if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) {
return false;
}
}
return true;
}
private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) {
if (from instanceof Class) {
Class<?> fromClass = (Class<?>) from;
if (!fromClass.isArray()) {
return false;
}
return isAssignable(fromClass.getComponentType(), to.getGenericComponentType());
} else if (from instanceof GenericArrayType) {
GenericArrayType fromArrayType = (GenericArrayType) from;
return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType());
} else {
return false;
}
}
private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) {
if (to instanceof Class) {
Class<?> toClass = (Class<?>) to;
if (!toClass.isArray()) {
return toClass == Object.class; // any T[] is assignable to Object
}
return isAssignable(from.getGenericComponentType(), toClass.getComponentType());
} else if (to instanceof GenericArrayType) {
GenericArrayType toArrayType = (GenericArrayType) to;
return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType());
} else {
return false;
}
}
private static boolean matchTypeArgument(Type from, Type to) {
if (from.equals(to)) {
return true;
}
if (to instanceof WildcardType) {
return isAssignableToWildcardType(from, (WildcardType) to);
}
return false;
}
private static Type supertypeBound(Type type) {
if (type instanceof WildcardType) {
return supertypeBound((WildcardType) type);
}
return type;
}
private static Type supertypeBound(WildcardType type) {
Type[] upperBounds = type.getUpperBounds();
if (upperBounds.length == 1) {
return supertypeBound(upperBounds[0]);
} else if (upperBounds.length == 0) {
return Object.class;
} else {
throw new AssertionError(
"There should be at most one upper bound for wildcard type: " + type);
}
}
@Nullable private static Type subtypeBound(Type type) {
if (type instanceof WildcardType) {
return subtypeBound((WildcardType) type);
} else {
return type;
}
}
@Nullable private static Type subtypeBound(WildcardType type) {
Type[] lowerBounds = type.getLowerBounds();
if (lowerBounds.length == 1) {
return subtypeBound(lowerBounds[0]);
} else if (lowerBounds.length == 0) {
return null;
} else {
throw new AssertionError(
"Wildcard should have at most one lower bound: " + type);
}
}
@VisibleForTesting static Class<?> getRawType(Type type) {
// For wildcard or type variable, the first bound determines the runtime type.
return getRawTypes(type).iterator().next();
}
@VisibleForTesting static ImmutableSet<Class<?>> getRawTypes(Type type) {
if (type instanceof Class) {
return ImmutableSet.<Class<?>>of((Class<?>) type);
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// JDK implementation declares getRawType() to return Class<?>
return ImmutableSet.<Class<?>>of((Class<?>) parameterizedType.getRawType());
} else if (type instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) type;
return ImmutableSet.<Class<?>>of(Types.getArrayClass(
getRawType(genericArrayType.getGenericComponentType())));
} else if (type instanceof TypeVariable) {
return getRawTypes(((TypeVariable<?>) type).getBounds());
} else if (type instanceof WildcardType) {
return getRawTypes(((WildcardType) type).getUpperBounds());
} else {
throw new AssertionError(type + " unsupported");
}
}
private static ImmutableSet<Class<?>> getRawTypes(Type[] types) {
ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder();
for (Type type : types) {
builder.addAll(getRawTypes(type));
}
return builder.build();
}
/**
* Returns the type token representing the generic type declaration of {@code cls}. For example:
* {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}.
*
* <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
* returned.
*/
@VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) {
if (cls.isArray()) {
Type arrayOfGenericType = Types.newArrayType(
// If we are passed with int[].class, don't turn it to GenericArrayType
toGenericType(cls.getComponentType()).runtimeType);
@SuppressWarnings("unchecked") // array is covariant
TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType);
return result;
}
TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters();
if (typeParams.length > 0) {
@SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class
TypeToken<? extends T> type = (TypeToken<? extends T>)
of(Types.newParameterizedType(cls, typeParams));
return type;
} else {
return of(cls);
}
}
private TypeToken<? super T> getSupertypeFromUpperBounds(
Class<? super T> supertype, Type[] upperBounds) {
for (Type upperBound : upperBounds) {
@SuppressWarnings("unchecked") // T's upperbound is <? super T>.
TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound);
if (of(supertype).isAssignableFrom(bound)) {
@SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check.
TypeToken<? super T> result = bound.getSupertype((Class) supertype);
return result;
}
}
throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
}
private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) {
for (Type lowerBound : lowerBounds) {
@SuppressWarnings("unchecked") // T's lower bound is <? extends T>
TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound);
// Java supports only one lowerbound anyway.
return bound.getSubtype(subclass);
}
throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
}
private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) {
// with component type, we have lost generic type information
// Use raw type so that compiler allows us to call getSupertype()
@SuppressWarnings("rawtypes")
TypeToken componentType = checkNotNull(getComponentType(),
"%s isn't a super type of %s", supertype, this);
// array is covariant. component type is super type, so is the array type.
@SuppressWarnings("unchecked") // going from raw type back to generics
TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType());
@SuppressWarnings("unchecked") // component type is super type, so is array type.
TypeToken<? super T> result = (TypeToken<? super T>)
// If we are passed with int[].class, don't turn it to GenericArrayType
of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
return result;
}
private TypeToken<? extends T> getArraySubtype(Class<?> subclass) {
// array is covariant. component type is subtype, so is the array type.
TypeToken<?> componentSubtype = getComponentType()
.getSubtype(subclass.getComponentType());
@SuppressWarnings("unchecked") // component type is subtype, so is array type.
TypeToken<? extends T> result = (TypeToken<? extends T>)
// If we are passed with int[].class, don't turn it to GenericArrayType
of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
return result;
}
private Type resolveTypeArgsForSubclass(Class<?> subclass) {
if (runtimeType instanceof Class) {
// no resolution needed
return subclass;
}
// class Base<A, B> {}
// class Sub<X, Y> extends Base<X, Y> {}
// Base<String, Integer>.subtype(Sub.class):
// Sub<X, Y>.getSupertype(Base.class) => Base<X, Y>
// => X=String, Y=Integer
// => Sub<X, Y>=Sub<String, Integer>
TypeToken<?> genericSubtype = toGenericType(subclass);
@SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T>
Type supertypeWithArgsFromSubtype = genericSubtype
.getSupertype((Class) getRawType())
.runtimeType;
return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType)
.resolveType(genericSubtype.runtimeType);
}
/**
* Creates an array class if {@code componentType} is a class, or else, a
* {@link GenericArrayType}. This is what Java7 does for generic array type
* parameters.
*/
private static Type newArrayClassOrGenericArrayType(Type componentType) {
return Types.JavaVersion.JAVA7.newArrayType(componentType);
}
private static final class SimpleTypeToken<T> extends TypeToken<T> {
SimpleTypeToken(Type type) {
super(type);
}
private static final long serialVersionUID = 0;
}
/**
* Collects parent types from a sub type.
*
* @param <K> The type "kind". Either a TypeToken, or Class.
*/
private abstract static class TypeCollector<K> {
static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE =
new TypeCollector<TypeToken<?>>() {
@Override Class<?> getRawType(TypeToken<?> type) {
return type.getRawType();
}
@Override Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) {
return type.getGenericInterfaces();
}
@Nullable
@Override TypeToken<?> getSuperclass(TypeToken<?> type) {
return type.getGenericSuperclass();
}
};
static final TypeCollector<Class<?>> FOR_RAW_TYPE =
new TypeCollector<Class<?>>() {
@Override Class<?> getRawType(Class<?> type) {
return type;
}
@Override Iterable<? extends Class<?>> getInterfaces(Class<?> type) {
return Arrays.asList(type.getInterfaces());
}
@Nullable
@Override Class<?> getSuperclass(Class<?> type) {
return type.getSuperclass();
}
};
/** For just classes, we don't have to traverse interfaces. */
final TypeCollector<K> classesOnly() {
return new ForwardingTypeCollector<K>(this) {
@Override Iterable<? extends K> getInterfaces(K type) {
return ImmutableSet.of();
}
@Override ImmutableList<K> collectTypes(Iterable<? extends K> types) {
ImmutableList.Builder<K> builder = ImmutableList.builder();
for (K type : types) {
if (!getRawType(type).isInterface()) {
builder.add(type);
}
}
return super.collectTypes(builder.build());
}
};
}
final ImmutableList<K> collectTypes(K type) {
return collectTypes(ImmutableList.of(type));
}
ImmutableList<K> collectTypes(Iterable<? extends K> types) {
// type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
Map<K, Integer> map = Maps.newHashMap();
for (K type : types) {
collectTypes(type, map);
}
return sortKeysByValue(map, Ordering.natural().reverse());
}
/** Collects all types to map, and returns the total depth from T up to Object. */
private int collectTypes(K type, Map<? super K, Integer> map) {
Integer existing = map.get(this);
if (existing != null) {
// short circuit: if set contains type it already contains its supertypes
return existing;
}
int aboveMe = getRawType(type).isInterface()
? 1 // interfaces should be listed before Object
: 0;
for (K interfaceType : getInterfaces(type)) {
aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map));
}
K superclass = getSuperclass(type);
if (superclass != null) {
aboveMe = Math.max(aboveMe, collectTypes(superclass, map));
}
// TODO(benyu): should we include Object for interface?
// Also, CharSequence[] and Object[] for String[]?
map.put(type, aboveMe + 1);
return aboveMe + 1;
}
private static <K, V> ImmutableList<K> sortKeysByValue(
final Map<K, V> map, final Comparator<? super V> valueComparator) {
Ordering<K> keyOrdering = new Ordering<K>() {
@Override public int compare(K left, K right) {
return valueComparator.compare(map.get(left), map.get(right));
}
};
return keyOrdering.immutableSortedCopy(map.keySet());
}
abstract Class<?> getRawType(K type);
abstract Iterable<? extends K> getInterfaces(K type);
@Nullable abstract K getSuperclass(K type);
private static class ForwardingTypeCollector<K> extends TypeCollector<K> {
private final TypeCollector<K> delegate;
ForwardingTypeCollector(TypeCollector<K> delegate) {
this.delegate = delegate;
}
@Override Class<?> getRawType(K type) {
return delegate.getRawType(type);
}
@Override Iterable<? extends K> getInterfaces(K type) {
return delegate.getInterfaces(type);
}
@Override K getSuperclass(K type) {
return delegate.getSuperclass(type);
}
}
}
}
| Java |
/*
* Copyright (C) 2005 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.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* Static utilities relating to Java reflection.
*
* @since 12.0
*/
@Beta
public final class Reflection {
/**
* Returns the package name of {@code clazz} according to the Java Language Specification (section
* 6.7). Unlike {@link Class#getPackage}, this method only parses the class name, without
* attempting to define the {@link Package} and hence load files.
*/
public static String getPackageName(Class<?> clazz) {
return getPackageName(clazz.getName());
}
/**
* Returns the package name of {@code classFullName} according to the Java Language Specification
* (section 6.7). Unlike {@link Class#getPackage}, this method only parses the class name, without
* attempting to define the {@link Package} and hence load files.
*/
public static String getPackageName(String classFullName) {
int lastDot = classFullName.lastIndexOf('.');
return (lastDot < 0) ? "" : classFullName.substring(0, lastDot);
}
/**
* Ensures that the given classes are initialized, as described in
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4.2">
* JLS Section 12.4.2</a>.
*
* <p>WARNING: Normally it's a smell if a class needs to be explicitly initialized, because static
* state hurts system maintainability and testability. In cases when you have no choice while
* inter-operating with a legacy framework, this method helps to keep the code less ugly.
*
* @throws ExceptionInInitializerError if an exception is thrown during
* initialization of a class
*/
public static void initialize(Class<?>... classes) {
for (Class<?> clazz : classes) {
try {
Class.forName(clazz.getName(), true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
throw new AssertionError(e);
}
}
}
/**
* Returns a proxy instance that implements {@code interfaceType} by
* dispatching method invocations to {@code handler}. The class loader of
* {@code interfaceType} will be used to define the proxy class. To implement
* multiple interfaces or specify a class loader, use
* {@link Proxy#newProxyInstance}.
*
* @throws IllegalArgumentException if {@code interfaceType} does not specify
* the type of a Java interface
*/
public static <T> T newProxy(
Class<T> interfaceType, InvocationHandler handler) {
checkNotNull(handler);
checkArgument(interfaceType.isInterface(), "%s is not an interface", interfaceType);
Object object = Proxy.newProxyInstance(
interfaceType.getClassLoader(),
new Class<?>[] { interfaceType },
handler);
return interfaceType.cast(object);
}
private Reflection() {}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.