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.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) 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.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* A comparator with added methods to support common functions. 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> {
// Static factories
/**
* 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;
}
/**
* Returns an ordering for a pre-existing {@code comparator}. Note
* that if the comparator is not pre-existing, and you don't require
* serialization, you can subclass {@code Ordering} and implement its
* {@link #compare(Object, Object) compare} method instead.
*
* @param comparator the comparator that defines the order
*/
@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));
}
/**
* 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;
}
/**
* 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;
}
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);
}
}
/**
* 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 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);
}
/**
* Constructs a new instance of this class (only invokable by the subclass
* constructor, typically implicit).
*/
protected Ordering() {}
// Non-static factories
/**
* 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 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 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 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);
}
/**
* 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);
}
// Regular instance methods
// Override to add @Nullable
@Override public abstract int compare(@Nullable T left, @Nullable T right);
/**
* 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.
*
* @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);
}
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.
*
* @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;
}
/**
* {@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);
}
/**
* 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) {
List<E> list = Lists.newArrayList(iterable);
Collections.sort(list, this);
return list;
}
/**
* 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) {
return ImmutableList.copyOf(sortedCopy(iterable));
}
/**
* 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;
}
/**
* 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 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 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 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 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 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;
}
// Never make these public
static final int LEFT_IS_GREATER = 1;
static final int RIGHT_IS_GREATER = -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.checkNotNull;
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.Map;
/**
* A {@code BiMap} backed by two {@code EnumMap} instances. Null keys and values
* are not permitted. An {@code EnumBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>>
extends AbstractBiMap<K, V> {
private transient Class<K> keyType;
private transient Class<V> valueType;
/**
* Returns a new, empty {@code EnumBiMap} using the specified key and value
* types.
*
* @param keyType the key type
* @param valueType the value type
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V>
create(Class<K> keyType, Class<V> valueType) {
return new EnumBiMap<K, V>(keyType, valueType);
}
/**
* Returns a new bimap with the same mappings as the specified map. If the
* specified map is an {@code EnumBiMap}, the new bimap has the same types as
* the provided map. Otherwise, the specified map must contain at least one
* mapping, in order to determine the key and value types.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V>
create(Map<K, V> map) {
EnumBiMap<K, V> bimap = create(inferKeyType(map), inferValueType(map));
bimap.putAll(map);
return bimap;
}
private EnumBiMap(Class<K> keyType, Class<V> valueType) {
super(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
WellBehavedMap.wrap(new EnumMap<V, K>(valueType)));
this.keyType = keyType;
this.valueType = valueType;
}
static <K extends Enum<K>> Class<K> inferKeyType(Map<K, ?> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<K, ?>) map).keyType();
}
if (map instanceof EnumHashBiMap) {
return ((EnumHashBiMap<K, ?>) map).keyType();
}
checkArgument(!map.isEmpty());
return map.keySet().iterator().next().getDeclaringClass();
}
private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<?, V>) map).valueType;
}
checkArgument(!map.isEmpty());
return map.values().iterator().next().getDeclaringClass();
}
/** Returns the associated key type. */
public Class<K> keyType() {
return keyType;
}
/** Returns the associated value type. */
public Class<V> valueType() {
return valueType;
}
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override
V checkValue(V value) {
return checkNotNull(value);
}
/**
* @serialData the key class, value class, number of entries, first key, first
* value, second key, second value, and so on.
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyType);
stream.writeObject(valueType);
Serialization.writeMap(this, stream);
}
@SuppressWarnings("unchecked") // reading fields populated by writeObject
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyType = (Class<K>) stream.readObject();
valueType = (Class<V>) stream.readObject();
setDelegates(
WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
WellBehavedMap.wrap(new EnumMap<V, K>(valueType)));
Serialization.populateMap(this, stream);
}
@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 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 javax.annotation.Nullable;
/**
* A factory for copying nodes in binary search trees with different children.
*
* <p>Typically, nodes will carry more information than the fields in the {@link BstNode} class,
* often some kind of value or some aggregate data for the subtree. This factory is responsible for
* copying this additional data between nodes.
*
* @author Louis Wasserman
* @param <N> The type of the tree nodes constructed with this {@code BstNodeFactory}.
*/
@GwtCompatible
abstract class BstNodeFactory<N extends BstNode<?, N>> {
/**
* Returns a new {@code N} with the key and value data from {@code source}, with left child
* {@code left}, and right child {@code right}. If {@code left} or {@code right} is null, the
* returned node will not have a child on the corresponding side.
*/
public abstract N createNode(N source, @Nullable N left, @Nullable N right);
/**
* Returns a new {@code N} with the key and value data from {@code source} that is a leaf.
*/
public final N createLeaf(N source) {
return createNode(source, null, 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 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) 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.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A collection that associates an ordered pair of keys, called a row key and a
* column key, with a single value. A table may be sparse, with only a small
* fraction of row key / column key pairs possessing a corresponding value.
*
* <p>The mappings corresponding to a given row key may be viewed as a {@link
* Map} whose keys are the columns. The reverse is also available, associating a
* column with a row key / value map. Note that, in some implementations, data
* access by column key may have fewer supported operations or worse performance
* than data access by row key.
*
* <p>The methods returning collections or maps always return views of the
* underlying table. Updating the table can change the contents of those
* collections, and updating the collections will change the table.
*
* <p>All methods that modify the table are optional, and the views returned by
* the table may or may not be modifiable. When modification isn't supported,
* those methods will throw an {@link UnsupportedOperationException}.
*
* <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
* @param <R> the type of the table row keys
* @param <C> the type of the table column keys
* @param <V> the type of the mapped values
* @since 7.0
*/
@GwtCompatible
@Beta
public interface Table<R, C, V> {
// TODO(jlevy): Consider adding methods similar to ConcurrentMap methods.
// Accessors
/**
* Returns {@code true} if the table contains a mapping with the specified
* row and column keys.
*
* @param rowKey key of row to search for
* @param columnKey key of column to search for
*/
boolean contains(@Nullable Object rowKey, @Nullable Object columnKey);
/**
* Returns {@code true} if the table contains a mapping with the specified
* row key.
*
* @param rowKey key of row to search for
*/
boolean containsRow(@Nullable Object rowKey);
/**
* Returns {@code true} if the table contains a mapping with the specified
* column.
*
* @param columnKey key of column to search for
*/
boolean containsColumn(@Nullable Object columnKey);
/**
* Returns {@code true} if the table contains a mapping with the specified
* value.
*
* @param value value to search for
*/
boolean containsValue(@Nullable Object value);
/**
* Returns the value corresponding to the given row and column keys, or
* {@code null} if no such mapping exists.
*
* @param rowKey key of row to search for
* @param columnKey key of column to search for
*/
V get(@Nullable Object rowKey, @Nullable Object columnKey);
/** Returns {@code true} if the table contains no mappings. */
boolean isEmpty();
/**
* Returns the number of row key / column key / value mappings in the table.
*/
int size();
/**
* Compares the specified object with this table for equality. Two tables are
* equal when their cell views, as returned by {@link #cellSet}, are equal.
*/
@Override
boolean equals(@Nullable Object obj);
/**
* Returns the hash code for this table. The hash code of a table is defined
* as the hash code of its cell view, as returned by {@link #cellSet}.
*/
@Override
int hashCode();
// Mutators
/** Removes all mappings from the table. */
void clear();
/**
* Associates the specified value with the specified keys. If the table
* already contained a mapping for those keys, the old value is replaced with
* the specified value.
*
* @param rowKey row key that the value should be associated with
* @param columnKey column key that the value should be associated with
* @param value value to be associated with the specified keys
* @return the value previously associated with the keys, or {@code null} if
* no mapping existed for the keys
*/
V put(R rowKey, C columnKey, V value);
/**
* Copies all mappings from the specified table to this table. The effect is
* equivalent to calling {@link #put} with each row key / column key / value
* mapping in {@code table}.
*
* @param table the table to add to this table
*/
void putAll(Table<? extends R, ? extends C, ? extends V> table);
/**
* Removes the mapping, if any, associated with the given keys.
*
* @param rowKey row key of mapping to be removed
* @param columnKey column key of mapping to be removed
* @return the value previously associated with the keys, or {@code null} if
* no such value existed
*/
V remove(@Nullable Object rowKey, @Nullable Object columnKey);
// Views
/**
* Returns a view of all mappings that have the given row key. For each row
* key / column key / value mapping in the table with that row key, the
* returned map associates the column key with the value. If no mappings in
* the table have the provided row key, an empty map is returned.
*
* <p>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
*/
Map<C, V> row(R rowKey);
/**
* Returns a view of all mappings that have the given column key. For each row
* key / column key / value mapping in the table with that column key, the
* returned map associates the row key with the value. If no mappings in the
* table have the provided column key, an empty map is returned.
*
* <p>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
*/
Map<R, V> column(C columnKey);
/**
* Returns a set of all row key / column key / value triplets. Changes to the
* returned set will update the underlying table, and vice versa. The cell set
* does not support the {@code add} or {@code addAll} methods.
*
* @return set of table cells consisting of row key / column key / value
* triplets
*/
Set<Cell<R, C, V>> cellSet();
/**
* Returns a set of row keys that have one or more values in the table.
* Changes to the set will update the underlying table, and vice versa.
*
* @return set of row keys
*/
Set<R> rowKeySet();
/**
* Returns a set of column keys that have one or more values in the table.
* Changes to the set will update the underlying table, and vice versa.
*
* @return set of column keys
*/
Set<C> columnKeySet();
/**
* Returns a collection of all values, which may contain duplicates. Changes
* to the returned collection will update the underlying table, and vice
* versa.
*
* @return collection of values
*/
Collection<V> values();
/**
* Returns a view that associates each row key with the corresponding map from
* column keys to values. Changes to the returned map will update this table.
* The returned map does not support {@code put()} or {@code putAll()}, or
* {@code setValue()} on its entries.
*
* <p>In contrast, the maps returned by {@code rowMap().get()} have the same
* behavior as those returned by {@link #row}. Those maps may support {@code
* setValue()}, {@code put()}, and {@code putAll()}.
*
* @return a map view from each row key to a secondary map from column keys to
* values
*/
Map<R, Map<C, V>> rowMap();
/**
* Returns a view that associates each column key with the corresponding map
* from row keys to values. Changes to the returned map will update this
* table. The returned map does not support {@code put()} or {@code putAll()},
* or {@code setValue()} on its entries.
*
* <p>In contrast, the maps returned by {@code columnMap().get()} have the
* same behavior as those returned by {@link #column}. Those maps may support
* {@code setValue()}, {@code put()}, and {@code putAll()}.
*
* @return a map view from each column key to a secondary map from row keys to
* values
*/
Map<C, Map<R, V>> columnMap();
/**
* Row key / column key / value triplet corresponding to a mapping in a table.
*
* @since 7.0
*/
@Beta
interface Cell<R, C, V> {
/**
* Returns the row key of this cell.
*/
R getRowKey();
/**
* Returns the column key of this cell.
*/
C getColumnKey();
/**
* Returns the value of this cell.
*/
V getValue();
/**
* Compares the specified object with this cell for equality. Two cells are
* equal when they have equal row keys, column keys, and values.
*/
@Override
boolean equals(@Nullable Object obj);
/**
* Returns the hash code of this cell.
*
* <p>The hash code of a table cell is equal to {@link
* Objects#hashCode}{@code (e.getRowKey(), e.getColumnKey(), e.getValue())}.
*/
@Override
int 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;
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 boolean contains(@Nullable Object target) {
return indexOf(target) != -1;
}
// The fake cast to E is safe because the creation methods only allow E's
@SuppressWarnings("unchecked")
@Override public UnmodifiableIterator<E> iterator() {
return (UnmodifiableIterator<E>) Iterators.forArray(array, offset, size);
}
@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 public int indexOf(@Nullable Object target) {
if (target != null) {
for (int i = offset; i < offset + size; i++) {
if (array[i].equals(target)) {
return i - offset;
}
}
}
return -1;
}
@Override public int lastIndexOf(@Nullable Object target) {
if (target != null) {
for (int i = offset + size - 1; i >= offset; i--) {
if (array[i].equals(target)) {
return i - offset;
}
}
}
return -1;
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
Preconditions.checkPositionIndexes(fromIndex, toIndex, size);
return (fromIndex == toIndex)
? ImmutableList.<E>of()
: new RegularImmutableList<E>(
array, offset + fromIndex, toIndex - fromIndex);
}
@Override public UnmodifiableListIterator<E> listIterator(final int start) {
return new AbstractIndexedListIterator<E>(size, start) {
// The fake cast to E is safe because the creation methods only allow E's
@SuppressWarnings("unchecked")
@Override protected E get(int index) {
return (E) array[index + offset];
}
};
}
@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 int hashCode() {
// not caching hash code since it could change if the elements are mutable
// in a way that modifies their hash codes
int hashCode = 1;
for (int i = offset; i < offset + size; i++) {
hashCode = 31 * hashCode + array[i].hashCode();
}
return hashCode;
}
@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) 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.GwtCompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* An immutable {@code SortedSet} that stores its elements in a sorted array.
* Some instances are ordered by an explicit comparator, while others follow the
* natural sort ordering of their elements. Either way, null elements are not
* supported.
*
* <p>Unlike {@link Collections#unmodifiableSortedSet}, which is a <i>view</i>
* of a separate collection that can still change, an instance of {@code
* ImmutableSortedSet} 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>The sets returned by the {@link #headSet}, {@link #tailSet}, and
* {@link #subSet} methods share the same array as the original set, preventing
* that array from being garbage collected. If this is a concern, the data may
* be copied into a correctly-sized array by calling {@link #copyOfSorted}.
*
* <p><b>Note on element equivalence:</b> The {@link #contains(Object)},
* {@link #containsAll(Collection)}, and {@link #equals(Object)}
* implementations must check whether a provided object is equivalent to an
* element in the collection. Unlike most collections, an
* {@code ImmutableSortedSet} doesn't use {@link Object#equals} to determine if
* two elements are equivalent. Instead, with an explicit comparator, the
* following relation determines whether elements {@code x} and {@code y} are
* equivalent: <pre> {@code
*
* {(x, y) | comparator.compare(x, y) == 0}}</pre>
*
* With natural ordering of elements, the following relation determines whether
* two elements are equivalent: <pre> {@code
*
* {(x, y) | x.compareTo(y) == 0}}</pre>
*
* <b>Warning:</b> Like most sets, an {@code ImmutableSortedSet} 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><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 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 ImmutableSet
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
// TODO(benyu): benchmark and optimize all creation paths, which are a mess now
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxverideShim<E>
implements SortedSet<E>, SortedIterable<E> {
private static final Comparator<Comparable> NATURAL_ORDER =
Ordering.natural();
private static final ImmutableSortedSet<Comparable> NATURAL_EMPTY_SET =
new EmptyImmutableSortedSet<Comparable>(NATURAL_ORDER);
@SuppressWarnings("unchecked")
private static <E> ImmutableSortedSet<E> emptySet() {
return (ImmutableSortedSet<E>) NATURAL_EMPTY_SET;
}
static <E> ImmutableSortedSet<E> emptySet(
Comparator<? super E> comparator) {
if (NATURAL_ORDER.equals(comparator)) {
return emptySet();
} else {
return new EmptyImmutableSortedSet<E>(comparator);
}
}
/**
* Returns the empty immutable sorted set.
*/
public static <E> ImmutableSortedSet<E> of() {
return emptySet();
}
/**
* Returns an immutable sorted set containing a single element.
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E element) {
return new RegularImmutableSortedSet<E>(
ImmutableList.of(element), Ordering.natural());
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4, e5));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
int size = remaining.length + 6;
List<E> all = new ArrayList<E>(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, remaining);
return copyOf(Ordering.natural(), all);
}
// TODO(kevinb): Consider factory methods that reject duplicates
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(
E[] elements) {
return copyOf(Ordering.natural(), Arrays.asList(elements));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@code compareTo()}, only the first one specified is included. To create a
* copy of a {@code SortedSet} that preserves the comparator, call {@link
* #copyOfSorted} instead. This method iterates over {@code elements} at most
* once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code
* ImmutableSortedSet.copyOf(s)} returns an {@code ImmutableSortedSet<String>}
* containing each of the strings in {@code s}, while {@code
* ImmutableSortedSet.of(s)} returns an {@code
* ImmutableSortedSet<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.
*
* <p>This method is not type-safe, as it may be called on elements that are
* not mutually comparable.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Iterable<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@code compareTo()}, only the first one specified is included. To create a
* copy of a {@code SortedSet} that preserves the comparator, call
* {@link #copyOfSorted} instead. This method iterates over {@code elements}
* at most once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then
* {@code ImmutableSortedSet.copyOf(s)} returns an
* {@code ImmutableSortedSet<String>} containing each of the strings in
* {@code s}, while {@code ImmutableSortedSet.of(s)} returns an
* {@code ImmutableSortedSet<Set<String>>} containing one element (the given
* set itself).
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code elements}
* is an {@code ImmutableSortedSet}, it may be returned instead of a copy.
*
* <p>This method is not type-safe, as it may be called on elements that are
* not mutually comparable.
*
* <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 ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSortedSet<E> copyOf(
Collection<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@code compareTo()}, only the first one specified is included.
*
* <p>This method is not type-safe, as it may be called on elements that are
* not mutually comparable.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Iterator<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOfInternal(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* the given {@code Comparator}. When multiple elements are equivalent
* according to {@code compareTo()}, only the first one specified is
* included.
*
* @throws NullPointerException if {@code comparator} or any of
* {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterator<? extends E> elements) {
checkNotNull(comparator);
return copyOfInternal(comparator, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* the given {@code Comparator}. When multiple elements are equivalent
* according to {@code compare()}, only the first one specified is
* included. This method iterates over {@code elements} at most once.
*
* <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 {@code comparator} or any of {@code
* elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
checkNotNull(comparator);
return copyOfInternal(comparator, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* the given {@code Comparator}. When multiple elements are equivalent
* according to {@code compareTo()}, only the first one specified is
* included.
*
* <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.
*
* <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 {@code comparator} or any of
* {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Collection<? extends E> elements) {
checkNotNull(comparator);
return copyOfInternal(comparator, elements);
}
/**
* Returns an immutable sorted set containing the elements of a sorted set,
* sorted by the same {@code Comparator}. That behavior differs from {@link
* #copyOf(Iterable)}, which always uses the natural ordering of the
* elements.
*
* <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.
*
* <p>This method is safe to use even when {@code sortedSet} is a synchronized
* or concurrent collection that is currently being modified by another
* thread.
*
* @throws NullPointerException if {@code sortedSet} or any of its elements
* is null
*/
@SuppressWarnings("unchecked")
public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
Comparator<? super E> comparator = sortedSet.comparator();
if (comparator == null) {
comparator = (Comparator<? super E>) NATURAL_ORDER;
}
return copyOfInternal(comparator, sortedSet);
}
private static <E> ImmutableSortedSet<E> copyOfInternal(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
boolean hasSameComparator =
SortedIterables.hasSameComparator(comparator, elements);
if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
@SuppressWarnings("unchecked")
ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
if (!original.isPartialView()) {
return original;
}
}
ImmutableList<E> list = ImmutableList.copyOf(
SortedIterables.sortedUnique(comparator, elements));
return list.isEmpty()
? ImmutableSortedSet.<E>emptySet(comparator)
: new RegularImmutableSortedSet<E>(list, comparator);
}
private static <E> ImmutableSortedSet<E> copyOfInternal(
Comparator<? super E> comparator, Iterator<? extends E> elements) {
ImmutableList<E> list =
ImmutableList.copyOf(SortedIterables.sortedUnique(comparator, elements));
return list.isEmpty()
? ImmutableSortedSet.<E>emptySet(comparator)
: new RegularImmutableSortedSet<E>(list, comparator);
}
/**
* Returns a builder that creates immutable sorted sets with an explicit
* comparator. If the comparator has a more general type than the set being
* generated, such as creating a {@code SortedSet<Integer>} with a
* {@code Comparator<Number>}, use the {@link Builder} constructor instead.
*
* @throws NullPointerException if {@code comparator} is null
*/
public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
return new Builder<E>(comparator);
}
/**
* Returns a builder that creates immutable sorted sets whose elements are
* ordered by the reverse of their natural ordering.
*
* <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather
* than {@code Comparable<? super E>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <E extends Comparable<E>> Builder<E> reverseOrder() {
return new Builder<E>(Ordering.natural().reverse());
}
/**
* Returns a builder that creates immutable sorted sets whose elements are
* ordered by their natural ordering. The sorted sets use {@link
* Ordering#natural()} as the comparator. This method provides more
* type-safety than {@link #builder}, as it can be called only for classes
* that implement {@link Comparable}.
*
* <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather
* than {@code Comparable<? super E>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <E extends Comparable<E>> Builder<E> naturalOrder() {
return new Builder<E>(Ordering.natural());
}
/**
* A builder for creating immutable sorted set instances, especially {@code
* public static final} sets ("constant sets"), with a given comparator.
* Example: <pre> {@code
*
* public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
* new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
* .addAll(SINGLE_DIGIT_PRIMES)
* .add(42)
* .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 final class Builder<E> extends ImmutableSet.Builder<E> {
private final Comparator<? super E> comparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSortedSet#orderedBy}.
*/
public Builder(Comparator<? super E> comparator) {
this.comparator = checkNotNull(comparator);
}
/**
* Adds {@code element} to the {@code ImmutableSortedSet}. If the
* {@code ImmutableSortedSet} 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) {
super.add(element);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet},
* 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} contains a null element
*/
@Override public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSortedSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSortedSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Returns a newly-created {@code ImmutableSortedSet} based on the contents
* of the {@code Builder} and its comparator.
*/
@Override public ImmutableSortedSet<E> build() {
return copyOfInternal(comparator, contents.iterator());
}
}
int unsafeCompare(Object a, Object b) {
return unsafeCompare(comparator, a, b);
}
static int unsafeCompare(
Comparator<?> comparator, Object a, Object b) {
// Pretend the comparator can compare anything. If it turns out it can't
// compare a and b, we should get a CCE on the subsequent line. Only methods
// that are spec'd to throw CCE should call this.
@SuppressWarnings("unchecked")
Comparator<Object> unsafeComparator = (Comparator<Object>) comparator;
return unsafeComparator.compare(a, b);
}
final transient Comparator<? super E> comparator;
ImmutableSortedSet(Comparator<? super E> comparator) {
this.comparator = comparator;
}
/**
* Returns the comparator that orders the elements, which is
* {@link Ordering#natural()} when the natural ordering of the
* elements is used. Note that its behavior is not consistent with
* {@link SortedSet#comparator()}, which returns {@code null} to indicate
* natural ordering.
*/
@Override
public Comparator<? super E> comparator() {
return comparator;
}
@Override // needed to unify the iterator() methods in Collection and SortedIterable
public abstract UnmodifiableIterator<E> iterator();
/**
* {@inheritDoc}
*
* <p>This method returns a serializable {@code ImmutableSortedSet}.
*
* <p>The {@link SortedSet#headSet} documentation states that a subset of a
* subset throws an {@link IllegalArgumentException} if passed a
* {@code toElement} greater than an earlier {@code toElement}. However, this
* method doesn't throw an exception in that situation, but instead keeps the
* original {@code toElement}.
*/
@Override
public ImmutableSortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
return headSetImpl(checkNotNull(toElement), inclusive);
}
/**
* {@inheritDoc}
*
* <p>This method returns a serializable {@code ImmutableSortedSet}.
*
* <p>The {@link SortedSet#subSet} documentation states that a subset of a
* subset throws an {@link IllegalArgumentException} if passed a
* {@code fromElement} smaller than an earlier {@code fromElement}. However,
* this method doesn't throw an exception in that situation, but instead keeps
* the original {@code fromElement}. Similarly, this method keeps the
* original {@code toElement}, instead of throwing an exception, if passed a
* {@code toElement} greater than an earlier {@code toElement}.
*/
@Override
public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
ImmutableSortedSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
checkNotNull(fromElement);
checkNotNull(toElement);
checkArgument(comparator.compare(fromElement, toElement) <= 0);
return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
}
/**
* {@inheritDoc}
*
* <p>This method returns a serializable {@code ImmutableSortedSet}.
*
* <p>The {@link SortedSet#tailSet} documentation states that a subset of a
* subset throws an {@link IllegalArgumentException} if passed a
* {@code fromElement} smaller than an earlier {@code fromElement}. However,
* this method doesn't throw an exception in that situation, but instead keeps
* the original {@code fromElement}.
*/
@Override
public ImmutableSortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
return tailSetImpl(checkNotNull(fromElement), inclusive);
}
/*
* These methods perform most headSet, subSet, and tailSet logic, besides
* parameter validation.
*/
abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive);
abstract ImmutableSortedSet<E> subSetImpl(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive);
/**
* Returns the position of an element within the set, or -1 if not present.
*/
abstract int indexOf(@Nullable Object target);
/*
* This class is used to serialize all ImmutableSortedSet instances,
* regardless of implementation type. It captures their "logical contents"
* only. This is necessary to ensure that the existence of a particular
* implementation type is an implementation detail.
*/
private static class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final Object[] elements;
public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
this.comparator = comparator;
this.elements = elements;
}
@SuppressWarnings("unchecked")
Object readResolve() {
return new Builder<E>(comparator).add((E[]) elements).build();
}
private static final long serialVersionUID = 0;
}
private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override Object writeReplace() {
return new SerializedForm<E>(comparator, toArray());
}
}
| 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;
/**
* "Overrides" the {@link ImmutableMap} static methods that lack
* {@link ImmutableSortedMap} equivalents with deprecated, exception-throwing
* versions. See {@link ImmutableSortedSetFauxverideShim} for details.
*
* @author Chris Povirk
*/
@GwtCompatible
abstract class ImmutableSortedMapFauxverideShim<K, V>
extends ImmutableMap<K, V> {
/**
* Not supported. Use {@link ImmutableSortedMap#naturalOrder}, which offers
* better type-safety, instead. This method exists only to hide
* {@link ImmutableMap#builder} from consumers of {@code ImmutableSortedMap}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedMap#naturalOrder}, which offers
* better type-safety.
*/
@Deprecated public static <K, V> ImmutableSortedMap.Builder<K, V> builder() {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain a
* non-{@code Comparable} key.</b> Proper calls will resolve to the version in
* {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass a key of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls will resolve to the version
* in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls to will resolve to the
* version in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object,
* Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls will resolve to the version
* in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object,
* Comparable, Object, Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls will resolve to the version
* in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object,
* Comparable, Object, Comparable, Object, Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
throw new UnsupportedOperationException();
}
// No copyOf() fauxveride; see ImmutableSortedSetFauxverideShim.
}
| 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.BstSide.LEFT;
import static com.google.common.collect.BstSide.RIGHT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
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 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;
}
/**
* Returns an iterator over the elements contained in this collection.
*/
@Override
public Iterator<E> iterator() {
// Needed to avoid Javadoc bug.
return super.iterator();
}
private TreeMultiset(Comparator<? super E> comparator) {
super(comparator);
this.range = GeneralRange.all(comparator);
this.rootReference = new Reference<Node<E>>();
}
private TreeMultiset(GeneralRange<E> range, Reference<Node<E>> root) {
super(range.comparator());
this.range = range;
this.rootReference = root;
}
@SuppressWarnings("unchecked")
E checkElement(Object o) {
return (E) o;
}
private transient final GeneralRange<E> range;
private transient final Reference<Node<E>> rootReference;
static final class Reference<T> {
T value;
public Reference() {}
public T get() {
return value;
}
public boolean compareAndSet(T expected, T newValue) {
if (value == expected) {
value = newValue;
return true;
}
return false;
}
}
@Override
int distinctElements() {
Node<E> root = rootReference.get();
return Ints.checkedCast(BstRangeOps.totalInRange(distinctAggregate(), range, root));
}
@Override
public int size() {
Node<E> root = rootReference.get();
return Ints.saturatedCast(BstRangeOps.totalInRange(sizeAggregate(), range, root));
}
@Override
public int count(@Nullable Object element) {
try {
E e = checkElement(element);
if (range.contains(e)) {
Node<E> node = BstOperations.seek(comparator(), rootReference.get(), e);
return countOrZero(node);
}
return 0;
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
private int mutate(@Nullable E e, MultisetModifier modifier) {
BstMutationRule<E, Node<E>> mutationRule = BstMutationRule.createRule(
modifier,
BstCountBasedBalancePolicies.
<E, Node<E>>singleRebalancePolicy(distinctAggregate()),
nodeFactory());
BstMutationResult<E, Node<E>> mutationResult =
BstOperations.mutate(comparator(), mutationRule, rootReference.get(), e);
if (!rootReference.compareAndSet(
mutationResult.getOriginalRoot(), mutationResult.getChangedRoot())) {
throw new ConcurrentModificationException();
}
Node<E> original = mutationResult.getOriginalTarget();
return countOrZero(original);
}
@Override
public int add(E element, int occurrences) {
checkElement(element);
if (occurrences == 0) {
return count(element);
}
checkArgument(range.contains(element));
return mutate(element, new AddModifier(occurrences));
}
@Override
public int remove(@Nullable Object element, int occurrences) {
if (element == null) {
return 0;
} else if (occurrences == 0) {
return count(element);
}
try {
E e = checkElement(element);
return range.contains(e) ? mutate(e, new RemoveModifier(occurrences)) : 0;
} catch (ClassCastException e) {
return 0;
}
}
@Override
public boolean setCount(E element, int oldCount, int newCount) {
checkElement(element);
checkArgument(range.contains(element));
return mutate(element, new ConditionalSetCountModifier(oldCount, newCount))
== oldCount;
}
@Override
public int setCount(E element, int count) {
checkElement(element);
checkArgument(range.contains(element));
return mutate(element, new SetCountModifier(count));
}
private BstPathFactory<Node<E>, BstInOrderPath<Node<E>>> pathFactory() {
return BstInOrderPath.inOrderFactory();
}
@Override
Iterator<Entry<E>> entryIterator() {
Node<E> root = rootReference.get();
final BstInOrderPath<Node<E>> startingPath =
BstRangeOps.furthestPath(range, LEFT, pathFactory(), root);
return iteratorInDirection(startingPath, RIGHT);
}
@Override
Iterator<Entry<E>> descendingEntryIterator() {
Node<E> root = rootReference.get();
final BstInOrderPath<Node<E>> startingPath =
BstRangeOps.furthestPath(range, RIGHT, pathFactory(), root);
return iteratorInDirection(startingPath, LEFT);
}
private Iterator<Entry<E>> iteratorInDirection(
@Nullable BstInOrderPath<Node<E>> start, final BstSide direction) {
final Iterator<BstInOrderPath<Node<E>>> pathIterator =
new AbstractSequentialIterator<BstInOrderPath<Node<E>>>(start) {
@Override
protected BstInOrderPath<Node<E>> computeNext(BstInOrderPath<Node<E>> previous) {
if (!previous.hasNext(direction)) {
return null;
}
BstInOrderPath<Node<E>> next = previous.next(direction);
// TODO(user): only check against one side
return range.contains(next.getTip().getKey()) ? next : null;
}
};
return new Iterator<Entry<E>>() {
E toRemove = null;
@Override
public boolean hasNext() {
return pathIterator.hasNext();
}
@Override
public Entry<E> next() {
BstInOrderPath<Node<E>> path = pathIterator.next();
return new LiveEntry(
toRemove = path.getTip().getKey(), path.getTip().elemCount());
}
@Override
public void remove() {
checkState(toRemove != null);
setCount(toRemove, 0);
toRemove = null;
}
};
}
class LiveEntry extends Multisets.AbstractEntry<E> {
private Node<E> expectedRoot;
private final E element;
private int count;
private LiveEntry(E element, int count) {
this.expectedRoot = rootReference.get();
this.element = element;
this.count = count;
}
@Override
public E getElement() {
return element;
}
@Override
public int getCount() {
if (rootReference.get() == expectedRoot) {
return count;
} else {
// check for updates
expectedRoot = rootReference.get();
return count = TreeMultiset.this.count(element);
}
}
}
@Override
public void clear() {
Node<E> root = rootReference.get();
Node<E> cleared = BstRangeOps.minusRange(range,
BstCountBasedBalancePolicies.<E, Node<E>>fullRebalancePolicy(distinctAggregate()),
nodeFactory(), root);
if (!rootReference.compareAndSet(root, cleared)) {
throw new ConcurrentModificationException();
}
}
@Override
public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
checkNotNull(upperBound);
return new TreeMultiset<E>(
range.intersect(GeneralRange.upTo(comparator, upperBound, boundType)), rootReference);
}
@Override
public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
checkNotNull(lowerBound);
return new TreeMultiset<E>(
range.intersect(GeneralRange.downTo(comparator, lowerBound, boundType)), rootReference);
}
/**
* {@inheritDoc}
*
* @since 11.0
*/
@Override
public Comparator<? super E> comparator() {
return super.comparator();
}
private static final class Node<E> extends BstNode<E, Node<E>> implements Serializable {
private final long size;
private final int distinct;
private Node(E key, int elemCount, @Nullable Node<E> left,
@Nullable Node<E> right) {
super(key, left, right);
checkArgument(elemCount > 0);
this.size = (long) elemCount + sizeOrZero(left) + sizeOrZero(right);
this.distinct = 1 + distinctOrZero(left) + distinctOrZero(right);
}
int elemCount() {
long result = size - sizeOrZero(childOrNull(LEFT))
- sizeOrZero(childOrNull(RIGHT));
return Ints.checkedCast(result);
}
private Node(E key, int elemCount) {
this(key, elemCount, null, null);
}
private static final long serialVersionUID = 0;
}
private static long sizeOrZero(@Nullable Node<?> node) {
return (node == null) ? 0 : node.size;
}
private static int distinctOrZero(@Nullable Node<?> node) {
return (node == null) ? 0 : node.distinct;
}
private static int countOrZero(@Nullable Node<?> entry) {
return (entry == null) ? 0 : entry.elemCount();
}
@SuppressWarnings("unchecked")
private BstAggregate<Node<E>> distinctAggregate() {
return (BstAggregate) DISTINCT_AGGREGATE;
}
private static final BstAggregate<Node<Object>> DISTINCT_AGGREGATE =
new BstAggregate<Node<Object>>() {
@Override
public int entryValue(Node<Object> entry) {
return 1;
}
@Override
public long treeValue(@Nullable Node<Object> tree) {
return distinctOrZero(tree);
}
};
@SuppressWarnings("unchecked")
private BstAggregate<Node<E>> sizeAggregate() {
return (BstAggregate) SIZE_AGGREGATE;
}
private static final BstAggregate<Node<Object>> SIZE_AGGREGATE =
new BstAggregate<Node<Object>>() {
@Override
public int entryValue(Node<Object> entry) {
return entry.elemCount();
}
@Override
public long treeValue(@Nullable Node<Object> tree) {
return sizeOrZero(tree);
}
};
@SuppressWarnings("unchecked")
private BstNodeFactory<Node<E>> nodeFactory() {
return (BstNodeFactory) NODE_FACTORY;
}
private static final BstNodeFactory<Node<Object>> NODE_FACTORY =
new BstNodeFactory<Node<Object>>() {
@Override
public Node<Object> createNode(Node<Object> source, @Nullable Node<Object> left,
@Nullable Node<Object> right) {
return new Node<Object>(source.getKey(), source.elemCount(), left, right);
}
};
private abstract class MultisetModifier implements BstModifier<E, Node<E>> {
abstract int newCount(int oldCount);
@Nullable
@Override
public BstModificationResult<Node<E>> modify(E key, @Nullable Node<E> originalEntry) {
int oldCount = countOrZero(originalEntry);
int newCount = newCount(oldCount);
if (oldCount == newCount) {
return BstModificationResult.identity(originalEntry);
} else if (newCount == 0) {
return BstModificationResult.rebalancingChange(originalEntry, null);
} else if (oldCount == 0) {
return BstModificationResult.rebalancingChange(null, new Node<E>(key, newCount));
} else {
return BstModificationResult.rebuildingChange(originalEntry,
new Node<E>(originalEntry.getKey(), newCount));
}
}
}
private final class AddModifier extends MultisetModifier {
private final int countToAdd;
private AddModifier(int countToAdd) {
checkArgument(countToAdd > 0);
this.countToAdd = countToAdd;
}
@Override
int newCount(int oldCount) {
checkArgument(countToAdd <= Integer.MAX_VALUE - oldCount, "Cannot add this many elements");
return oldCount + countToAdd;
}
}
private final class RemoveModifier extends MultisetModifier {
private final int countToRemove;
private RemoveModifier(int countToRemove) {
checkArgument(countToRemove > 0);
this.countToRemove = countToRemove;
}
@Override
int newCount(int oldCount) {
return Math.max(0, oldCount - countToRemove);
}
}
private final class SetCountModifier extends MultisetModifier {
private final int countToSet;
private SetCountModifier(int countToSet) {
checkArgument(countToSet >= 0);
this.countToSet = countToSet;
}
@Override
int newCount(int oldCount) {
return countToSet;
}
}
private final class ConditionalSetCountModifier extends MultisetModifier {
private final int expectedCount;
private final int setCount;
private ConditionalSetCountModifier(int expectedCount, int setCount) {
checkArgument(setCount >= 0 & expectedCount >= 0);
this.expectedCount = expectedCount;
this.setCount = setCount;
}
@Override
int newCount(int oldCount) {
return (oldCount == expectedCount) ? setCount : oldCount;
}
}
/*
* 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<Node<E>>());
Serialization.populateMultiset(this, stream);
}
@GwtIncompatible("not needed in emulated source")
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.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet.ArrayImmutableSet;
/**
* Implementation of {@link ImmutableSet} with two or more elements.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class RegularImmutableSet<E> extends ArrayImmutableSet<E> {
// the same elements in hashed positions (plus nulls)
@VisibleForTesting final transient Object[] table;
// 'and' with an int to get a valid table index.
private final transient int mask;
private final transient int hashCode;
RegularImmutableSet(
Object[] elements, int hashCode, Object[] table, int mask) {
super(elements);
this.table = table;
this.mask = mask;
this.hashCode = hashCode;
}
@Override public boolean contains(Object target) {
if (target == null) {
return false;
}
for (int i = Hashing.smear(target.hashCode()); true; i++) {
Object candidate = table[i & mask];
if (candidate == null) {
return false;
}
if (candidate.equals(target)) {
return true;
}
}
}
@Override public int hashCode() {
return hashCode;
}
@Override boolean isHashCodeFast() {
return true;
}
}
| 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 javax.annotation.Nullable;
/**
* A specification for a local change to an entry in a binary search tree.
*
* @author Louis Wasserman
*/
@GwtCompatible
interface BstModifier<K, N extends BstNode<K, N>> {
/**
* Given a target key and the original entry (if any) with the specified key, returns the entry
* with key {@code key} after this mutation has been performed. The result must either be {@code
* null} or must have a key that compares as equal to {@code key}. A deletion operation, for
* example, would always return {@code null}, or an insertion operation would always return a
* non-null {@code insertedEntry}.
*
* <p>If this method returns a non-null entry of type {@code N}, any children it has will be
* ignored.
*
* <p>This method may return {@code originalEntry} itself to indicate that no change is made.
*
* @param key The key being targeted for modification.
* @param originalEntry The original entry in the binary search tree with the specified key, if
* any. No guarantees are made about the children of this entry when treated as a node; in
* particular, they are not necessarily the children of the corresponding node in the
* binary search tree.
* @return the entry (if any) with the specified key after this modification is performed
*/
BstModificationResult<N> modify(K key, @Nullable N originalEntry);
}
| 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 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.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) {
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
*/
@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) {
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) {
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;
}
}
};
}
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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Nullable;
/** An ordering that compares objects according to a given order. */
@GwtCompatible(serializable = true)
final class ExplicitOrdering<T> extends Ordering<T> implements Serializable {
final ImmutableMap<T, Integer> rankMap;
ExplicitOrdering(List<T> valuesInOrder) {
this(buildRankMap(valuesInOrder));
}
ExplicitOrdering(ImmutableMap<T, Integer> rankMap) {
this.rankMap = rankMap;
}
@Override public int compare(T left, T right) {
return rank(left) - rank(right); // safe because both are nonnegative
}
private int rank(T value) {
Integer rank = rankMap.get(value);
if (rank == null) {
throw new IncomparableValueException(value);
}
return rank;
}
private static <T> ImmutableMap<T, Integer> buildRankMap(
List<T> valuesInOrder) {
ImmutableMap.Builder<T, Integer> builder = ImmutableMap.builder();
int rank = 0;
for (T value : valuesInOrder) {
builder.put(value, rank++);
}
return builder.build();
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof ExplicitOrdering) {
ExplicitOrdering<?> that = (ExplicitOrdering<?>) object;
return this.rankMap.equals(that.rankMap);
}
return false;
}
@Override public int hashCode() {
return rankMap.hashCode();
}
@Override public String toString() {
return "Ordering.explicit(" + rankMap.keySet() + ")";
}
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 static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableSet.ArrayImmutableSet;
import com.google.common.collect.ImmutableSet.TransformedImmutableSet;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Implementation of {@link ImmutableMap} with two or more entries.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Gregory Kick
*/
@GwtCompatible(serializable = true, emulated = true)
final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// entries in insertion order
private final transient LinkedEntry<K, V>[] entries;
// array of linked lists of entries
private final transient LinkedEntry<K, V>[] table;
// 'and' with an int to get a table index
private final transient int mask;
private final transient int keySetHashCode;
// TODO(gak): investigate avoiding the creation of ImmutableEntries since we
// re-copy them anyway.
RegularImmutableMap(Entry<?, ?>... immutableEntries) {
int size = immutableEntries.length;
entries = createEntryArray(size);
int tableSize = chooseTableSize(size);
table = createEntryArray(tableSize);
mask = tableSize - 1;
int keySetHashCodeMutable = 0;
for (int entryIndex = 0; entryIndex < size; entryIndex++) {
// each of our 6 callers carefully put only Entry<K, V>s into the array!
@SuppressWarnings("unchecked")
Entry<K, V> entry = (Entry<K, V>) immutableEntries[entryIndex];
K key = entry.getKey();
int keyHashCode = key.hashCode();
keySetHashCodeMutable += keyHashCode;
int tableIndex = Hashing.smear(keyHashCode) & mask;
@Nullable LinkedEntry<K, V> existing = table[tableIndex];
// prepend, not append, so the entries can be immutable
LinkedEntry<K, V> linkedEntry =
newLinkedEntry(key, entry.getValue(), existing);
table[tableIndex] = linkedEntry;
entries[entryIndex] = linkedEntry;
while (existing != null) {
checkArgument(!key.equals(existing.getKey()), "duplicate key: %s", key);
existing = existing.next();
}
}
keySetHashCode = keySetHashCodeMutable;
}
private static int chooseTableSize(int size) {
// least power of 2 greater than size
int tableSize = Integer.highestOneBit(size) << 1;
checkArgument(tableSize > 0, "table too large: %s", size);
return tableSize;
}
/**
* Creates a {@link LinkedEntry} array to hold parameterized entries. The
* result must never be upcast back to LinkedEntry[] (or Object[], etc.), or
* allowed to escape the class.
*/
@SuppressWarnings("unchecked") // Safe as long as the javadocs are followed
private LinkedEntry<K, V>[] createEntryArray(int size) {
return new LinkedEntry[size];
}
private static <K, V> LinkedEntry<K, V> newLinkedEntry(K key, V value,
@Nullable LinkedEntry<K, V> next) {
return (next == null)
? new TerminalEntry<K, V>(key, value)
: new NonTerminalEntry<K, V>(key, value, next);
}
private interface LinkedEntry<K, V> extends Entry<K, V> {
/** Returns the next entry in the list or {@code null} if none exists. */
@Nullable LinkedEntry<K, V> next();
}
/** {@code LinkedEntry} implementation that has a next value. */
@Immutable
@SuppressWarnings("serial") // this class is never serialized
private static final class NonTerminalEntry<K, V>
extends ImmutableEntry<K, V> implements LinkedEntry<K, V> {
final LinkedEntry<K, V> next;
NonTerminalEntry(K key, V value, LinkedEntry<K, V> next) {
super(key, value);
this.next = next;
}
@Override public LinkedEntry<K, V> next() {
return next;
}
}
/**
* {@code LinkedEntry} implementation that serves as the last entry in the
* list. I.e. no next entry
*/
@Immutable
@SuppressWarnings("serial") // this class is never serialized
private static final class TerminalEntry<K, V> extends ImmutableEntry<K, V>
implements LinkedEntry<K, V> {
TerminalEntry(K key, V value) {
super(key, value);
}
@Nullable @Override public LinkedEntry<K, V> next() {
return null;
}
}
@Override public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int index = Hashing.smear(key.hashCode()) & mask;
for (LinkedEntry<K, V> entry = table[index];
entry != null;
entry = entry.next()) {
K candidateKey = entry.getKey();
/*
* Assume that equals uses the == optimization when appropriate, and that
* it would check hash codes as an optimization when appropriate. If we
* did these things, it would just make things worse for the most
* performance-conscious users.
*/
if (key.equals(candidateKey)) {
return entry.getValue();
}
}
return null;
}
@Override
public int size() {
return entries.length;
}
@Override public boolean isEmpty() {
return false;
}
@Override public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
for (Entry<K, V> entry : entries) {
if (entry.getValue().equals(value)) {
return true;
}
}
return false;
}
@Override boolean isPartialView() {
return false;
}
private transient ImmutableSet<Entry<K, V>> entrySet;
@Override public ImmutableSet<Entry<K, V>> entrySet() {
ImmutableSet<Entry<K, V>> es = entrySet;
return (es == null) ? (entrySet = new EntrySet<K, V>(this)) : es;
}
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
private static class EntrySet<K, V> extends ArrayImmutableSet<Entry<K, V>> {
final transient RegularImmutableMap<K, V> map;
EntrySet(RegularImmutableMap<K, V> map) {
super(map.entries);
this.map = map;
}
@Override public boolean contains(Object target) {
if (target instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) target;
V mappedValue = map.get(entry.getKey());
return mappedValue != null && mappedValue.equals(entry.getValue());
}
return false;
}
}
private transient ImmutableSet<K> keySet;
@Override public ImmutableSet<K> keySet() {
ImmutableSet<K> ks = keySet;
return (ks == null) ? (keySet = new KeySet<K, V>(this)) : ks;
}
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
private static class KeySet<K, V>
extends TransformedImmutableSet<Entry<K, V>, K> {
final RegularImmutableMap<K, V> map;
KeySet(RegularImmutableMap<K, V> map) {
super(map.entries, map.keySetHashCode);
this.map = map;
}
@Override K transform(Entry<K, V> element) {
return element.getKey();
}
@Override public boolean contains(Object target) {
return map.containsKey(target);
}
@Override boolean isPartialView() {
return true;
}
}
private transient ImmutableCollection<V> values;
@Override public ImmutableCollection<V> values() {
ImmutableCollection<V> v = values;
return (v == null) ? (values = new Values<V>(this)) : v;
}
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
private static class Values<V> extends ImmutableCollection<V> {
final RegularImmutableMap<?, V> map;
Values(RegularImmutableMap<?, V> map) {
this.map = map;
}
@Override
public int size() {
return map.entries.length;
}
@Override public UnmodifiableIterator<V> iterator() {
return new AbstractIndexedListIterator<V>(map.entries.length) {
@Override protected V get(int index) {
return map.entries[index].getValue();
}
};
}
@Override public boolean contains(Object target) {
return map.containsValue(target);
}
@Override boolean isPartialView() {
return true;
}
}
@Override public String toString() {
StringBuilder result
= Collections2.newStringBuilderForCollection(size()).append('{');
Collections2.STANDARD_JOINER.appendTo(result, entries);
return result.append('}').toString();
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
}
| 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.Comparator;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A sorted set multimap which forwards all its method calls to another sorted
* set 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 ForwardingSortedSetMultimap<K, V>
extends ForwardingSetMultimap<K, V> implements SortedSetMultimap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingSortedSetMultimap() {}
@Override protected abstract SortedSetMultimap<K, V> delegate();
@Override public SortedSet<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override public SortedSet<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
@Override public Comparator<? super V> valueComparator() {
return delegate().valueComparator();
}
}
| 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.ListIterator;
/**
* A list iterator that does not support {@link #remove}, {@link #add}, or
* {@link #set}.
*
* @since 7.0
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class UnmodifiableListIterator<E>
extends UnmodifiableIterator<E> implements ListIterator<E> {
/** Constructor for use by subclasses. */
protected UnmodifiableListIterator() {}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override public final void add(E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override public final void set(E e) {
throw new UnsupportedOperationException();
}
}
| 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.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Equivalences;
import com.google.common.base.Function;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link Map} instances (including instances of
* {@link SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts
* {@link Lists}, {@link Sets} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Maps">
* {@code Maps}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Isaac Shum
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Maps {
private Maps() {}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
* #newEnumMap} instead.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity"
* that it <i>should</i> hold {@code expectedSize} elements without growth.
* This behavior cannot be broadly guaranteed, but it is observed to be true
* for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of elements you expect to add to the
* returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
int expectedSize) {
return new HashMap<K, V>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as
* long as it grows no larger than expectedSize and the load factor is >= its
* default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkArgument(expectedSize >= 0);
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
return expectedSize + expectedSize / 3;
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as
* the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link
* #newEnumMap} instead.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code
* map}
*/
public static <K, V> HashMap<K, V> newHashMap(
Map<? extends K, ? extends V> map) {
return new HashMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap}
* instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
/**
* Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance
* with the same mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from
* {@code map}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(
Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
}
/**
* Returns a general-purpose instance of {@code ConcurrentMap}, which supports
* all optional operations of the ConcurrentMap interface. It does not permit
* null keys or values. It is serializable.
*
* <p>This is currently accomplished by calling {@link MapMaker#makeMap()}.
*
* <p>It is preferable to use {@code MapMaker} directly (rather than through
* this method), as it presents numerous useful configuration options,
* such as the concurrency level, load factor, key/value reference types,
* and value computation.
*
* @return a new, empty {@code ConcurrentMap}
* @since 3.0
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new MapMaker().<K, V>makeMap();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural
* ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#of()} instead.
*
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
/**
* Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as
* the specified map and using the same ordering as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
* @param map the sorted map whose mappings are to be placed in the new map
* and whose comparator is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code
* map} and using the comparator of {@code map}
*/
public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
return new TreeMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(
@Nullable Comparator<C> comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator<Class<?>> comparator = null;
// Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
return new TreeMap<K, V>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
return new EnumMap<K, V>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code
* map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(
Map<K, ? extends V> map) {
return new EnumMap<K, V>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<K, V>();
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* <p><b>Note:</b>If you only need to know whether two maps have the same
* mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
@SuppressWarnings("unchecked")
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
SortedMapDifference<K, V> result = difference(sortedLeft, right);
return result;
}
return difference(left, right, Equivalences.equals());
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Values are compared using a provided equivalence, in the case of
* equality, the value on the 'left' is returned in the difference.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @param valueEquivalence the equivalence relationship to use to compare
* values
* @return the difference between the two maps
* @since 10.0
*/
@Beta
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newHashMap();
Map<K, V> onlyOnRight = new HashMap<K, V>(right); // will whittle it down
Map<K, V> onBoth = newHashMap();
Map<K, MapDifference.ValueDifference<V>> differences = newHashMap();
boolean eq = true;
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
eq = false;
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
eq = false;
onlyOnLeft.put(leftKey, leftValue);
}
}
boolean areEqual = eq && onlyOnRight.isEmpty();
return mapDifference(
areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> MapDifference<K, V> mapDifference(boolean areEqual,
Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
return new MapDifferenceImpl<K, V>(areEqual,
Collections.unmodifiableMap(onlyOnLeft),
Collections.unmodifiableMap(onlyOnRight),
Collections.unmodifiableMap(onBoth),
Collections.unmodifiableMap(differences));
}
static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
final boolean areEqual;
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(boolean areEqual, Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.areEqual = areEqual;
this.onlyOnLeft = onlyOnLeft;
this.onlyOnRight = onlyOnRight;
this.onBoth = onBoth;
this.differences = differences;
}
@Override
public boolean areEqual() {
return areEqual;
}
@Override
public Map<K, V> entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map<K, V> entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map<K, V> entriesInCommon() {
return onBoth;
}
@Override
public Map<K, ValueDifference<V>> entriesDiffering() {
return differences;
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference<?, ?> other = (MapDifference<?, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(),
entriesInCommon(), entriesDiffering());
}
@Override public String toString() {
if (areEqual) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl<V>
implements MapDifference.ValueDifference<V> {
private final V left;
private final V right;
static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) {
return new ValueDifferenceImpl<V>(left, right);
}
private ValueDifferenceImpl(@Nullable V left, @Nullable V right) {
this.left = left;
this.right = right;
}
@Override
public V leftValue() {
return left;
}
@Override
public V rightValue() {
return right;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof MapDifference.ValueDifference<?>) {
MapDifference.ValueDifference<?> that =
(MapDifference.ValueDifference<?>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(left, right);
}
@Override public String toString() {
return "(" + left + ", " + right + ")";
}
}
/**
* Computes the difference between two sorted maps, using the comparator of
* the left map, or {@code Ordering.natural()} if the left map uses the
* natural ordering of its elements. This difference is an immutable snapshot
* of the state of the maps at the time this method is called. It will never
* change, even if the maps change at a later time.
*
* <p>Since this method uses {@code TreeMap} instances internally, the keys of
* the right map must all compare as distinct according to the comparator
* of the left map.
*
* <p><b>Note:</b>If you only need to know whether two sorted maps have the
* same mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
@Beta
public static <K, V> SortedMapDifference<K, V> difference(
SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator<? super K> comparator = orNaturalOrder(left.comparator());
SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences =
Maps.newTreeMap(comparator);
boolean eq = true;
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (Objects.equal(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
eq = false;
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
eq = false;
onlyOnLeft.put(leftKey, leftValue);
}
}
boolean areEqual = eq && onlyOnRight.isEmpty();
return sortedMapDifference(
areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> SortedMapDifference<K, V> sortedMapDifference(
boolean areEqual, SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight,
SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) {
return new SortedMapDifferenceImpl<K, V>(areEqual,
Collections.unmodifiableSortedMap(onlyOnLeft),
Collections.unmodifiableSortedMap(onlyOnRight),
Collections.unmodifiableSortedMap(onBoth),
Collections.unmodifiableSortedMap(differences));
}
static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(boolean areEqual, SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override public SortedMap<K, ValueDifference<V>> entriesDiffering() {
return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
}
@Override public SortedMap<K, V> entriesInCommon() {
return (SortedMap<K, V>) super.entriesInCommon();
}
@Override public SortedMap<K, V> entriesOnlyOnLeft() {
return (SortedMap<K, V>) super.entriesOnlyOnLeft();
}
@Override public SortedMap<K, V> entriesOnlyOnRight() {
return (SortedMap<K, V>) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code
* Ordering.natural()}. This method is an abomination of generics; the only
* purpose of this method is to contain the ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static <E> Comparator<? super E> orNaturalOrder(
@Nullable Comparator<? super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator<E>) Ordering.natural();
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* <b>Deprecated.</b>
*
* @since 10.0
* @deprecated use {@link #uniqueIndex(Iterator, Function)} by casting {@code
* values} to {@code Iterator<V>}, or better yet, by implementing only
* {@code Iterator} and not {@code Iterable}. <b>This method is scheduled
* for deletion in March 2012.</b>
*/
@Beta
@Deprecated
public static <K, V, I extends Object & Iterable<V> & Iterator<V>>
ImmutableMap<K, V> uniqueIndex(
I values, Function<? super V, K> keyFunction) {
Iterable<V> valuesIterable = checkNotNull(values);
return uniqueIndex(valuesIterable, keyFunction);
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
* @since 10.0
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
/**
* Creates an {@code ImmutableMap<String, String>} from a {@code Properties}
* instance. Properties normally derive from {@code Map<Object, Object>}, but
* they typically contain strings, which is awkward. This method lets you get
* a plain-old-{@code Map} out of a {@code Properties}.
*
* @param properties a {@code Properties} object to be converted
* @return an immutable map containing all the entries in {@code properties}
* @throws ClassCastException if any key in {@code Properties} is not a {@code
* String}
* @throws NullPointerException if any key or value in {@code Properties} is
* null
*/
@GwtIncompatible("java.util.Properties")
public static ImmutableMap<String, String> fromProperties(
Properties properties) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
builder.put(key, properties.getProperty(key));
}
return builder.build();
}
/**
* Returns an immutable map entry with the specified key and value. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException}.
*
* <p>The returned entry is serializable.
*
* @param key the key to be associated with the returned entry
* @param value the value to be associated with the returned entry
*/
@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(
@Nullable K key, @Nullable V value) {
return new ImmutableEntry<K, V>(key, value);
}
/**
* Returns an unmodifiable view of the specified set of entries. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException},
* as do any operations that would modify the returned set.
*
* @param entrySet the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
static <K, V> Set<Entry<K, V>> unmodifiableEntrySet(
Set<Entry<K, V>> entrySet) {
return new UnmodifiableEntrySet<K, V>(
Collections.unmodifiableSet(entrySet));
}
/**
* Returns an unmodifiable view of the specified map entry. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException}.
* This also has the side-effect of redefining {@code equals} to comply with
* the Entry contract, to avoid a possible nefarious implementation of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
static <K, V> Entry<K, V> unmodifiableEntry(final Entry<K, V> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V getValue() {
return entry.getValue();
}
};
}
/** @see Multimaps#unmodifiableEntries */
static class UnmodifiableEntries<K, V>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
UnmodifiableEntries(Collection<Entry<K, V>> entries) {
this.entries = entries;
}
@Override protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> delegate = super.iterator();
return new ForwardingIterator<Entry<K, V>>() {
@Override public Entry<K, V> next() {
return unmodifiableEntry(super.next());
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
@Override protected Iterator<Entry<K, V>> delegate() {
return delegate;
}
};
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean add(Entry<K, V> element) {
throw new UnsupportedOperationException();
}
@Override public boolean addAll(
Collection<? extends Entry<K, V>> collection) {
throw new UnsupportedOperationException();
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object object) {
throw new UnsupportedOperationException();
}
@Override public boolean removeAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override public boolean retainAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
}
/** @see Maps#unmodifiableEntrySet(Set) */
static class UnmodifiableEntrySet<K, V>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
super(entries);
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/**
* Returns a synchronized (thread-safe) bimap backed by the specified bimap.
* In order to guarantee serial access, it is critical that <b>all</b> access
* to the backing bimap is accomplished through the returned bimap.
*
* <p>It is imperative that the user manually synchronize on the returned map
* when accessing any of its collection views: <pre> {@code
*
* BiMap<Long, String> map = Maps.synchronizedBiMap(
* HashBiMap.<Long, String>create());
* ...
* Set<Long> set = map.keySet(); // Needn't be in synchronized block
* ...
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<Long> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap to be wrapped in a synchronized view
* @return a sychronized view of the specified bimap
*/
public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
return Synchronized.biMap(bimap, null);
}
/**
* Returns an unmodifiable view of the specified bimap. This method allows
* modules to provide users with "read-only" access to internal bimaps. Query
* operations on the returned bimap "read through" to the specified bimap, and
* attempts to modify the returned map, whether direct or via its collection
* views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified bimap
*/
public static <K, V> BiMap<K, V> unmodifiableBiMap(
BiMap<? extends K, ? extends V> bimap) {
return new UnmodifiableBiMap<K, V>(bimap, null);
}
/** @see Maps#unmodifiableBiMap(BiMap) */
private static class UnmodifiableBiMap<K, V>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
transient BiMap<V, K> inverse;
transient Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate,
@Nullable BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
this.delegate = delegate;
this.inverse = inverse;
}
@Override protected Map<K, V> delegate() {
return unmodifiableMap;
}
@Override
public V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null)
? inverse = new UnmodifiableBiMap<V, K>(delegate.inverse(), this)
: result;
}
@Override public Set<V> values() {
Set<V> result = values;
return (result == null)
? values = Collections.unmodifiableSet(delegate.values())
: result;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a view of a map where each value is transformed by a function. All
* other properties of the map, such as iteration order, are left intact. For
* example, the code: <pre> {@code
*
* Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* Map<String, Double> transformed = Maps.transformValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*/
public static <K, V1, V2> Map<K, V2> transformValues(
Map<K, V1> fromMap, final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMap, transformer);
}
/**
* Returns a view of a sorted map where each value is transformed by a
* function. All other properties of the map, such as iteration order, are
* left intact. For example, the code: <pre> {@code
*
* SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* SortedMap<String, Double> transformed =
* Maps.transformSortedValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*
* @since 11.0
*/
@Beta
public static <K, V1, V2> SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMap, transformer);
}
/**
* Returns a view of a map whose values are derived from the original map's
* entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "no" + key;
* }
* };
* Map<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {verbose=verbose, sort=nosort}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 7.0
*/
public static <K, V1, V2> Map<K, V2> transformEntries(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
if (fromMap instanceof SortedMap) {
return transformEntries((SortedMap<K, V1>) fromMap, transformer);
}
return new TransformedEntriesMap<K, V1, V2>(fromMap, transformer);
}
/**
* Returns a view of a sorted map whose values are derived from the original
* sorted map's entries. In contrast to {@link #transformValues}, this
* method's entry-transformation logic may depend on the key as well as the
* value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableSortedMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "yes" + key;
* }
* };
* SortedMap<String, String> transformed =
* LabsMaps.transformSortedEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 11.0
*/
@Beta
public static <K, V1, V2> SortedMap<K, V2> transformEntries(
final SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesSortedMap<K, V1, V2>(fromMap, transformer);
}
/**
* A transformation of the value of a key-value pair, using both key and value
* as inputs. To apply the transformation to a map, use
* {@link Maps#transformEntries(Map, EntryTransformer)}.
*
* @param <K> the key type of the input and output entries
* @param <V1> the value type of the input entry
* @param <V2> the value type of the output entry
* @since 7.0
*/
public interface EntryTransformer<K, V1, V2> {
/**
* Determines an output value based on a key-value pair. This method is
* <i>generally expected</i>, but not absolutely required, to have the
* following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is,
* {@link Objects#equal Objects.equal}{@code (k1, k2) &&}
* {@link Objects#equal}{@code (v1, v2)} implies that {@code
* Objects.equal(transformer.transform(k1, v1),
* transformer.transform(k2, v2))}.
* </ul>
*
* @throws NullPointerException if the key or value is null and this
* transformer does not accept null arguments
*/
V2 transformEntry(@Nullable K key, @Nullable V1 value);
}
static class TransformedEntriesMap<K, V1, V2>
extends AbstractMap<K, V2> {
final Map<K, V1> fromMap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMap(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMap = checkNotNull(fromMap);
this.transformer = checkNotNull(transformer);
}
@Override public int size() {
return fromMap.size();
}
@Override public boolean containsKey(Object key) {
return fromMap.containsKey(key);
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 get(Object key) {
V1 value = fromMap.get(key);
return (value != null || fromMap.containsKey(key))
? transformer.transformEntry((K) key, value)
: null;
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 remove(Object key) {
return fromMap.containsKey(key)
? transformer.transformEntry((K) key, fromMap.remove(key))
: null;
}
@Override public void clear() {
fromMap.clear();
}
@Override public Set<K> keySet() {
return fromMap.keySet();
}
Set<Entry<K, V2>> entrySet;
@Override public Set<Entry<K, V2>> entrySet() {
Set<Entry<K, V2>> result = entrySet;
if (result == null) {
entrySet = result = new EntrySet<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
@Override public Iterator<Entry<K, V2>> iterator() {
final Iterator<Entry<K, V1>> backingIterator =
fromMap.entrySet().iterator();
return Iterators.transform(backingIterator,
new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override public Entry<K, V2> apply(Entry<K, V1> entry) {
return immutableEntry(
entry.getKey(),
transformer.transformEntry(entry.getKey(),
entry.getValue()));
}
});
}
};
}
return result;
}
Collection<V2> values;
@Override public Collection<V2> values() {
Collection<V2> result = values;
if (result == null) {
return values = new Values<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
};
}
return result;
}
}
static class TransformedEntriesSortedMap<K, V1, V2>
extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
protected SortedMap<K, V1> fromMap() {
return (SortedMap<K, V1>) fromMap;
}
TransformedEntriesSortedMap(SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override public Comparator<? super K> comparator() {
return fromMap().comparator();
}
@Override public K firstKey() {
return fromMap().firstKey();
}
@Override public SortedMap<K, V2> headMap(K toKey) {
return transformEntries(fromMap().headMap(toKey), transformer);
}
@Override public K lastKey() {
return fromMap().lastKey();
}
@Override public SortedMap<K, V2> subMap(K fromKey, K toKey) {
return transformEntries(
fromMap().subMap(fromKey, toKey), transformer);
}
@Override public SortedMap<K, V2> tailMap(K fromKey) {
return transformEntries(fromMap().tailMap(fromKey), transformer);
}
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} 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.
*/
public static <K, V> Map<K, V> filterKeys(
Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof SortedMap) {
return filterKeys((SortedMap<K, V>) unfiltered, keyPredicate);
}
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredKeyMap<K, V>(
checkNotNull(unfiltered), keyPredicate, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* keys satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} 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.
*
* @since 11.0
*/
@Beta
public static <K, V> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO: Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} 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.
*/
public static <K, V> Map<K, V> filterValues(
Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
if (unfiltered instanceof SortedMap) {
return filterValues((SortedMap<K, V>) unfiltered, valuePredicate);
}
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* values satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} 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.
*
* @since 11.0
*/
@Beta
public static <K, V> SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a map containing the mappings in {@code unfiltered} that satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes
* to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*/
public static <K, V> Map<K, V> filterEntries(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
if (unfiltered instanceof SortedMap) {
return filterEntries((SortedMap<K, V>) unfiltered, entryPredicate);
}
checkNotNull(entryPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 11.0
*/
@Beta
public static <K, V> SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntrySortedMap)
? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered map.
*/
private static <K, V> Map<K, V> filterFiltered(AbstractFilteredMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate =
Predicates.and(map.predicate, entryPredicate);
return new FilteredEntryMap<K, V>(map.unfiltered, predicate);
}
private abstract static class AbstractFilteredMap<K, V>
extends AbstractMap<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
AbstractFilteredMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
boolean apply(Object key, V value) {
// This method is called only when the key is in the map, implying that
// key is a K.
@SuppressWarnings("unchecked")
K k = (K) key;
return predicate.apply(Maps.immutableEntry(k, value));
}
@Override public V put(K key, V value) {
checkArgument(apply(key, value));
return unfiltered.put(key, value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
checkArgument(apply(entry.getKey(), entry.getValue()));
}
unfiltered.putAll(map);
}
@Override public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
}
@Override public V get(Object key) {
V value = unfiltered.get(key);
return ((value != null) && apply(key, value)) ? value : null;
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public V remove(Object key) {
return containsKey(key) ? unfiltered.remove(key) : null;
}
Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = new Values() : result;
}
class Values extends AbstractCollection<V> {
@Override public Iterator<V> iterator() {
final Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
@Override public int size() {
return entrySet().size();
}
@Override public void clear() {
entrySet().clear();
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public boolean remove(Object o) {
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> collection) {
checkNotNull(collection);
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (collection.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> collection) {
checkNotNull(collection);
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!collection.contains(entry.getValue())
&& predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@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);
}
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered sorted map.
*/
private static <K, V> SortedMap<K, V> filterFiltered(
FilteredEntrySortedMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredEntrySortedMap<K, V>(map.sortedMap(), predicate);
}
private static class FilteredEntrySortedMap<K, V>
extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
FilteredEntrySortedMap(SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
}
SortedMap<K, V> sortedMap() {
return (SortedMap<K, V>) unfiltered;
}
@Override public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override public K firstKey() {
// correctly throws NoSuchElementException when filtered map is empty.
return keySet().iterator().next();
}
@Override public K lastKey() {
SortedMap<K, V> headMap = sortedMap();
while (true) {
// correctly throws NoSuchElementException when filtered map is empty.
K key = headMap.lastKey();
if (apply(key, unfiltered.get(key))) {
return key;
}
headMap = sortedMap().headMap(key);
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
return new FilteredEntrySortedMap<K, V>(sortedMap().headMap(toKey), predicate);
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().subMap(fromKey, toKey), predicate);
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().tailMap(fromKey), predicate);
}
}
private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> {
Predicate<? super K> keyPredicate;
FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate,
Predicate<Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null)
? entrySet = Sets.filter(unfiltered.entrySet(), predicate)
: result;
}
Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null)
? keySet = Sets.filter(unfiltered.keySet(), keyPredicate)
: result;
}
// The cast is called only when the key is in the unfiltered map, implying
// that key is a K.
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
}
}
static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> {
/**
* Entries in this set satisfy the predicate, but they don't validate the
* input to {@code Entry.setValue()}.
*/
final Set<Entry<K, V>> filteredEntrySet;
FilteredEntryMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
}
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>> {
@Override protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator();
return new UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry<K, V> next() {
final Entry<K, V> entry = iterator.next();
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return entry;
}
@Override public V setValue(V value) {
checkArgument(apply(entry.getKey(), value));
return super.setValue(value);
}
};
}
};
}
}
Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = new KeySet() : result;
}
private class KeySet extends AbstractSet<K> {
@Override public Iterator<K> iterator() {
final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator();
return new UnmodifiableIterator<K>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public K next() {
return iterator.next().getKey();
}
};
}
@Override public int size() {
return filteredEntrySet.size();
}
@Override public void clear() {
filteredEntrySet.clear();
}
@Override public boolean contains(Object o) {
return containsKey(o);
}
@Override public boolean remove(Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
@Override public boolean removeAll(Collection<?> collection) {
checkNotNull(collection); // for GWT
boolean changed = false;
for (Object obj : collection) {
changed |= remove(obj);
}
return changed;
}
@Override public boolean retainAll(Collection<?> collection) {
checkNotNull(collection); // for GWT
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!collection.contains(entry.getKey()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@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);
}
}
}
/**
* Returns an unmodifiable view of the specified navigable map. Query operations on the returned
* map read through to the specified map, and attempts to modify the returned map, whether direct
* or via its views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned navigable map will be serializable if the specified navigable map is
* serializable.
*
* @param map the navigable map for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable map
* @since 12.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, V> map) {
checkNotNull(map);
if (map instanceof UnmodifiableNavigableMap) {
return map;
} else {
return new UnmodifiableNavigableMap<K, V>(map);
}
}
@Nullable private static <K, V> Entry<K, V> unmodifiableOrNull(@Nullable Entry<K, V> entry) {
return (entry == null) ? null : Maps.unmodifiableEntry(entry);
}
@GwtIncompatible("NavigableMap")
static class UnmodifiableNavigableMap<K, V>
extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable {
private final NavigableMap<K, V> delegate;
UnmodifiableNavigableMap(NavigableMap<K, V> delegate) {
this.delegate = delegate;
}
@Override
protected SortedMap<K, V> delegate() {
return Collections.unmodifiableSortedMap(delegate);
}
@Override
public Entry<K, V> lowerEntry(K key) {
return unmodifiableOrNull(delegate.lowerEntry(key));
}
@Override
public K lowerKey(K key) {
return delegate.lowerKey(key);
}
@Override
public Entry<K, V> floorEntry(K key) {
return unmodifiableOrNull(delegate.floorEntry(key));
}
@Override
public K floorKey(K key) {
return delegate.floorKey(key);
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return unmodifiableOrNull(delegate.ceilingEntry(key));
}
@Override
public K ceilingKey(K key) {
return delegate.ceilingKey(key);
}
@Override
public Entry<K, V> higherEntry(K key) {
return unmodifiableOrNull(delegate.higherEntry(key));
}
@Override
public K higherKey(K key) {
return delegate.higherKey(key);
}
@Override
public Entry<K, V> firstEntry() {
return unmodifiableOrNull(delegate.firstEntry());
}
@Override
public Entry<K, V> lastEntry() {
return unmodifiableOrNull(delegate.lastEntry());
}
@Override
public final Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public final Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
private transient UnmodifiableNavigableMap<K, V> descendingMap;
@Override
public NavigableMap<K, V> descendingMap() {
UnmodifiableNavigableMap<K, V> result = descendingMap;
if (result == null) {
descendingMap = result = new UnmodifiableNavigableMap<K, V>(delegate.descendingMap());
result.descendingMap = this;
}
return result;
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
@Override
public NavigableSet<K> navigableKeySet() {
return Sets.unmodifiableNavigableSet(delegate.navigableKeySet());
}
@Override
public NavigableSet<K> descendingKeySet() {
return Sets.unmodifiableNavigableSet(delegate.descendingKeySet());
}
@Override
public
NavigableMap<K, V>
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return Maps.unmodifiableNavigableMap(delegate.subMap(
fromKey,
fromInclusive,
toKey,
toInclusive));
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive));
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive));
}
}
/**
* {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code
* entrySet().isEmpty()} instead of {@code size() == 0} to speed up
* implementations where {@code size()} is O(n), and it delegates the {@code
* isEmpty()} methods of its key set and value collection to this
* implementation.
*/
@GwtCompatible
static abstract class ImprovedAbstractMap<K, V> extends AbstractMap<K, V> {
/**
* Creates the entry set to be returned by {@link #entrySet()}. This method
* is invoked at most once on a given map, at the time when {@code entrySet}
* is first called.
*/
protected abstract Set<Entry<K, V>> createEntrySet();
private Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
if (result == null) {
entrySet = result = createEntrySet();
}
return result;
}
private Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
return keySet = new KeySet<K, V>() {
@Override Map<K, V> map() {
return ImprovedAbstractMap.this;
}
};
}
return result;
}
private Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
return values = new Values<K, V>(){
@Override Map<K, V> map() {
return ImprovedAbstractMap.this;
}
};
}
return result;
}
/**
* Returns {@code true} if this map contains no key-value mappings.
*
* <p>The implementation returns {@code entrySet().isEmpty()}.
*
* @return {@code true} if this map contains no key-value mappings
*/
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
}
static final MapJoiner STANDARD_JOINER =
Collections2.STANDARD_JOINER.withKeyValueSeparator("=");
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code
* ClassCastException}.
*/
static <V> V safeGet(Map<?, V> map, Object key) {
try {
return map.get(key);
} catch (ClassCastException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code
* ClassCastException}
*/
static boolean safeContainsKey(Map<?, ?> map, Object key) {
try {
return map.containsKey(key);
} catch (ClassCastException e) {
return false;
}
}
/**
* Implements {@code Collection.contains} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is the backing (delegate) collection, rather than
* the forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object that might be contained in {@code c}
* @return {@code true} if {@code c} contains {@code o}
*/
static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.contains(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* Implements {@code Collection.remove} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is backing (delegate) collection, rather than the
* forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object to remove from {@code c}
* @return {@code true} if {@code c} was changed
*/
static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.remove(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* An implementation of {@link Map#equals}.
*/
static boolean equalsImpl(Map<?, ?> map, Object object) {
if (map == object) {
return true;
}
if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
/**
* An implementation of {@link Map#hashCode}.
*/
static int hashCodeImpl(Map<?, ?> map) {
return Sets.hashCodeImpl(map.entrySet());
}
/**
* An implementation of {@link Map#toString}.
*/
static String toStringImpl(Map<?, ?> map) {
StringBuilder sb
= Collections2.newStringBuilderForCollection(map.size()).append('{');
STANDARD_JOINER.appendTo(sb, map);
return sb.append('}').toString();
}
/**
* An implementation of {@link Map#putAll}.
*/
static <K, V> void putAllImpl(
Map<K, V> self, Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
self.put(entry.getKey(), entry.getValue());
}
}
/**
* An admittedly inefficient implementation of {@link Map#containsKey}.
*/
static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) {
for (Entry<?, ?> entry : map.entrySet()) {
if (Objects.equal(entry.getKey(), key)) {
return true;
}
}
return false;
}
/**
* An implementation of {@link Map#containsValue}.
*/
static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) {
for (Entry<?, ?> entry : map.entrySet()) {
if (Objects.equal(entry.getValue(), value)) {
return true;
}
}
return false;
}
abstract static class KeySet<K, V> extends AbstractSet<K> {
abstract Map<K, V> map();
@Override public Iterator<K> iterator() {
return Iterators.transform(map().entrySet().iterator(),
new Function<Map.Entry<K, V>, K>() {
@Override public K apply(Entry<K, V> entry) {
return entry.getKey();
}
});
}
@Override public int size() {
return map().size();
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean contains(Object o) {
return map().containsKey(o);
}
@Override public boolean remove(Object o) {
if (contains(o)) {
map().remove(o);
return true;
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
// TODO(user): find out why this is necessary to make GWT tests pass.
return super.removeAll(checkNotNull(c));
}
@Override public void clear() {
map().clear();
}
}
@Nullable
static <K> K keyOrNull(@Nullable Entry<K, ?> entry) {
return (entry == null) ? null : entry.getKey();
}
@GwtIncompatible("NavigableMap")
abstract static class NavigableKeySet<K, V> extends KeySet<K, V> implements NavigableSet<K> {
@Override
abstract NavigableMap<K, V> map();
@Override
public Comparator<? super K> comparator() {
return map().comparator();
}
@Override
public K first() {
return map().firstKey();
}
@Override
public K last() {
return map().lastKey();
}
@Override
public K lower(K e) {
return map().lowerKey(e);
}
@Override
public K floor(K e) {
return map().floorKey(e);
}
@Override
public K ceiling(K e) {
return map().ceilingKey(e);
}
@Override
public K higher(K e) {
return map().higherKey(e);
}
@Override
public K pollFirst() {
return keyOrNull(map().pollFirstEntry());
}
@Override
public K pollLast() {
return keyOrNull(map().pollLastEntry());
}
@Override
public NavigableSet<K> descendingSet() {
return map().descendingKeySet();
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> subSet(
K fromElement,
boolean fromInclusive,
K toElement,
boolean toInclusive) {
return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet();
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return map().headMap(toElement, inclusive).navigableKeySet();
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return map().tailMap(fromElement, inclusive).navigableKeySet();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public SortedSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
}
abstract static class Values<K, V> extends AbstractCollection<V> {
abstract Map<K, V> map();
@Override public Iterator<V> iterator() {
return Iterators.transform(map().entrySet().iterator(),
new Function<Entry<K, V>, V>() {
@Override public V apply(Entry<K, V> entry) {
return entry.getValue();
}
});
}
@Override public boolean remove(Object o) {
try {
return super.remove(o);
} catch (UnsupportedOperationException e) {
for (Entry<K, V> entry : map().entrySet()) {
if (Objects.equal(o, entry.getValue())) {
map().remove(entry.getKey());
return true;
}
}
return false;
}
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRemove = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRemove.add(entry.getKey());
}
}
return map().keySet().removeAll(toRemove);
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRetain = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRetain.add(entry.getKey());
}
}
return map().keySet().retainAll(toRetain);
}
}
@Override public int size() {
return map().size();
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean contains(@Nullable Object o) {
return map().containsValue(o);
}
@Override public void clear() {
map().clear();
}
}
abstract static class EntrySet<K, V> extends AbstractSet<Entry<K, V>> {
abstract Map<K, V> map();
@Override public int size() {
return map().size();
}
@Override public void clear() {
map().clear();
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
V value = map().get(key);
return Objects.equal(value, entry.getValue())
&& (value != null || map().containsKey(key));
}
return false;
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return map().keySet().remove(entry.getKey());
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
boolean changed = true;
for (Object o : c) {
changed |= remove(o);
}
return changed;
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size());
for (Object o : c) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
keys.add(entry.getKey());
}
}
return map().keySet().retainAll(keys);
}
}
}
@GwtIncompatible("NavigableMap")
static abstract class DescendingMap<K, V> extends ForwardingMap<K, V>
implements NavigableMap<K, V> {
abstract NavigableMap<K, V> forward();
@Override
protected final Map<K, V> delegate() {
return forward();
}
private transient Comparator<? super K> comparator;
@SuppressWarnings("unchecked")
@Override
public Comparator<? super K> comparator() {
Comparator<? super K> result = comparator;
if (result == null) {
Comparator<? super K> forwardCmp = forward().comparator();
if (forwardCmp == null) {
forwardCmp = (Comparator) Ordering.natural();
}
result = comparator = reverse(forwardCmp);
}
return result;
}
// If we inline this, we get a javac error.
private static <T> Ordering<T> reverse(Comparator<T> forward) {
return Ordering.from(forward).reverse();
}
@Override
public K firstKey() {
return forward().lastKey();
}
@Override
public K lastKey() {
return forward().firstKey();
}
@Override
public Entry<K, V> lowerEntry(K key) {
return forward().higherEntry(key);
}
@Override
public K lowerKey(K key) {
return forward().higherKey(key);
}
@Override
public Entry<K, V> floorEntry(K key) {
return forward().ceilingEntry(key);
}
@Override
public K floorKey(K key) {
return forward().ceilingKey(key);
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return forward().floorEntry(key);
}
@Override
public K ceilingKey(K key) {
return forward().floorKey(key);
}
@Override
public Entry<K, V> higherEntry(K key) {
return forward().lowerEntry(key);
}
@Override
public K higherKey(K key) {
return forward().lowerKey(key);
}
@Override
public Entry<K, V> firstEntry() {
return forward().lastEntry();
}
@Override
public Entry<K, V> lastEntry() {
return forward().firstEntry();
}
@Override
public Entry<K, V> pollFirstEntry() {
return forward().pollLastEntry();
}
@Override
public Entry<K, V> pollLastEntry() {
return forward().pollFirstEntry();
}
@Override
public NavigableMap<K, V> descendingMap() {
return forward();
}
private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
abstract Iterator<Entry<K, V>> entryIterator();
Set<Entry<K, V>> createEntrySet() {
return new EntrySet<K, V>() {
@Override
Map<K, V> map() {
return DescendingMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entryIterator();
}
};
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
private transient NavigableSet<K> navigableKeySet;
@Override
public NavigableSet<K> navigableKeySet() {
NavigableSet<K> result = navigableKeySet;
if (result == null) {
result = navigableKeySet = new NavigableKeySet<K, V>() {
@Override
NavigableMap<K, V> map() {
return DescendingMap.this;
}
};
}
return result;
}
@Override
public NavigableSet<K> descendingKeySet() {
return forward().navigableKeySet();
}
@Override
public
NavigableMap<K, V>
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap();
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return forward().tailMap(toKey, inclusive).descendingMap();
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return forward().headMap(fromKey, inclusive).descendingMap();
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public Collection<V> values() {
return new Values<K, V>() {
@Override
Map<K, V> map() {
return DescendingMap.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.Collections;
import java.util.List;
/** An ordering that uses the natural order of the values. */
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this??
final class NaturalOrdering
extends Ordering<Comparable> implements Serializable {
static final NaturalOrdering INSTANCE = new NaturalOrdering();
@Override public int compare(Comparable left, Comparable right) {
checkNotNull(left); // for GWT
checkNotNull(right);
if (left == right) {
return 0;
}
return left.compareTo(right);
}
@Override public <S extends Comparable> Ordering<S> reverse() {
return (Ordering<S>) ReverseNaturalOrdering.INSTANCE;
}
// Override to remove a level of indirection from inner loop
@Override public int binarySearch(
List<? extends Comparable> sortedList, Comparable key) {
return Collections.binarySearch((List) sortedList, key);
}
// Override to remove a level of indirection from inner loop
@Override public <E extends Comparable> List<E> sortedCopy(
Iterable<E> iterable) {
List<E> list = Lists.newArrayList(iterable);
Collections.sort(list);
return list;
}
// preserving singleton-ness gives equals()/hashCode() for free
private Object readResolve() {
return INSTANCE;
}
@Override public String toString() {
return "Ordering.natural()";
}
private NaturalOrdering() {}
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 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) 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.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A collection that supports order-independent equality, like {@link Set}, but
* may have duplicate elements. A multiset is also sometimes called a
* <i>bag</i>.
*
* <p>Elements of a multiset that are equal to one another are referred to as
* <i>occurrences</i> of the same single element. The total number of
* occurrences of an element in a multiset is called the <i>count</i> of that
* element (the terms "frequency" and "multiplicity" are equivalent, but not
* used in this API). Since the count of an element is represented as an {@code
* int}, a multiset may never contain more than {@link Integer#MAX_VALUE}
* occurrences of any one element.
*
* <p>{@code Multiset} refines the specifications of several methods from
* {@code Collection}. It also defines an additional query operation, {@link
* #count}, which returns the count of an element. There are five new
* bulk-modification operations, for example {@link #add(Object, int)}, to add
* or remove multiple occurrences of an element at once, or to set the count of
* an element to a specific value. These modification operations are optional,
* but implementations which support the standard collection operations {@link
* #add(Object)} or {@link #remove(Object)} are encouraged to implement the
* related methods as well. Finally, two collection views are provided: {@link
* #elementSet} contains the distinct elements of the multiset "with duplicates
* collapsed", and {@link #entrySet} is similar but contains {@link Entry
* Multiset.Entry} instances, each providing both a distinct element and the
* count of that element.
*
* <p>In addition to these required methods, implementations of {@code
* Multiset} are expected to provide two {@code static} creation methods:
* {@code create()}, returning an empty multiset, and {@code
* create(Iterable<? extends E>)}, returning a multiset containing the
* given initial elements. This is simply a refinement of {@code Collection}'s
* constructor recommendations, reflecting the new developments of Java 5.
*
* <p>As with other collection types, the modification operations are optional,
* and should throw {@link UnsupportedOperationException} when they are not
* implemented. Most implementations should support either all add operations
* or none of them, all removal operations or none of them, and if and only if
* all of these are supported, the {@code setCount} methods as well.
*
* <p>A multiset uses {@link Object#equals} to determine whether two instances
* should be considered "the same," <i>unless specified otherwise</i> by the
* implementation.
*
* <p>Common implementations include {@link ImmutableMultiset}, {@link
* HashMultiset}, and {@link ConcurrentHashMultiset}.
*
* <p>If your values may be zero, negative, or outside the range of an int, you
* may wish to use {@link com.google.common.util.concurrent.AtomicLongMap}
* instead. Note, however, that unlike {@code Multiset}, {@code AtomicLongMap}
* does not automatically remove zeros.
*
* <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
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface Multiset<E> extends Collection<E> {
// Query Operations
/**
* Returns the number of occurrences of an element in this multiset (the
* <i>count</i> of the element). Note that for an {@link Object#equals}-based
* multiset, this gives the same result as {@link Collections#frequency}
* (which would presumably perform more poorly).
*
* <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes
* this operation; it correctly delegates to this method when dealing with a
* multiset, but it can also accept any other iterable type.
*
* @param element the element to count occurrences of
* @return the number of occurrences of the element in this multiset; possibly
* zero but never negative
*/
int count(@Nullable Object element);
// Bulk Operations
/**
* Adds a number of occurrences of an element to this multiset. Note that if
* {@code occurrences == 1}, this method has the identical effect to {@link
* #add(Object)}. This method is functionally equivalent (except in the case
* of overflow) to the call {@code addAll(Collections.nCopies(element,
* occurrences))}, which would presumably perform much more poorly.
*
* @param element the element to add occurrences of; may be null only if
* explicitly allowed by the implementation
* @param occurrences the number of occurrences of the element to add. May be
* zero, in which case no change will be made.
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative, or if
* this operation would result in more than {@link Integer#MAX_VALUE}
* occurrences of the element
* @throws NullPointerException if {@code element} is null and this
* implementation does not permit null elements. Note that if {@code
* occurrences} is zero, the implementation may opt to return normally.
*/
int add(@Nullable E element, int occurrences);
/**
* 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. Note that if
* {@code occurrences == 1}, this is functionally equivalent to the call
* {@code remove(element)}.
*
* @param element the element to conditionally remove occurrences of
* @param occurrences the number of occurrences of the element to remove. May
* be zero, in which case no change will be made.
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
int remove(@Nullable Object element, int occurrences);
/**
* Adds or removes the necessary occurrences of an element such that the
* element attains the desired count.
*
* @param element the element to add or remove occurrences of; may be null
* only if explicitly allowed by the implementation
* @param count the desired count of the element in this multiset
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code count} is negative
* @throws NullPointerException if {@code element} is null and this
* implementation does not permit null elements. Note that if {@code
* count} is zero, the implementor may optionally return zero instead.
*/
int setCount(E element, int count);
/**
* Conditionally sets the count of an element to a new value, as described in
* {@link #setCount(Object, int)}, provided that the element has the expected
* current count. If the current count is not {@code oldCount}, no change is
* made.
*
* @param element the element to conditionally set the count of; may be null
* only if explicitly allowed by the implementation
* @param oldCount the expected present count of the element in this multiset
* @param newCount the desired count of the element in this multiset
* @return {@code true} if the condition for modification was met. This
* implies that the multiset was indeed modified, unless
* {@code oldCount == newCount}.
* @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is
* negative
* @throws NullPointerException if {@code element} is null and the
* implementation does not permit null elements. Note that if {@code
* oldCount} and {@code newCount} are both zero, the implementor may
* optionally return {@code true} instead.
*/
boolean setCount(E element, int oldCount, int newCount);
// Views
/**
* Returns the set of distinct elements contained in this multiset. The
* element set is backed by the same data as the multiset, so any change to
* either is immediately reflected in the other. The order of the elements in
* the element set is unspecified.
*
* <p>If the element set supports any removal operations, these necessarily
* cause <b>all</b> occurrences of the removed element(s) to be removed from
* the multiset. Implementations are not expected to support the add
* operations, although this is possible.
*
* <p>A common use for the element set is to find the number of distinct
* elements in the multiset: {@code elementSet().size()}.
*
* @return a view of the set of distinct elements in this multiset
*/
Set<E> elementSet();
/**
* Returns a view of the contents of this multiset, grouped into {@code
* Multiset.Entry} instances, each providing an element of the multiset and
* the count of that element. This set contains exactly one entry for each
* distinct element in the multiset (thus it always has the same size as the
* {@link #elementSet}). The order of the elements in the element set is
* unspecified.
*
* <p>The entry set is backed by the same data as the multiset, so any change
* to either is immediately reflected in the other. However, multiset changes
* may or may not be reflected in any {@code Entry} instances already
* retrieved from the entry set (this is implementation-dependent).
* Furthermore, implementations are not required to support modifications to
* the entry set at all, and the {@code Entry} instances themselves don't
* even have methods for modification. See the specific implementation class
* for more details on how its entry set handles modifications.
*
* @return a set of entries representing the data of this multiset
*/
Set<Entry<E>> entrySet();
/**
* An unmodifiable element-count pair for a multiset. The {@link
* Multiset#entrySet} method returns a view of the multiset whose elements
* are of this class. A multiset implementation may return Entry instances
* that are either live "read-through" views to the Multiset, or immutable
* snapshots. Note that this type is unrelated to the similarly-named type
* {@code Map.Entry}.
*
* @since 2.0 (imported from Google Collections Library)
*/
interface Entry<E> {
/**
* Returns the multiset element corresponding to this entry. Multiple calls
* to this method always return the same instance.
*
* @return the element corresponding to this entry
*/
E getElement();
/**
* Returns the count of the associated element in the underlying multiset.
* This count may either be an unchanging snapshot of the count at the time
* the entry was retrieved, or a live view of the current count of the
* element in the multiset, depending on the implementation. Note that in
* the former case, this method can never return zero, while in the latter,
* it will return zero if all occurrences of the element were since removed
* from the multiset.
*
* @return the count of the element; never negative
*/
int getCount();
/**
* {@inheritDoc}
*
* <p>Returns {@code true} if the given object is also a multiset entry and
* the two entries represent the same element and count. That is, two
* entries {@code a} and {@code b} are equal if: <pre> {@code
*
* Objects.equal(a.getElement(), b.getElement())
* && a.getCount() == b.getCount()}</pre>
*/
@Override
// TODO(kevinb): check this wrt TreeMultiset?
boolean equals(Object o);
/**
* {@inheritDoc}
*
* <p>The hash code of a multiset entry for element {@code element} and
* count {@code count} is defined as: <pre> {@code
*
* ((element == null) ? 0 : element.hashCode()) ^ count}</pre>
*/
@Override
int hashCode();
/**
* Returns the canonical string representation of this entry, defined as
* follows. If the count for this entry is one, this is simply the string
* representation of the corresponding element. Otherwise, it is the string
* representation of the element, followed by the three characters {@code
* " x "} (space, letter x, space), followed by the count.
*/
@Override
String toString();
}
// Comparison and hashing
/**
* Compares the specified object with this multiset for equality. Returns
* {@code true} if the given object is also a multiset and contains equal
* elements with equal counts, regardless of order.
*/
@Override
// TODO(kevinb): caveats about equivalence-relation?
boolean equals(@Nullable Object object);
/**
* Returns the hash code for this multiset. This is defined as the sum of
* <pre> {@code
*
* ((element == null) ? 0 : element.hashCode()) ^ count(element)}</pre>
*
* over all distinct elements in the multiset. It follows that a multiset and
* its entry set always have the same hash code.
*/
@Override
int hashCode();
/**
* {@inheritDoc}
*
* <p>It is recommended, though not mandatory, that this method return the
* result of invoking {@link #toString} on the {@link #entrySet}, yielding a
* result such as {@code [a x 3, c, d x 2, e]}.
*/
@Override
String toString();
// Refined Collection Methods
/**
* {@inheritDoc}
*
* <p>Elements that occur multiple times in the multiset will appear
* multiple times in this iterator, though not necessarily sequentially.
*/
@Override
Iterator<E> iterator();
/**
* Determines whether this multiset contains the specified element.
*
* <p>This method refines {@link Collection#contains} to further specify that
* it <b>may not</b> throw an exception in response to {@code element} being
* null or of the wrong type.
*
* @param element the element to check for
* @return {@code true} if this multiset contains at least one occurrence of
* the element
*/
@Override
boolean contains(@Nullable Object element);
/**
* Returns {@code true} if this multiset contains at least one occurrence of
* each element in the specified collection.
*
* <p>This method refines {@link Collection#containsAll} to further specify
* that it <b>may not</b> throw an exception in response to any of {@code
* elements} being null or of the wrong type.
*
* <p><b>Note:</b> this method does not take into account the occurrence
* count of an element in the two collections; it may still return {@code
* true} even if {@code elements} contains several occurrences of an element
* and this multiset contains only one. This is no different than any other
* collection type like {@link List}, but it may be unexpected to the user of
* a multiset.
*
* @param elements the collection of elements to be checked for containment in
* this multiset
* @return {@code true} if this multiset contains at least one occurrence of
* each element contained in {@code elements}
* @throws NullPointerException if {@code elements} is null
*/
@Override
boolean containsAll(Collection<?> elements);
/**
* Adds a single occurrence of the specified element to this multiset.
*
* <p>This method refines {@link Collection#add}, which only <i>ensures</i>
* the presence of the element, to further specify that a successful call must
* always increment the count of the element, and the overall size of the
* collection, by one.
*
* @param element the element to add one occurrence of; may be null only if
* explicitly allowed by the implementation
* @return {@code true} always, since this call is required to modify the
* multiset, unlike other {@link Collection} types
* @throws NullPointerException if {@code element} is null and this
* implementation does not permit null elements
* @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences
* of {@code element} are already contained in this multiset
*/
@Override
boolean add(E element);
/**
* Removes a <i>single</i> occurrence of the specified element from this
* multiset, if present.
*
* <p>This method refines {@link Collection#remove} to further specify that it
* <b>may not</b> throw an exception in response to {@code element} being null
* or of the wrong type.
*
* @param element the element to remove one occurrence of
* @return {@code true} if an occurrence was found and removed
*/
@Override
boolean remove(@Nullable Object element);
/**
* {@inheritDoc}
*
* <p><b>Note:</b> This method ignores how often any element might appear in
* {@code c}, and only cares whether or not an element appears at all.
* If you wish to remove one occurrence in this multiset for every occurrence
* in {@code c}, see {@link Multisets#removeOccurrences(Multiset, Multiset)}.
*
* <p>This method refines {@link Collection#removeAll} to further specify that
* it <b>may not</b> throw an exception in response to any of {@code elements}
* being null or of the wrong type.
*/
@Override
boolean removeAll(Collection<?> c);
/**
* {@inheritDoc}
*
* <p><b>Note:</b> This method ignores how often any element might appear in
* {@code c}, and only cares whether or not an element appears at all.
* If you wish to remove one occurrence in this multiset for every occurrence
* in {@code c}, see {@link Multisets#retainOccurrences(Multiset, Multiset)}.
*
* <p>This method refines {@link Collection#retainAll} to further specify that
* it <b>may not</b> throw an exception in response to any of {@code elements}
* being null or of the wrong type.
*
* @see Multisets#retainOccurrences(Multiset, Multiset)
*/
@Override
boolean retainAll(Collection<?> c);
}
| 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
*/
@Override
public <T extends B> T putInstance(Class<T> type, T value) {
throw new UnsupportedOperationException();
}
}
| 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.util.Collection;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to object arrays.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class ObjectArrays {
private ObjectArrays() {}
/**
* Returns a new array of the given length with the specified component type.
*
* @param type the component type
* @param length the length of the new array
*/
@GwtIncompatible("Array.newInstance(Class, int)")
public static <T> T[] newArray(Class<T> type, int length) {
return Platform.newArray(type, length);
}
/**
* 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
*/
public static <T> T[] newArray(T[] reference, int length) {
return Platform.newArray(reference, length);
}
/**
* Returns a new array that contains the concatenated contents of two arrays.
*
* @param first the first array of elements to concatenate
* @param second the second array of elements to concatenate
* @param type the component type of the returned array
*/
@GwtIncompatible("Array.newInstance(Class, int)")
public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
T[] result = newArray(type, first.length + second.length);
Platform.unsafeArrayCopy(first, 0, result, 0, first.length);
Platform.unsafeArrayCopy(second, 0, result, first.length, second.length);
return result;
}
/**
* Returns a new array that prepends {@code element} to {@code array}.
*
* @param element the element to prepend to the front of {@code array}
* @param array the array of elements to append
* @return an array whose size is one larger than {@code array}, with
* {@code element} occupying the first position, and the
* elements of {@code array} occupying the remaining elements.
*/
public static <T> T[] concat(@Nullable T element, T[] array) {
T[] result = newArray(array, array.length + 1);
result[0] = element;
Platform.unsafeArrayCopy(array, 0, result, 1, array.length);
return result;
}
/**
* Returns a new array that appends {@code element} to {@code array}.
*
* @param array the array of elements to prepend
* @param element the element to append to the end
* @return an array whose size is one larger than {@code array}, with
* the same contents as {@code array}, plus {@code element} occupying the
* last position.
*/
public static <T> T[] concat(T[] array, @Nullable T element) {
T[] result = arraysCopyOf(array, array.length + 1);
result[array.length] = element;
return result;
}
/** GWT safe version of Arrays.copyOf. */
static <T> T[] arraysCopyOf(T[] original, int newLength) {
T[] copy = newArray(original, newLength);
Platform.unsafeArrayCopy(
original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
/**
* Returns an array containing all of the elements in the specified
* collection; the runtime type of the returned array is that of the specified
* array. If the collection fits in the specified array, it is returned
* therein. Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of the specified collection.
*
* <p>If the collection fits in the specified array with room to spare (i.e.,
* the array has more elements than the collection), the element in the array
* immediately following the end of the collection is set to {@code null}.
* This is useful in determining the length of the collection <i>only</i> if
* the caller knows that the collection does not contain any null elements.
*
* <p>This method returns the elements in the order they are returned by the
* collection's iterator.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
* @param array the array in which to place the collection elements
* @throws ArrayStoreException if the runtime type of the specified array is
* not a supertype of the runtime type of every element in the specified
* collection
*/
static <T> T[] toArrayImpl(Collection<?> c, T[] array) {
int size = c.size();
if (array.length < size) {
array = newArray(array, size);
}
fillArray(c, array);
if (array.length > size) {
array[size] = null;
}
return array;
}
/**
* Returns an array containing all of the elements in the specified
* collection. This method returns the elements in the order they are returned
* by the collection's iterator. The returned array is "safe" in that no
* references to it are maintained by the collection. The caller is thus free
* to modify the returned array.
*
* <p>This method assumes that the collection size doesn't change while the
* method is running.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
*/
static Object[] toArrayImpl(Collection<?> c) {
return fillArray(c, new Object[c.size()]);
}
private static Object[] fillArray(Iterable<?> elements, Object[] array) {
int i = 0;
for (Object element : elements) {
array[i++] = element;
}
return array;
}
/**
* Swaps {@code array[i]} with {@code array[j]}.
*/
static void swap(Object[] array, int i, int j) {
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
| 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.Preconditions;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* A high-performance, immutable, random-access {@code List} implementation.
* Does not permit null elements.
*
* <p>Unlike {@link Collections#unmodifiableList}, which is a <i>view</i> of a
* separate collection that can still change, an instance of {@code
* ImmutableList} contains its own private data and will <i>never</i> change.
* {@code ImmutableList} is convenient for {@code public static final} lists
* ("constant lists") and also lets you easily make a "defensive copy" of a list
* 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 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 ImmutableMap
* @see ImmutableSet
* @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 ImmutableList<E> extends ImmutableCollection<E>
implements List<E>, RandomAccess {
/**
* Returns the empty immutable list. This set behaves and performs comparably
* to {@link Collections#emptyList}, and is preferable mainly for consistency
* and maintainability of your code.
*/
// Casting to any type is safe because the list will never hold any elements.
@SuppressWarnings("unchecked")
public static <E> ImmutableList<E> of() {
return (ImmutableList<E>) EmptyImmutableList.INSTANCE;
}
/**
* Returns an immutable list containing a single element. This list 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.
*
* @throws NullPointerException if {@code element} is null
*/
public static <E> ImmutableList<E> of(E element) {
return new SingletonImmutableList<E>(element);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2) {
return construct(e1, e2);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
return construct(e1, e2, e3);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
return construct(e1, e2, e3, e4);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
return construct(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
return construct(e1, e2, e3, e4, e5, e6);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
return construct(e1, e2, e3, e4, e5, e6, e7);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
}
// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12,
E... others) {
Object[] array = new Object[12 + others.length];
array[0] = e1;
array[1] = e2;
array[2] = e3;
array[3] = e4;
array[4] = e5;
array[5] = e6;
array[6] = e7;
array[7] = e8;
array[8] = e9;
array[9] = e10;
array[10] = e11;
array[11] = e12;
System.arraycopy(others, 0, array, 12, others.length);
return construct(array);
}
/**
* Returns an immutable list containing the given elements, in order. If
* {@code elements} is a {@link Collection}, this method behaves exactly as
* {@link #copyOf(Collection)}; otherwise, it behaves exactly as {@code
* copyOf(elements.iterator()}.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
return (elements instanceof Collection)
? copyOf(Collections2.cast(elements))
: copyOf(elements.iterator());
}
/**
* Returns an immutable list containing the given elements, in order.
*
* <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.
*
* <p>Note that if {@code list} is a {@code List<String>}, then {@code
* ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>}
* containing each of the strings in {@code list}, while
* ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>}
* containing one element (the given list itself).
*
* <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
*/
public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
if (elements instanceof ImmutableCollection) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
return list.isPartialView() ? copyFromCollection(list) : list;
}
return copyFromCollection(elements);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
return copyFromCollection(Lists.newArrayList(elements));
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E> ImmutableList<E> copyOf(E[] elements) {
switch (elements.length) {
case 0:
return ImmutableList.of();
case 1:
return new SingletonImmutableList<E>(elements[0]);
default:
return construct(elements.clone());
}
}
private static <E> ImmutableList<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
ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
return list;
default:
// safe to use the array without copying it
// as specified by Collection.toArray().
return construct(elements);
}
}
/** {@code elements} has to be internally created array. */
private static <E> ImmutableList<E> construct(Object... elements) {
for (int i = 0; i < elements.length; i++) {
checkElementNotNull(elements[i], i);
}
return new RegularImmutableList<E>(elements);
}
// We do this instead of Preconditions.checkNotNull to save boxing and array
// creation cost.
private static Object checkElementNotNull(Object element, int index) {
if (element == null) {
throw new NullPointerException("at index " + index);
}
return element;
}
ImmutableList() {}
// This declaration is needed to make List.iterator() and
// ImmutableCollection.iterator() consistent.
@Override public UnmodifiableIterator<E> iterator() {
return listIterator();
}
@Override public UnmodifiableListIterator<E> listIterator() {
return listIterator(0);
}
@Override public abstract UnmodifiableListIterator<E> listIterator(int index);
// Mark these two methods with @Nullable
@Override
public abstract int indexOf(@Nullable Object object);
@Override
public abstract int lastIndexOf(@Nullable Object object);
// constrain the return type to ImmutableList<E>
/**
* Returns an immutable list of the elements between the specified {@code
* fromIndex}, inclusive, and {@code toIndex}, exclusive. (If {@code
* fromIndex} and {@code toIndex} are equal, the empty immutable list is
* returned.)
*/
@Override
public abstract ImmutableList<E> subList(int fromIndex, int toIndex);
/**
* Guaranteed to throw an exception and leave the list unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final boolean addAll(int index, Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the list unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final E set(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the list unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final void add(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the list unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final E remove(int index) {
throw new UnsupportedOperationException();
}
/**
* Returns this list instance.
*
* @since 2.0
*/
@Override public ImmutableList<E> asList() {
return this;
}
/**
* Returns a view of this immutable list in reverse order. For example, {@code
* ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code
* ImmutableList.of(3, 2, 1)}.
*
* @return a view of this immutable list in reverse order
* @since 7.0
*/
public ImmutableList<E> reverse() {
return new ReverseImmutableList<E>(this);
}
private static class ReverseImmutableList<E> extends ImmutableList<E> {
private transient final ImmutableList<E> forwardList;
private transient final int size;
ReverseImmutableList(ImmutableList<E> backingList) {
this.forwardList = backingList;
this.size = backingList.size();
}
private int reverseIndex(int index) {
return (size - 1) - index;
}
private int reversePosition(int index) {
return size - index;
}
@Override public ImmutableList<E> reverse() {
return forwardList;
}
@Override public boolean contains(@Nullable Object object) {
return forwardList.contains(object);
}
@Override public boolean containsAll(Collection<?> targets) {
return forwardList.containsAll(targets);
}
@Override public int indexOf(@Nullable Object object) {
int index = forwardList.lastIndexOf(object);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public int lastIndexOf(@Nullable Object object) {
int index = forwardList.indexOf(object);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
Preconditions.checkPositionIndexes(fromIndex, toIndex, size);
return forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)).reverse();
}
@Override public E get(int index) {
Preconditions.checkElementIndex(index, size);
return forwardList.get(reverseIndex(index));
}
@Override public UnmodifiableListIterator<E> listIterator(int index) {
Preconditions.checkPositionIndex(index, size);
final UnmodifiableListIterator<E> forward =
forwardList.listIterator(reversePosition(index));
return new UnmodifiableListIterator<E>() {
@Override public boolean hasNext() {
return forward.hasPrevious();
}
@Override public boolean hasPrevious() {
return forward.hasNext();
}
@Override public E next() {
return forward.previous();
}
@Override public int nextIndex() {
return reverseIndex(forward.previousIndex());
}
@Override public E previous() {
return forward.next();
}
@Override public int previousIndex() {
return reverseIndex(forward.nextIndex());
}
};
}
@Override public int size() {
return size;
}
@Override public boolean isEmpty() {
return forwardList.isEmpty();
}
@Override boolean isPartialView() {
return forwardList.isPartialView();
}
}
@Override public boolean equals(Object obj) {
return Lists.equalsImpl(this, obj);
}
@Override public int hashCode() {
return Lists.hashCodeImpl(this);
}
/*
* Serializes ImmutableLists 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 copyOf(elements);
}
private static final long serialVersionUID = 0;
}
private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@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 list instances, especially {@code public
* static final} lists ("constant lists"). Example: <pre> {@code
*
* public static final ImmutableList<Color> GOOGLE_COLORS
* = new ImmutableList.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 lists in series. Each new list contains all the
* elements of the ones created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<E> extends ImmutableCollection.Builder<E> {
private final ArrayList<E> contents = Lists.newArrayList();
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableList#builder}.
*/
public Builder() {}
/**
* Adds {@code element} to the {@code ImmutableList}.
*
* @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) {
contents.add(checkNotNull(element));
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableList}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableList}
* @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;
contents.ensureCapacity(contents.size() + collection.size());
}
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableList}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableList}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> add(E... elements) {
contents.ensureCapacity(contents.size() + elements.length);
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableList}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableList}
* @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 ImmutableList} based on the contents of
* the {@code Builder}.
*/
@Override public ImmutableList<E> build() {
return copyOf(contents);
}
}
}
| 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) 2009 Google Inc.
*
* 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 gak@google.com (Gregory Kick)
*/
@GwtCompatible
abstract class RegularImmutableTable<R, C, V> extends ImmutableTable<R, C, V> {
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);
}
}
/**
* A {@code RegularImmutableTable} optimized for dense data.
*/
@Immutable @VisibleForTesting
static final class DenseImmutableTable<R, C, V>
extends RegularImmutableTable<R, C, V> {
private final ImmutableBiMap<R, Integer> rowKeyToIndex;
private final ImmutableBiMap<C, Integer> columnKeyToIndex;
private final V[][] values;
private static <E> ImmutableBiMap<E, Integer> makeIndex(
ImmutableSet<E> set) {
ImmutableBiMap.Builder<E, Integer> indexBuilder =
ImmutableBiMap.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);
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();
}
}
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
Integer columnIndexInteger = columnKeyToIndex.get(columnKey);
if (columnIndexInteger == null) {
return ImmutableMap.of();
} else {
// unbox only once
int columnIndex = columnIndexInteger;
ImmutableMap.Builder<R, V> columnBuilder = ImmutableMap.builder();
for (int i = 0; i < values.length; i++) {
V value = values[i][columnIndex];
if (value != null) {
columnBuilder.put(rowKeyToIndex.inverse().get(i), value);
}
}
return columnBuilder.build();
}
}
@Override public ImmutableSet<C> columnKeySet() {
return columnKeyToIndex.keySet();
}
private transient volatile ImmutableMap<C, Map<R, V>> columnMap;
private ImmutableMap<C, Map<R, V>> makeColumnMap() {
ImmutableMap.Builder<C, Map<R, V>> columnMapBuilder =
ImmutableMap.builder();
for (int c = 0; c < columnKeyToIndex.size(); c++) {
ImmutableMap.Builder<R, V> rowMapBuilder = ImmutableMap.builder();
for (int r = 0; r < rowKeyToIndex.size(); r++) {
V value = values[r][c];
if (value != null) {
rowMapBuilder.put(rowKeyToIndex.inverse().get(r), value);
}
}
columnMapBuilder.put(columnKeyToIndex.inverse().get(c),
rowMapBuilder.build());
}
return columnMapBuilder.build();
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
ImmutableMap<C, Map<R, V>> result = columnMap;
if (result == null) {
columnMap = result = makeColumnMap();
}
return result;
}
@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 {
ImmutableMap.Builder<C, V> rowBuilder = ImmutableMap.builder();
V[] row = values[rowIndex];
for (int r = 0; r < row.length; r++) {
V value = row[r];
if (value != null) {
rowBuilder.put(columnKeyToIndex.inverse().get(r), value);
}
}
return rowBuilder.build();
}
}
@Override public ImmutableSet<R> rowKeySet() {
return rowKeyToIndex.keySet();
}
private transient volatile ImmutableMap<R, Map<C, V>> rowMap;
private ImmutableMap<R, Map<C, V>> makeRowMap() {
ImmutableMap.Builder<R, Map<C, V>> rowMapBuilder = ImmutableMap.builder();
for (int r = 0; r < values.length; r++) {
V[] row = values[r];
ImmutableMap.Builder<C, V> columnMapBuilder = ImmutableMap.builder();
for (int c = 0; c < row.length; c++) {
V value = row[c];
if (value != null) {
columnMapBuilder.put(columnKeyToIndex.inverse().get(c), value);
}
}
rowMapBuilder.put(rowKeyToIndex.inverse().get(r),
columnMapBuilder.build());
}
return rowMapBuilder.build();
}
@Override public ImmutableMap<R, Map<C, V>> rowMap() {
ImmutableMap<R, Map<C, V>> result = rowMap;
if (result == null) {
rowMap = result = makeRowMap();
}
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 static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Ranges.create;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Predicate;
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A range, sometimes known as an <i>interval</i>, is a <i>convex</i>
* (informally, "contiguous" or "unbroken") portion of a particular domain.
* Formally, convexity means that for any {@code a <= b <= c},
* {@code range.contains(a) && range.contains(c)} implies that {@code
* range.contains(b)}.
*
* <p>A range is characterized by its lower and upper <i>bounds</i> (extremes),
* each of which can <i>open</i> (exclusive of its endpoint), <i>closed</i>
* (inclusive of its endpoint), or <i>unbounded</i>. This yields nine basic
* types of ranges:
*
* <ul>
* <li>{@code (a..b) = {x | a < x < b}}
* <li>{@code [a..b] = {x | a <= x <= b}}
* <li>{@code [a..b) = {x | a <= x < b}}
* <li>{@code (a..b] = {x | a < x <= b}}
* <li>{@code (a..+∞) = {x | x > a}}
* <li>{@code [a..+∞) = {x | x >= a}}
* <li>{@code (-∞..b) = {x | x < b}}
* <li>{@code (-∞..b] = {x | x <= b}}
* <li>{@code (-∞..+∞) = all values}
* </ul>
*
* (The notation {@code {x | statement}} is read "the set of all <i>x</i> such
* that <i>statement</i>.")
*
* <p>Notice that we use a square bracket ({@code [ ]}) to denote that an range
* is closed on that end, and a parenthesis ({@code ( )}) when it is open or
* unbounded.
*
* <p>The values {@code a} and {@code b} used above are called <i>endpoints</i>.
* The upper endpoint may not be less than the lower endpoint. The endpoints may
* be equal only if at least one of the bounds is closed:
*
* <ul>
* <li>{@code [a..a]} : singleton range
* <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty}, but valid
* <li>{@code (a..a)} : <b>invalid</b>
* </ul>
*
* <p>Instances of this type can be obtained using the static factory methods in
* the {@link Ranges} class.
*
* <p>Instances of {@code Range} are immutable. It is strongly encouraged to
* use this class only with immutable data types. When creating a range over a
* mutable type, take great care not to allow the value objects to mutate after
* the range is created.
*
* <p>In this and other range-related specifications, concepts like "equal",
* "same", "unique" and so on are based on {@link Comparable#compareTo}
* returning zero, not on {@link Object#equals} returning {@code true}. Of
* course, when these methods are kept <i>consistent</i> (as defined in {@link
* Comparable}), this is not an issue.
*
* <p>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}.
*
* <p>This class can be used with any type which implements {@code Comparable};
* it does not require {@code Comparable<? super C>} because this would be
* incompatible with pre-Java 5 types. If this class is used with a perverse
* {@code Comparable} type ({@code Foo implements Comparable<Bar>} where {@code
* Bar} is not a supertype of {@code Foo}), any of its methods may throw {@link
* ClassCastException}. (There is no good reason for such a type to exist.)
*
* <p>When evaluated as a {@link Predicate}, a range yields the same result as
* invoking {@link #contains}.
*
* <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
*/
@GwtCompatible
@Beta
public final class Range<C extends Comparable>
implements Predicate<C>, Serializable {
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>The encloses relation has the following properties:
*
* <ul>
* <li>reflexive: {@code a.encloses(a)} is always true
* <li>antisymmetric: {@code a.encloses(b) && b.encloses(a)} implies {@code
* a.equals(b)}
* <li>transitive: {@code a.encloses(b) && b.encloses(c)} implies {@code
* a.encloses(c)}
* <li>not a total ordering: {@code !a.encloses(b)} does not imply {@code
* b.encloses(a)}
* <li>there exists a {@linkplain Ranges#all maximal} range, for which
* {@code encloses} is always true
* <li>there also exist {@linkplain #isEmpty minimal} ranges, for
* which {@code encloses(b)} is always false when {@code !equals(b)}
* <li>if {@code a.encloses(b)}, then {@link #isConnected a.isConnected(b)}
* is {@code true}.
* </ul>
*/
public boolean encloses(Range<C> other) {
return lowerBound.compareTo(other.lowerBound) <= 0
&& upperBound.compareTo(other.upperBound) >= 0;
}
/**
* Returns the maximal range {@linkplain #encloses enclosed} by both this
* range and {@code other}, 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>Generally, the intersection exists if and only if this range and
* {@code other} are {@linkplain #isConnected connected}.
*
* <p>The intersection operation has the following properties:
*
* <ul>
* <li>commutative: {@code a.intersection(b)} produces the same result as
* {@code b.intersection(a)}
* <li>associative: {@code a.intersection(b).intersection(c)} produces the
* same result as {@code a.intersection(b.intersection(c))}
* <li>idempotent: {@code a.intersection(a)} equals {@code a}
* <li>identity ({@link Ranges#all}): {@code a.intersection(Ranges.all())}
* equals {@code a}
* </ul>
*
* @throws IllegalArgumentException if no range exists that is enclosed by
* both these ranges
*/
public Range<C> intersection(Range<C> other) {
Cut<C> newLower = Ordering.natural().max(lowerBound, other.lowerBound);
Cut<C> newUpper = Ordering.natural().min(upperBound, other.upperBound);
return create(newLower, newUpper);
}
/**
* 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 has the following properties:
*
* <ul>
* <li>symmetric: {@code a.isConnected(b)} produces the same result as
* {@code b.isConnected(a)}
* <li>reflexive: {@code a.isConnected(a)} returns {@code true}
* </ul>
*/
public boolean isConnected(Range<C> other) {
return lowerBound.compareTo(other.upperBound) <= 0
&& other.lowerBound.compareTo(upperBound) <= 0;
}
/**
* 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)}. Note that the span may contain values
* that are not contained by either original range.
*
* <p>The span operation has the following properties:
*
* <ul>
* <li>closed: the range {@code a.span(b)} exists for all ranges {@code a} and
* {@code b}
* <li>commutative: {@code a.span(b)} equals {@code b.span(a)}
* <li>associative: {@code a.span(b).span(c)} equals {@code a.span(b.span(c))}
* <li>idempotent: {@code a.span(a)} equals {@code a}
* </ul>
*
* <p>Note that the returned range is also called the <i>union</i> of this
* range and {@code other} if and only if the ranges are
* {@linkplain #isConnected connected}.
*/
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 ImmutableSortedSet} containing the same values in the
* given domain {@linkplain Range#contains contained} by this range.
*
* <p><b>Note:</b> {@code a.asSet().equals(b.asSet())} 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 Ranges.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 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) {
checkNotNull(domain);
Range<C> effectiveRange = this;
try {
if (!hasLowerBound()) {
effectiveRange = effectiveRange.intersection(
Ranges.atLeast(domain.minValue()));
}
if (!hasUpperBound()) {
effectiveRange = effectiveRange.intersection(
Ranges.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()
|| compareOrThrow(
lowerBound.leastValueAbove(domain),
upperBound.greatestValueBelow(domain)) > 0;
return empty
? new EmptyContiguousSet<C>(domain)
: new RegularContiguousSet<C>(effectiveRange, 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) 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.base.Preconditions;
import java.util.List;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableList} with exactly one element.
*
* @author Hayward Chan
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class SingletonImmutableList<E> extends ImmutableList<E> {
final transient E element;
SingletonImmutableList(E element) {
this.element = checkNotNull(element);
}
@Override
public E get(int index) {
Preconditions.checkElementIndex(index, 1);
return element;
}
@Override public int indexOf(@Nullable Object object) {
return element.equals(object) ? 0 : -1;
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.singletonIterator(element);
}
@Override public int lastIndexOf(@Nullable Object object) {
return element.equals(object) ? 0 : -1;
}
@Override public UnmodifiableListIterator<E> listIterator(final int start) {
Preconditions.checkPositionIndex(start, 1);
return new UnmodifiableListIterator<E>() {
boolean hasNext = start == 0;
@Override public boolean hasNext() {
return hasNext;
}
@Override public boolean hasPrevious() {
return !hasNext;
}
@Override public E next() {
if (!hasNext) {
throw new NoSuchElementException();
}
hasNext = false;
return element;
}
@Override public int nextIndex() {
return hasNext ? 0 : 1;
}
@Override public E previous() {
if (hasNext) {
throw new NoSuchElementException();
}
hasNext = true;
return element;
}
@Override public int previousIndex() {
return hasNext ? -1 : 0;
}
};
}
@Override
public int size() {
return 1;
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
Preconditions.checkPositionIndexes(fromIndex, toIndex, 1);
return (fromIndex == toIndex) ? ImmutableList.<E>of() : this;
}
@Override public ImmutableList<E> reverse() {
return this;
}
@Override public boolean contains(@Nullable Object object) {
return element.equals(object);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof List) {
List<?> that = (List<?>) object;
return that.size() == 1 && element.equals(that.get(0));
}
return false;
}
@Override public int hashCode() {
// not caching hash code since it could change if the element is mutable
// in a way that modifies its hash code.
return 31 + element.hashCode();
}
@Override public String toString() {
String elementToString = element.toString();
return new StringBuilder(elementToString.length() + 2)
.append('[')
.append(elementToString)
.append(']')
.toString();
}
@Override public boolean isEmpty() {
return false;
}
@Override boolean isPartialView() {
return false;
}
@Override public Object[] toArray() {
return new Object[] { element };
}
@Override public <T> T[] toArray(T[] array) {
if (array.length == 0) {
array = ObjectArrays.newArray(array, 1);
} else if (array.length > 1) {
array[1] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires.
Object[] objectArray = array;
objectArray[0] = element;
return array;
}
}
| 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) 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) 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.collect.BstSide.LEFT;
import static com.google.common.collect.BstSide.RIGHT;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* A utility class with operations on binary search trees that operate on some interval.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class BstRangeOps {
/**
* Returns the total value of the specified aggregation function on the specified tree restricted
* to the specified range. Assumes that the tree satisfies the binary search ordering property
* relative to {@code range.comparator()}.
*/
public static <K, N extends BstNode<K, N>> long totalInRange(
BstAggregate<? super N> aggregate, GeneralRange<K> range, @Nullable N root) {
checkNotNull(aggregate);
checkNotNull(range);
if (root == null || range.isEmpty()) {
return 0;
}
long total = aggregate.treeValue(root);
if (range.hasLowerBound()) {
total -= totalBeyondRangeToSide(aggregate, range, LEFT, root);
}
if (range.hasUpperBound()) {
total -= totalBeyondRangeToSide(aggregate, range, RIGHT, root);
}
return total;
}
// Returns total value strictly to the specified side of the specified range.
private static <K, N extends BstNode<K, N>> long totalBeyondRangeToSide(
BstAggregate<? super N> aggregate, GeneralRange<K> range, BstSide side, @Nullable N root) {
long accum = 0;
while (root != null) {
if (beyond(range, root.getKey(), side)) {
accum += aggregate.entryValue(root);
accum += aggregate.treeValue(root.childOrNull(side));
root = root.childOrNull(side.other());
} else {
root = root.childOrNull(side);
}
}
return accum;
}
/**
* Returns a balanced tree containing all nodes from the specified tree that were <i>not</i> in
* the specified range, using the specified balance policy. Assumes that the tree satisfies the
* binary search ordering property relative to {@code range.comparator()}.
*/
@Nullable
public static <K, N extends BstNode<K, N>> N minusRange(GeneralRange<K> range,
BstBalancePolicy<N> balancePolicy, BstNodeFactory<N> nodeFactory, @Nullable N root) {
checkNotNull(range);
checkNotNull(balancePolicy);
checkNotNull(nodeFactory);
N higher = range.hasUpperBound()
? subTreeBeyondRangeToSide(range, balancePolicy, nodeFactory, RIGHT, root)
: null;
N lower = range.hasLowerBound()
? subTreeBeyondRangeToSide(range, balancePolicy, nodeFactory, LEFT, root)
: null;
return balancePolicy.combine(nodeFactory, lower, higher);
}
/*
* Returns a balanced tree containing all nodes in the specified tree that are strictly to the
* specified side of the specified range.
*/
@Nullable
private static <K, N extends BstNode<K, N>> N subTreeBeyondRangeToSide(GeneralRange<K> range,
BstBalancePolicy<N> balancePolicy, BstNodeFactory<N> nodeFactory, BstSide side,
@Nullable N root) {
if (root == null) {
return null;
}
if (beyond(range, root.getKey(), side)) {
N left = root.childOrNull(LEFT);
N right = root.childOrNull(RIGHT);
switch (side) {
case LEFT:
right = subTreeBeyondRangeToSide(range, balancePolicy, nodeFactory, LEFT, right);
break;
case RIGHT:
left = subTreeBeyondRangeToSide(range, balancePolicy, nodeFactory, RIGHT, left);
break;
default:
throw new AssertionError();
}
return balancePolicy.balance(nodeFactory, root, left, right);
} else {
return subTreeBeyondRangeToSide(
range, balancePolicy, nodeFactory, side, root.childOrNull(side));
}
}
/**
* Returns the furthest path to the specified side in the specified tree that falls into the
* specified range.
*/
@Nullable
public static <K, N extends BstNode<K, N>, P extends BstPath<N, P>> P furthestPath(
GeneralRange<K> range, BstSide side, BstPathFactory<N, P> pathFactory, @Nullable N root) {
checkNotNull(range);
checkNotNull(pathFactory);
checkNotNull(side);
if (root == null) {
return null;
}
P path = pathFactory.initialPath(root);
return furthestPath(range, side, pathFactory, path);
}
private static <K, N extends BstNode<K, N>, P extends BstPath<N, P>> P furthestPath(
GeneralRange<K> range, BstSide side, BstPathFactory<N, P> pathFactory, P currentPath) {
N tip = currentPath.getTip();
K tipKey = tip.getKey();
if (beyond(range, tipKey, side)) {
if (tip.hasChild(side.other())) {
currentPath = pathFactory.extension(currentPath, side.other());
return furthestPath(range, side, pathFactory, currentPath);
} else {
return null;
}
} else if (tip.hasChild(side)) {
P alphaPath = pathFactory.extension(currentPath, side);
alphaPath = furthestPath(range, side, pathFactory, alphaPath);
if (alphaPath != null) {
return alphaPath;
}
}
return beyond(range, tipKey, side.other()) ? null : currentPath;
}
/**
* Returns {@code true} if {@code key} is beyond the specified side of the specified range.
*/
public static <K> boolean beyond(GeneralRange<K> range, @Nullable K key, BstSide side) {
checkNotNull(range);
switch (side) {
case LEFT:
return range.tooLow(key);
case RIGHT:
return range.tooHigh(key);
default:
throw new AssertionError();
}
}
private BstRangeOps() {}
}
| 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.GwtCompatible;
import com.google.common.base.Optional;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* A {@code BstPath} supporting inorder traversal operations.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class BstInOrderPath<N extends BstNode<?, N>> extends BstPath<N, BstInOrderPath<N>> {
/**
* The factory to use to construct {@code BstInOrderPath} values.
*/
public static <N extends BstNode<?, N>> BstPathFactory<N, BstInOrderPath<N>> inOrderFactory() {
return new BstPathFactory<N, BstInOrderPath<N>>() {
@Override
public BstInOrderPath<N> extension(BstInOrderPath<N> path, BstSide side) {
return BstInOrderPath.extension(path, side);
}
@Override
public BstInOrderPath<N> initialPath(N root) {
return new BstInOrderPath<N>(root, null, null);
}
};
}
private static <N extends BstNode<?, N>> BstInOrderPath<N> extension(
BstInOrderPath<N> path, BstSide side) {
checkNotNull(path);
N tip = path.getTip();
return new BstInOrderPath<N>(tip.getChild(side), side, path);
}
private final BstSide sideExtension;
private transient Optional<BstInOrderPath<N>> prevInOrder;
private transient Optional<BstInOrderPath<N>> nextInOrder;
private BstInOrderPath(
N tip, @Nullable BstSide sideExtension, @Nullable BstInOrderPath<N> tail) {
super(tip, tail);
this.sideExtension = sideExtension;
assert (sideExtension == null) == (tail == null);
}
private Optional<BstInOrderPath<N>> computeNextInOrder(BstSide side) {
if (getTip().hasChild(side)) {
BstInOrderPath<N> path = extension(this, side);
BstSide otherSide = side.other();
while (path.getTip().hasChild(otherSide)) {
path = extension(path, otherSide);
}
return Optional.of(path);
} else {
BstInOrderPath<N> current = this;
while (current.sideExtension == side) {
current = current.getPrefix();
}
current = current.prefixOrNull();
return Optional.fromNullable(current);
}
}
private Optional<BstInOrderPath<N>> nextInOrder(BstSide side) {
Optional<BstInOrderPath<N>> result;
switch (side) {
case LEFT:
result = prevInOrder;
return (result == null) ? prevInOrder = computeNextInOrder(side) : result;
case RIGHT:
result = nextInOrder;
return (result == null) ? nextInOrder = computeNextInOrder(side) : result;
default:
throw new AssertionError();
}
}
/**
* Returns {@code true} if there is a next path in an in-order traversal in the given direction.
*/
public boolean hasNext(BstSide side) {
return nextInOrder(side).isPresent();
}
/**
* Returns the next path in an in-order traversal in the given direction.
*
* @throws NoSuchElementException if this would be the last path in an in-order traversal
*/
public BstInOrderPath<N> next(BstSide side) {
if (!hasNext(side)) {
throw new NoSuchElementException();
}
return nextInOrder(side).get();
}
/**
* Returns the direction this path went in relative to its tail path, or {@code null} if this
* path has no tail.
*/
public BstSide getSideOfExtension() {
return sideExtension;
}
}
| 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.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.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 UnmodifiableIterator<Object> EMPTY_ITERATOR
= new UnmodifiableIterator<Object>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
};
/**
* 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")
public static <T> UnmodifiableIterator<T> emptyIterator() {
return (UnmodifiableIterator<T>) EMPTY_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 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) {
if (!iterator.hasNext()) {
return "[]";
}
StringBuilder builder = new StringBuilder();
builder.append('[').append(iterator.next());
while (iterator.hasNext()) {
builder.append(", ").append(iterator.next());
}
return builder.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.
*/
public static <T> T getOnlyElement(
Iterator<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.
*/
@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.
*/
@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.
*/
@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.
*
* @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.
*/
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, T)} 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
*/
public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate,
@Nullable T defaultValue) {
UnmodifiableIterator<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(fromIterator);
checkNotNull(function);
return new Iterator<T>() {
@Override
public boolean hasNext() {
return fromIterator.hasNext();
}
@Override
public T next() {
F from = fromIterator.next();
return function.apply(from);
}
@Override
public void remove() {
fromIterator.remove();
}
};
}
/**
* 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
*/
public static <T> T get(Iterator<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
*/
public static <T> T getNext(Iterator<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
*/
public static <T> T getLast(Iterator<T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? getLast(iterator) : defaultValue;
}
/**
* Calls {@code next()} on {@code iterator}, either {@code numberToSkip} times
* or until {@code hasNext()} returns {@code false}, whichever comes first.
*
* @return the number of elements skipped
* @since 3.0
*/
@Beta
public static <T> int skip(Iterator<T> iterator, int numberToSkip) {
checkNotNull(iterator);
checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
int i;
for (i = 0; i < numberToSkip && 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 an iterator containing the elements in the specified range 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>The {@code Iterable} equivalent of this method is {@code
* Arrays.asList(array).subList(offset, offset + length)}.
*
* @param array array to read elements out of
* @param offset index of first array element to retrieve
* @param length number of elements in iteration
* @throws IndexOutOfBoundsException if {@code offset} is negative, {@code
* length} is negative, or {@code offset + length > array.length}
*/
static <T> UnmodifiableIterator<T> forArray(
final T[] array, final int offset, int length) {
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) {
@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;
}
}
}
| 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> {
private static final ImmutableBiMap<Object, Object> EMPTY_IMMUTABLE_BIMAP
= new EmptyBiMap();
/**
* 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>) EMPTY_IMMUTABLE_BIMAP;
}
/**
* 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 public ImmutableSet<Entry<K, V>> entrySet() {
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
*/
@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();
}
/** Bimap with no mappings. */
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
static class EmptyBiMap extends ImmutableBiMap<Object, Object> {
@Override ImmutableMap<Object, Object> delegate() {
return ImmutableMap.of();
}
@Override public ImmutableBiMap<Object, Object> inverse() {
return this;
}
@Override boolean isPartialView() {
return false;
}
Object readResolve() {
return EMPTY_IMMUTABLE_BIMAP; // preserve singleton property
}
}
/**
* 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 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), checkNotNull(v1));
}
/**
* 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) {
return Maps.immutableEntry(
checkNotNull(key, "null key"),
checkNotNull(value, "null 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
*/
@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
*/
@Override
public final V remove(Object o) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
@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
*/
@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;
}
// Overriding to mark it Nullable
@Override
public abstract boolean containsValue(@Nullable Object value);
// Overriding to mark it Nullable
@Override
public abstract V get(@Nullable Object key);
/**
* 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 abstract ImmutableSet<Entry<K, V>> entrySet();
/**
* 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 abstract ImmutableSet<K> keySet();
/**
* 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 abstract ImmutableCollection<V> values();
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Map) {
Map<?, ?> that = (Map<?, ?>) object;
return this.entrySet().equals(that.entrySet());
}
return false;
}
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) 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.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
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 java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Factory and utilities pertaining to the {@code MapConstraint} interface.
*
* @see Constraints
* @author Mike Bostock
* @since 3.0
*/
@Beta
@GwtCompatible
public final class MapConstraints {
private MapConstraints() {}
/**
* Returns a constraint that verifies that neither the key nor the value is
* null. If either is null, a {@link NullPointerException} is thrown.
*/
public static MapConstraint<Object, Object> notNull() {
return NotNullMapConstraint.INSTANCE;
}
// enum singleton pattern
private enum NotNullMapConstraint implements MapConstraint<Object, Object> {
INSTANCE;
@Override
public void checkKeyValue(Object key, Object value) {
checkNotNull(key);
checkNotNull(value);
}
@Override public String toString() {
return "Not null";
}
}
/**
* Returns a constrained view of the specified map, using the specified
* constraint. Any operations that add new mappings will call the provided
* constraint. However, this method does not verify that existing mappings
* satisfy the constraint.
*
* <p>The returned map is not serializable.
*
* @param map the map to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified map
*/
public static <K, V> Map<K, V> constrainedMap(
Map<K, V> map, MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedMap<K, V>(map, constraint);
}
/**
* Returns a constrained view of the specified multimap, using the specified
* constraint. Any operations that add new mappings will call the provided
* constraint. However, this method does not verify that existing mappings
* satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
*
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the multimap
*/
public static <K, V> Multimap<K, V> constrainedMultimap(
Multimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified list multimap, using the
* specified constraint. Any operations that add new mappings will call the
* provided constraint. However, this method does not verify that existing
* mappings satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
*
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> constrainedListMultimap(
ListMultimap<K, V> multimap,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedListMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified set multimap, using the
* specified constraint. Any operations that add new mappings will call the
* provided constraint. However, this method does not verify that existing
* mappings satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> constrainedSetMultimap(
SetMultimap<K, V> multimap,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedSetMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified sorted-set multimap, using the
* specified constraint. Any operations that add new mappings will call the
* provided constraint. However, this method does not verify that existing
* mappings satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V> constrainedSortedSetMultimap(
SortedSetMultimap<K, V> multimap,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedSortedSetMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified entry, using the specified
* constraint. The {@link Entry#setValue} operation will be verified with the
* constraint.
*
* @param entry the entry to constrain
* @param constraint the constraint for the entry
* @return a constrained view of the specified entry
*/
private static <K, V> Entry<K, V> constrainedEntry(
final Entry<K, V> entry,
final MapConstraint<? super K, ? super V> constraint) {
checkNotNull(entry);
checkNotNull(constraint);
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return entry;
}
@Override public V setValue(V value) {
constraint.checkKeyValue(getKey(), value);
return entry.setValue(value);
}
};
}
/**
* Returns a constrained view of the specified {@code asMap} entry, using the
* specified constraint. The {@link Entry#setValue} operation will be verified
* with the constraint, and the collection returned by {@link Entry#getValue}
* will be similarly constrained.
*
* @param entry the {@code asMap} entry to constrain
* @param constraint the constraint for the entry
* @return a constrained view of the specified entry
*/
private static <K, V> Entry<K, Collection<V>> constrainedAsMapEntry(
final Entry<K, Collection<V>> entry,
final MapConstraint<? super K, ? super V> constraint) {
checkNotNull(entry);
checkNotNull(constraint);
return new ForwardingMapEntry<K, Collection<V>>() {
@Override protected Entry<K, Collection<V>> delegate() {
return entry;
}
@Override public Collection<V> getValue() {
return Constraints.constrainedTypePreservingCollection(
entry.getValue(), new Constraint<V>() {
@Override
public V checkElement(V value) {
constraint.checkKeyValue(getKey(), value);
return value;
}
});
}
};
}
/**
* Returns a constrained view of the specified set of {@code asMap} entries,
* using the specified constraint. The {@link Entry#setValue} operation will
* be verified with the constraint, and the collection returned by {@link
* Entry#getValue} will be similarly constrained. The {@code add} and {@code
* addAll} operations simply forward to the underlying set, which throws an
* {@link UnsupportedOperationException} per the multimap specification.
*
* @param entries the entries to constrain
* @param constraint the constraint for the entries
* @return a constrained view of the entries
*/
private static <K, V> Set<Entry<K, Collection<V>>> constrainedAsMapEntries(
Set<Entry<K, Collection<V>>> entries,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedAsMapEntries<K, V>(entries, constraint);
}
/**
* Returns a constrained view of the specified collection (or set) of entries,
* using the specified constraint. The {@link Entry#setValue} operation will
* be verified with the constraint, along with add operations on the returned
* collection. The {@code add} and {@code addAll} operations simply forward to
* the underlying collection, which throws an {@link
* UnsupportedOperationException} per the map and multimap specification.
*
* @param entries the entries to constrain
* @param constraint the constraint for the entries
* @return a constrained view of the specified entries
*/
private static <K, V> Collection<Entry<K, V>> constrainedEntries(
Collection<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
if (entries instanceof Set) {
return constrainedEntrySet((Set<Entry<K, V>>) entries, constraint);
}
return new ConstrainedEntries<K, V>(entries, constraint);
}
/**
* Returns a constrained view of the specified set of entries, using the
* specified constraint. The {@link Entry#setValue} operation will be verified
* with the constraint, along with add operations on the returned set. The
* {@code add} and {@code addAll} operations simply forward to the underlying
* set, which throws an {@link UnsupportedOperationException} per the map and
* multimap specification.
*
* <p>The returned multimap is not serializable.
*
* @param entries the entries to constrain
* @param constraint the constraint for the entries
* @return a constrained view of the specified entries
*/
private static <K, V> Set<Entry<K, V>> constrainedEntrySet(
Set<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedEntrySet<K, V>(entries, constraint);
}
/** @see MapConstraints#constrainedMap */
static class ConstrainedMap<K, V> extends ForwardingMap<K, V> {
private final Map<K, V> delegate;
final MapConstraint<? super K, ? super V> constraint;
private transient Set<Entry<K, V>> entrySet;
ConstrainedMap(
Map<K, V> delegate, MapConstraint<? super K, ? super V> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Map<K, V> delegate() {
return delegate;
}
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
if (result == null) {
entrySet = result =
constrainedEntrySet(delegate.entrySet(), constraint);
}
return result;
}
@Override public V put(K key, V value) {
constraint.checkKeyValue(key, value);
return delegate.put(key, value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
delegate.putAll(checkMap(map, constraint));
}
}
/**
* Returns a constrained view of the specified bimap, using the specified
* constraint. Any operations that modify the bimap will have the associated
* keys and values verified with the constraint.
*
* <p>The returned bimap is not serializable.
*
* @param map the bimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified bimap
*/
public static <K, V> BiMap<K, V> constrainedBiMap(
BiMap<K, V> map, MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedBiMap<K, V>(map, null, constraint);
}
/** @see MapConstraints#constrainedBiMap */
private static class ConstrainedBiMap<K, V> extends ConstrainedMap<K, V>
implements BiMap<K, V> {
/*
* We could switch to racy single-check lazy init and remove volatile, but
* there's a downside. That's because this field is also written in the
* constructor. Without volatile, the constructor's write of the existing
* inverse BiMap could occur after inverse()'s read of the field's initial
* null value, leading inverse() to overwrite the existing inverse with a
* doubly indirect version. This wouldn't be catastrophic, but it's
* something to keep in mind if we make the change.
*
* Note that UnmodifiableBiMap *does* use racy single-check lazy init.
* TODO(cpovirk): pick one and standardize
*/
volatile BiMap<V, K> inverse;
ConstrainedBiMap(BiMap<K, V> delegate, @Nullable BiMap<V, K> inverse,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
this.inverse = inverse;
}
@Override protected BiMap<K, V> delegate() {
return (BiMap<K, V>) super.delegate();
}
@Override
public V forcePut(K key, V value) {
constraint.checkKeyValue(key, value);
return delegate().forcePut(key, value);
}
@Override
public BiMap<V, K> inverse() {
if (inverse == null) {
inverse = new ConstrainedBiMap<V, K>(delegate().inverse(), this,
new InverseConstraint<V, K>(constraint));
}
return inverse;
}
@Override public Set<V> values() {
return delegate().values();
}
}
/** @see MapConstraints#constrainedBiMap */
private static class InverseConstraint<K, V> implements MapConstraint<K, V> {
final MapConstraint<? super V, ? super K> constraint;
public InverseConstraint(MapConstraint<? super V, ? super K> constraint) {
this.constraint = checkNotNull(constraint);
}
@Override
public void checkKeyValue(K key, V value) {
constraint.checkKeyValue(value, key);
}
}
/** @see MapConstraints#constrainedMultimap */
private static class ConstrainedMultimap<K, V>
extends ForwardingMultimap<K, V> {
final MapConstraint<? super K, ? super V> constraint;
final Multimap<K, V> delegate;
transient Collection<Entry<K, V>> entries;
transient Map<K, Collection<V>> asMap;
public ConstrainedMultimap(Multimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Multimap<K, V> delegate() {
return delegate;
}
@Override public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
if (result == null) {
final Map<K, Collection<V>> asMapDelegate = delegate.asMap();
asMap = result = new ForwardingMap<K, Collection<V>>() {
Set<Entry<K, Collection<V>>> entrySet;
Collection<Collection<V>> values;
@Override protected Map<K, Collection<V>> delegate() {
return asMapDelegate;
}
@Override public Set<Entry<K, Collection<V>>> entrySet() {
Set<Entry<K, Collection<V>>> result = entrySet;
if (result == null) {
entrySet = result = constrainedAsMapEntries(
asMapDelegate.entrySet(), constraint);
}
return result;
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
try {
Collection<V> collection = ConstrainedMultimap.this.get((K) key);
return collection.isEmpty() ? null : collection;
} catch (ClassCastException e) {
return null; // key wasn't a K
}
}
@Override public Collection<Collection<V>> values() {
Collection<Collection<V>> result = values;
if (result == null) {
values = result = new ConstrainedAsMapValues<K, V>(
delegate().values(), entrySet());
}
return result;
}
@Override public boolean containsValue(Object o) {
return values().contains(o);
}
};
}
return result;
}
@Override public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
if (result == null) {
entries = result = constrainedEntries(delegate.entries(), constraint);
}
return result;
}
@Override public Collection<V> get(final K key) {
return Constraints.constrainedTypePreservingCollection(
delegate.get(key), new Constraint<V>() {
@Override
public V checkElement(V value) {
constraint.checkKeyValue(key, value);
return value;
}
});
}
@Override public boolean put(K key, V value) {
constraint.checkKeyValue(key, value);
return delegate.put(key, value);
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
return delegate.putAll(key, checkValues(key, values, constraint));
}
@Override public boolean putAll(
Multimap<? extends K, ? extends V> multimap) {
boolean changed = false;
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
changed |= put(entry.getKey(), entry.getValue());
}
return changed;
}
@Override public Collection<V> replaceValues(
K key, Iterable<? extends V> values) {
return delegate.replaceValues(key, checkValues(key, values, constraint));
}
}
/** @see ConstrainedMultimap#asMap */
private static class ConstrainedAsMapValues<K, V>
extends ForwardingCollection<Collection<V>> {
final Collection<Collection<V>> delegate;
final Set<Entry<K, Collection<V>>> entrySet;
/**
* @param entrySet map entries, linking each key with its corresponding
* values, that already enforce the constraint
*/
ConstrainedAsMapValues(Collection<Collection<V>> delegate,
Set<Entry<K, Collection<V>>> entrySet) {
this.delegate = delegate;
this.entrySet = entrySet;
}
@Override protected Collection<Collection<V>> delegate() {
return delegate;
}
@Override public Iterator<Collection<V>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = entrySet.iterator();
return new Iterator<Collection<V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Collection<V> next() {
return iterator.next().getValue();
}
@Override
public void remove() {
iterator.remove();
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return standardContains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean remove(Object o) {
return standardRemove(o);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** @see MapConstraints#constrainedEntries */
private static class ConstrainedEntries<K, V>
extends ForwardingCollection<Entry<K, V>> {
final MapConstraint<? super K, ? super V> constraint;
final Collection<Entry<K, V>> entries;
ConstrainedEntries(Collection<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
this.entries = entries;
this.constraint = constraint;
}
@Override protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = entries.iterator();
return new ForwardingIterator<Entry<K, V>>() {
@Override public Entry<K, V> next() {
return constrainedEntry(iterator.next(), constraint);
}
@Override protected Iterator<Entry<K, V>> delegate() {
return iterator;
}
};
}
// See Collections.CheckedMap.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 remove(Object o) {
return Maps.removeEntryImpl(delegate(), o);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** @see MapConstraints#constrainedEntrySet */
static class ConstrainedEntrySet<K, V>
extends ConstrainedEntries<K, V> implements Set<Entry<K, V>> {
ConstrainedEntrySet(Set<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
super(entries, constraint);
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/** @see MapConstraints#constrainedAsMapEntries */
static class ConstrainedAsMapEntries<K, V>
extends ForwardingSet<Entry<K, Collection<V>>> {
private final MapConstraint<? super K, ? super V> constraint;
private final Set<Entry<K, Collection<V>>> entries;
ConstrainedAsMapEntries(Set<Entry<K, Collection<V>>> entries,
MapConstraint<? super K, ? super V> constraint) {
this.entries = entries;
this.constraint = constraint;
}
@Override protected Set<Entry<K, Collection<V>>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = entries.iterator();
return new ForwardingIterator<Entry<K, Collection<V>>>() {
@Override public Entry<K, Collection<V>> next() {
return constrainedAsMapEntry(iterator.next(), constraint);
}
@Override protected Iterator<Entry<K, Collection<V>>> delegate() {
return iterator;
}
};
}
// See Collections.CheckedMap.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 equals(@Nullable Object object) {
return standardEquals(object);
}
@Override public int hashCode() {
return standardHashCode();
}
@Override public boolean remove(Object o) {
return Maps.removeEntryImpl(delegate(), o);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
private static class ConstrainedListMultimap<K, V>
extends ConstrainedMultimap<K, V> implements ListMultimap<K, V> {
ConstrainedListMultimap(ListMultimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
}
@Override public List<V> get(K key) {
return (List<V>) super.get(key);
}
@Override public List<V> removeAll(Object key) {
return (List<V>) super.removeAll(key);
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
return (List<V>) super.replaceValues(key, values);
}
}
private static class ConstrainedSetMultimap<K, V>
extends ConstrainedMultimap<K, V> implements SetMultimap<K, V> {
ConstrainedSetMultimap(SetMultimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
}
@Override public Set<V> get(K key) {
return (Set<V>) super.get(key);
}
@Override public Set<Map.Entry<K, V>> entries() {
return (Set<Map.Entry<K, V>>) super.entries();
}
@Override public Set<V> removeAll(Object key) {
return (Set<V>) super.removeAll(key);
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
return (Set<V>) super.replaceValues(key, values);
}
}
private static class ConstrainedSortedSetMultimap<K, V>
extends ConstrainedSetMultimap<K, V> implements SortedSetMultimap<K, V> {
ConstrainedSortedSetMultimap(SortedSetMultimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
}
@Override public SortedSet<V> get(K key) {
return (SortedSet<V>) super.get(key);
}
@Override public SortedSet<V> removeAll(Object key) {
return (SortedSet<V>) super.removeAll(key);
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
return (SortedSet<V>) super.replaceValues(key, values);
}
@Override
public Comparator<? super V> valueComparator() {
return ((SortedSetMultimap<K, V>) delegate()).valueComparator();
}
}
private static <K, V> Collection<V> checkValues(K key,
Iterable<? extends V> values,
MapConstraint<? super K, ? super V> constraint) {
Collection<V> copy = Lists.newArrayList(values);
for (V value : copy) {
constraint.checkKeyValue(key, value);
}
return copy;
}
private static <K, V> Map<K, V> checkMap(Map<? extends K, ? extends V> map,
MapConstraint<? super K, ? super V> constraint) {
Map<K, V> copy = new LinkedHashMap<K, V>(map);
for (Entry<K, V> entry : copy.entrySet()) {
constraint.checkKeyValue(entry.getKey(), entry.getValue());
}
return copy;
}
}
| 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.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
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.
*/
ImmutableMap.Builder<R, Integer> rowBuilder = ImmutableMap.builder();
for (int i = 0; i < rowList.size(); i++) {
rowBuilder.put(rowList.get(i), i);
}
rowKeyToIndex = rowBuilder.build();
ImmutableMap.Builder<C, Integer> columnBuilder = ImmutableMap.builder();
for (int i = 0; i < columnList.size(); i++) {
columnBuilder.put(columnList.get(i), i);
}
columnKeyToIndex = columnBuilder.build();
@SuppressWarnings("unchecked")
V[][] tmpArray
= (V[][]) new Object[rowList.size()][columnList.size()];
array = tmpArray;
}
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);
}
}
/**
* 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 getIndexed(rowIndex, columnIndex);
}
private V getIndexed(Integer rowIndex, Integer columnIndex) {
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 AbstractMap<R, V> {
final int columnIndex;
Column(int columnIndex) {
this.columnIndex = columnIndex;
}
ColumnEntrySet entrySet;
@Override public Set<Entry<R, V>> entrySet() {
ColumnEntrySet set = entrySet;
return (set == null) ? entrySet = new ColumnEntrySet(columnIndex) : set;
}
@Override public V get(Object rowKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
return getIndexed(rowIndex, columnIndex);
}
@Override public boolean containsKey(Object rowKey) {
return rowKeyToIndex.containsKey(rowKey);
}
@Override public V put(R rowKey, V value) {
checkNotNull(rowKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
return set(rowIndex, columnIndex, value);
}
@Override public Set<R> keySet() {
return rowKeySet();
}
}
private class ColumnEntrySet extends AbstractSet<Entry<R, V>> {
final int columnIndex;
ColumnEntrySet(int columnIndex) {
this.columnIndex = columnIndex;
}
@Override public Iterator<Entry<R, V>> iterator() {
return new AbstractIndexedListIterator<Entry<R, V>>(size()) {
@Override protected Entry<R, V> get(final int rowIndex) {
return new AbstractMapEntry<R, V>() {
@Override public R getKey() {
return rowList.get(rowIndex);
}
@Override public V getValue() {
return array[rowIndex][columnIndex];
}
@Override public V setValue(V value) {
return ArrayTable.this.set(rowIndex, columnIndex, value);
}
};
}
};
}
@Override public int size() {
return rowList.size();
}
}
/**
* 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 AbstractMap<C, Map<R, V>> {
transient ColumnMapEntrySet entrySet;
@Override public Set<Entry<C, Map<R, V>>> entrySet() {
ColumnMapEntrySet set = entrySet;
return (set == null) ? entrySet = new ColumnMapEntrySet() : set;
}
@Override public Map<R, V> get(Object columnKey) {
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (columnIndex == null) ? null : new Column(columnIndex);
}
@Override public boolean containsKey(Object columnKey) {
return containsColumn(columnKey);
}
@Override public Set<C> keySet() {
return columnKeySet();
}
@Override public Map<R, V> remove(Object columnKey) {
throw new UnsupportedOperationException();
}
}
private class ColumnMapEntrySet extends AbstractSet<Entry<C, Map<R, V>>> {
@Override public Iterator<Entry<C, Map<R, V>>> iterator() {
return new AbstractIndexedListIterator<Entry<C, Map<R, V>>>(size()) {
@Override protected Entry<C, Map<R, V>> get(int index) {
return Maps.<C, Map<R, V>>immutableEntry(columnList.get(index),
new Column(index));
}
};
}
@Override public int size() {
return columnList.size();
}
}
/**
* 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 AbstractMap<C, V> {
final int rowIndex;
Row(int rowIndex) {
this.rowIndex = rowIndex;
}
RowEntrySet entrySet;
@Override public Set<Entry<C, V>> entrySet() {
RowEntrySet set = entrySet;
return (set == null) ? entrySet = new RowEntrySet(rowIndex) : set;
}
@Override public V get(Object columnKey) {
Integer columnIndex = columnKeyToIndex.get(columnKey);
return getIndexed(rowIndex, columnIndex);
}
@Override public boolean containsKey(Object columnKey) {
return containsColumn(columnKey);
}
@Override public V put(C columnKey, V value) {
checkNotNull(columnKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
checkArgument(columnIndex != null,
"Column %s not in %s", columnKey, columnList);
return set(rowIndex, columnIndex, value);
}
@Override public Set<C> keySet() {
return columnKeySet();
}
}
private class RowEntrySet extends AbstractSet<Entry<C, V>> {
final int rowIndex;
RowEntrySet(int rowIndex) {
this.rowIndex = rowIndex;
}
@Override public Iterator<Entry<C, V>> iterator() {
return new AbstractIndexedListIterator<Entry<C, V>>(size()) {
@Override protected Entry<C, V> get(final int columnIndex) {
return new AbstractMapEntry<C, V>() {
@Override public C getKey() {
return columnList.get(columnIndex);
}
@Override public V getValue() {
return array[rowIndex][columnIndex];
}
@Override public V setValue(V value) {
return ArrayTable.this.set(rowIndex, columnIndex, value);
}
};
}
};
}
@Override public int size() {
return columnList.size();
}
}
/**
* 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 AbstractMap<R, Map<C, V>> {
transient RowMapEntrySet entrySet;
@Override public Set<Entry<R, Map<C, V>>> entrySet() {
RowMapEntrySet set = entrySet;
return (set == null) ? entrySet = new RowMapEntrySet() : set;
}
@Override public Map<C, V> get(Object rowKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
return (rowIndex == null) ? null : new Row(rowIndex);
}
@Override public boolean containsKey(Object rowKey) {
return containsRow(rowKey);
}
@Override public Set<R> keySet() {
return rowKeySet();
}
@Override public Map<C, V> remove(Object rowKey) {
throw new UnsupportedOperationException();
}
}
private class RowMapEntrySet extends AbstractSet<Entry<R, Map<C, V>>> {
@Override public Iterator<Entry<R, Map<C, V>>> iterator() {
return new AbstractIndexedListIterator<Entry<R, Map<C, V>>>(size()) {
@Override protected Entry<R, Map<C, V>> get(int index) {
return Maps.<R, Map<C, V>>immutableEntry(rowList.get(index),
new Row(index));
}
};
}
@Override public int size() {
return rowList.size();
}
}
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 AbstractIndexedListIterator<V>(size()) {
@Override protected V get(int index) {
int rowIndex = index / columnList.size();
int columnIndex = index % columnList.size();
return array[rowIndex][columnIndex];
}
};
}
@Override public int size() {
return ArrayTable.this.size();
}
@Override public boolean contains(Object value) {
return containsValue(value);
}
}
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 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) 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.checkState;
import static com.google.common.collect.BstSide.LEFT;
import static com.google.common.collect.BstSide.RIGHT;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* A reusable abstraction for a node in a binary search tree. Null keys are allowed.
*
* <p>The node is considered to be immutable. Any subclass with mutable fields must create a new
* {@code BstNode} object upon any mutation, as the {@code Bst} classes assume that two nodes
* {@code a} and {@code b} represent exactly the same tree if and only if {@code a == b}.
*
* <p>A {@code BstNode} can be considered to be an <i>entry</i>, containing a key and possibly some
* value data, or it can be considered to be a <i>subtree</i>, representative of it and all its
* descendants.
*
* @author Louis Wasserman
* @param <K> The key type associated with this tree.
* @param <N> The type of the nodes in this tree.
*/
@GwtCompatible
class BstNode<K, N extends BstNode<K, N>> {
/**
* The key on which this binary search tree is ordered. All descendants of the left subtree of
* this node must have keys strictly less than {@code this.key}.
*/
private final K key;
/**
* The left child of this node. A null value indicates that this node has no left child.
*/
@Nullable
private final N left;
/**
* The right child of this node. A null value indicates that this node has no right child.
*/
@Nullable
private final N right;
BstNode(@Nullable K key, @Nullable N left, @Nullable N right) {
this.key = key;
this.left = left;
this.right = right;
}
/**
* Returns the ordered key associated with this node.
*/
@Nullable
public final K getKey() {
return key;
}
/**
* Returns the child on the specified side, or {@code null} if there is no such child.
*/
@Nullable
public final N childOrNull(BstSide side) {
switch (side) {
case LEFT:
return left;
case RIGHT:
return right;
default:
throw new AssertionError();
}
}
/**
* Returns {@code true} if this node has a child on the specified side.
*/
public final boolean hasChild(BstSide side) {
return childOrNull(side) != null;
}
/**
* Returns this node's child on the specified side.
*
* @throws IllegalStateException if this node has no such child
*/
public final N getChild(BstSide side) {
N child = childOrNull(side);
checkState(child != null);
return child;
}
/**
* Returns {@code true} if the traditional binary search tree ordering invariant holds with
* respect to the specified {@code comparator}.
*/
protected final boolean orderingInvariantHolds(Comparator<? super K> comparator) {
checkNotNull(comparator);
boolean result = true;
if (hasChild(LEFT)) {
result &= comparator.compare(getChild(LEFT).getKey(), key) < 0;
}
if (hasChild(RIGHT)) {
result &= comparator.compare(getChild(RIGHT).getKey(), key) > 0;
}
return result;
}
}
| 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) 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.Equivalences;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Ticker;
import com.google.common.collect.ComputingConcurrentHashMap.ComputingMapAdapter;
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.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>least-recently-used eviction when a maximum size is exceeded
* <li>time-based expiration of entries, measured since last access or last write
* <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()
* .maximumSize(10000)
* .expireAfterWrite(10, TimeUnit.MINUTES)
* .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;
Equivalence<Object> valueEquivalence;
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() {}
private boolean useNullMap() {
return (nullRemovalCause == null);
}
/**
* Sets a custom {@code Equivalence} strategy for comparing keys.
*
* <p>By default, the map uses {@link Equivalences#identity} to determine key equality when
* {@link #weakKeys} or {@link #softKeys} is specified, and {@link Equivalences#equals()}
* otherwise.
*/
@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 a custom {@code Equivalence} strategy for comparing values.
*
* <p>By default, the map uses {@link Equivalences#identity} to determine value equality when
* {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalences#equals()}
* otherwise.
*/
@GwtIncompatible("To be supported")
@Override
MapMaker valueEquivalence(Equivalence<Object> equivalence) {
checkState(valueEquivalence == null,
"value equivalence was already set to %s", valueEquivalence);
this.valueEquivalence = checkNotNull(equivalence);
this.useCustomMap = true;
return this;
}
Equivalence<Object> getValueEquivalence() {
return firstNonNull(valueEquivalence, getValueStrength().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}.
*/
@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 strongly referenced.
*
* @throws IllegalStateException if the key strength was already set
*/
@Override
MapMaker strongKeys() {
return setKeyStrength(Strength.STRONG);
}
/**
* 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 strongly referenced.
*
* @throws IllegalStateException if the value strength was already set
*/
@Override
MapMaker strongValues() {
return setValueStrength(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);
}
/**
* Old name of {@link #expireAfterWrite}.
*
* @deprecated Caching functionality in {@code MapMaker} is being moved to
* {@link com.google.common.cache.CacheBuilder}. Functionality equivalent to
* {@link MapMaker#expiration} is provided by
* {@link com.google.common.cache.CacheBuilder#expireAfterWrite}.
* <b>This method is scheduled for deletion in July 2012.</b>
*/
@Deprecated
@Override
public
MapMaker expiration(long duration, TimeUnit unit) {
return expireAfterWrite(duration, unit);
}
/**
* 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}.
*/
@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}.
*/
@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}.
*/
@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}. Note that uses of
* {@link #makeComputingMap} with {@code AtomicLong} values can often be migrated to
* {@link AtomicLongMap}.
* <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 useNullMap()
? new 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 (valueEquivalence != null) {
s.addValue("valueEquivalence");
}
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);
}
}
}
}
| 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) 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.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* An immutable {@link ListMultimap} with reliable user-specified key and value
* iteration order. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableListMultimap(ListMultimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableListMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableListMultimap} 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>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(serializable = true, emulated = true)
public class ImmutableListMultimap<K, V>
extends ImmutableMultimap<K, V>
implements ListMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableListMultimap<K, V> of() {
return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
builder.put(k5, v5);
return builder.build();
}
// 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 {@code ListMultimap} instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableListMultimap.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 final class Builder<K, V>
extends ImmutableMultimap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableListMultimap#builder}.
*/
public Builder() {}
@Override public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
/**
* {@inheritDoc}
*
* @since 11.0
*/
@Override public Builder<K, V> put(
Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
@Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
super.putAll(key, values);
return this;
}
@Override public Builder<K, V> putAll(K key, V... values) {
super.putAll(key, values);
return this;
}
@Override public Builder<K, V> putAll(
Multimap<? extends K, ? extends V> multimap) {
super.putAll(multimap);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Beta @Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
super.orderKeysBy(keyComparator);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Beta @Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/**
* Returns a newly-created immutable list multimap.
*/
@Override public ImmutableListMultimap<K, V> build() {
return (ImmutableListMultimap<K, V>) super.build();
}
}
/**
* 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> ImmutableListMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap.isEmpty()) {
return of();
}
// TODO(user): copy ImmutableSetMultimap by using asList() on the sets
if (multimap instanceof ImmutableListMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableListMultimap<K, V> kvMultimap
= (ImmutableListMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder();
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
ImmutableList<V> list = ImmutableList.copyOf(entry.getValue());
if (!list.isEmpty()) {
builder.put(entry.getKey(), list);
size += list.size();
}
}
return new ImmutableListMultimap<K, V>(builder.build(), size);
}
ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
super(map, size);
}
// views
/**
* Returns an immutable list of the values for the given key. If no mappings
* in the multimap have the provided key, an empty immutable list is
* returned. The values are in the same order as the parameters used to build
* this multimap.
*/
@Override public ImmutableList<V> get(@Nullable K key) {
// This cast is safe as its type is known in constructor.
ImmutableList<V> list = (ImmutableList<V>) map.get(key);
return (list == null) ? ImmutableList.<V>of() : list;
}
private transient ImmutableListMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
* value, this method returns an {@code ImmutableListMultimap} rather than the
* {@code ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
*
* @since 11
*/
@Beta
public ImmutableListMultimap<V, K> inverse() {
ImmutableListMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableListMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableListMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override public ImmutableList<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override public ImmutableList<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* @serialData number of distinct keys, and then for each distinct key: the
* key, the number of values for that key, and the key's values
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int keyCount = stream.readInt();
if (keyCount < 0) {
throw new InvalidObjectException("Invalid key count " + keyCount);
}
ImmutableMap.Builder<Object, ImmutableList<Object>> builder
= ImmutableMap.builder();
int tmpSize = 0;
for (int i = 0; i < keyCount; i++) {
Object key = stream.readObject();
int valueCount = stream.readInt();
if (valueCount <= 0) {
throw new InvalidObjectException("Invalid value count " + valueCount);
}
Object[] array = new Object[valueCount];
for (int j = 0; j < valueCount; j++) {
array[j] = stream.readObject();
}
builder.put(key, ImmutableList.copyOf(array));
tmpSize += valueCount;
}
ImmutableMap<Object, ImmutableList<Object>> tmpMap;
try {
tmpMap = builder.build();
} catch (IllegalArgumentException e) {
throw (InvalidObjectException)
new InvalidObjectException(e.getMessage()).initCause(e);
}
FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
}
@GwtIncompatible("Not needed in emulated source")
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 static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.BstModificationResult.ModificationType.REBUILDING_CHANGE;
import static com.google.common.collect.BstSide.LEFT;
import static com.google.common.collect.BstSide.RIGHT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BstModificationResult.ModificationType;
import javax.annotation.Nullable;
/**
* The result of a mutation operation performed at a single location in a binary search tree.
*
* @author Louis Wasserman
* @param <K> The key type of the nodes in the modified binary search tree.
* @param <N> The type of the nodes in the modified binary search tree.
*/
@GwtCompatible
final class BstMutationResult<K, N extends BstNode<K, N>> {
/**
* Creates a {@code BstMutationResult}.
*
* @param targetKey The key targeted for modification. If {@code originalTarget} or {@code
* changedTarget} are non-null, their keys must compare as equal to {@code targetKey}.
* @param originalRoot The root of the subtree that was modified.
* @param changedRoot The root of the subtree, after the modification and any rebalancing.
* @param modificationResult The result of the local modification to an entry.
*/
public static <K, N extends BstNode<K, N>> BstMutationResult<K, N> mutationResult(
@Nullable K targetKey, @Nullable N originalRoot, @Nullable N changedRoot,
BstModificationResult<N> modificationResult) {
return new BstMutationResult<K, N>(targetKey, originalRoot, changedRoot, modificationResult);
}
private final K targetKey;
@Nullable
private N originalRoot;
@Nullable
private N changedRoot;
private final BstModificationResult<N> modificationResult;
private BstMutationResult(@Nullable K targetKey, @Nullable N originalRoot,
@Nullable N changedRoot, BstModificationResult<N> modificationResult) {
this.targetKey = targetKey;
this.originalRoot = originalRoot;
this.changedRoot = changedRoot;
this.modificationResult = checkNotNull(modificationResult);
}
/**
* Returns the key which was the target of this modification.
*/
public K getTargetKey() {
return targetKey;
}
/**
* Returns the root of the subtree that was modified.
*/
@Nullable
public N getOriginalRoot() {
return originalRoot;
}
/**
* Returns the root of the subtree, after the modification and any rebalancing was performed.
*/
@Nullable
public N getChangedRoot() {
return changedRoot;
}
/**
* Returns the entry in the original subtree with key {@code targetKey}, if any. This should not
* be treated as a subtree, but only as an entry, and no guarantees are made about its children
* when viewed as a subtree.
*/
@Nullable
public N getOriginalTarget() {
return modificationResult.getOriginalTarget();
}
/**
* Returns the result of the modification to {@link #getOriginalTarget()}. This should not be
* treated as a subtree, but only as an entry, and no guarantees are made about its children when
* viewed as a subtree.
*/
@Nullable
public N getChangedTarget() {
return modificationResult.getChangedTarget();
}
ModificationType modificationType() {
return modificationResult.getType();
}
/**
* If this mutation was to an immediate child subtree of the specified root on the specified
* side, returns the {@code BstMutationResult} of applying the mutation to the appropriate child
* of the specified root and rebalancing using the specified mutation rule.
*/
public BstMutationResult<K, N> lift(N liftOriginalRoot, BstSide side,
BstNodeFactory<N> nodeFactory, BstBalancePolicy<N> balancePolicy) {
assert liftOriginalRoot != null & side != null & nodeFactory != null & balancePolicy != null;
switch (modificationType()) {
case IDENTITY:
this.originalRoot = this.changedRoot = liftOriginalRoot;
return this;
case REBUILDING_CHANGE:
case REBALANCING_CHANGE:
this.originalRoot = liftOriginalRoot;
N resultLeft = liftOriginalRoot.childOrNull(LEFT);
N resultRight = liftOriginalRoot.childOrNull(RIGHT);
switch (side) {
case LEFT:
resultLeft = changedRoot;
break;
case RIGHT:
resultRight = changedRoot;
break;
default:
throw new AssertionError();
}
if (modificationType() == REBUILDING_CHANGE) {
this.changedRoot = nodeFactory.createNode(liftOriginalRoot, resultLeft, resultRight);
} else {
this.changedRoot =
balancePolicy.balance(nodeFactory, liftOriginalRoot, resultLeft, resultRight);
}
return this;
default:
throw new AssertionError();
}
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* 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.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* An empty implementation of {@link ImmutableTable}.
*
* @author gak@google.com (Gregory Kick)
*/
@GwtCompatible
@Immutable
final class EmptyImmutableTable extends ImmutableTable<Object, Object, Object> {
static final EmptyImmutableTable INSTANCE = new EmptyImmutableTable();
private EmptyImmutableTable() {}
@Override public int size() {
return 0;
}
@Override public Object get(@Nullable Object rowKey,
@Nullable Object columnKey) {
return null;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Table<?, ?, ?>) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
return that.isEmpty();
} else {
return false;
}
}
@Override public int hashCode() {
return 0;
}
@Override public ImmutableSet<Cell<Object, Object, Object>> cellSet() {
return ImmutableSet.of();
}
@Override public ImmutableMap<Object, Object> column(Object columnKey) {
checkNotNull(columnKey);
return ImmutableMap.of();
}
@Override public ImmutableSet<Object> columnKeySet() {
return ImmutableSet.of();
}
@Override public ImmutableMap<Object, Map<Object, Object>> columnMap() {
return ImmutableMap.of();
}
@Override public boolean contains(@Nullable Object rowKey,
@Nullable Object columnKey) {
return false;
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return false;
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return false;
}
@Override public boolean containsValue(@Nullable Object value) {
return false;
}
@Override public ImmutableMap<Object, Object> row(Object rowKey) {
checkNotNull(rowKey);
return ImmutableMap.of();
}
@Override public ImmutableSet<Object> rowKeySet() {
return ImmutableSet.of();
}
@Override public ImmutableMap<Object, Map<Object, Object>> rowMap() {
return ImmutableMap.of();
}
@Override public String toString() {
return "{}";
}
@Override public ImmutableCollection<Object> values() {
return ImmutableSet.of();
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| 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.Beta;
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 AbstractLinkedIterator<Integer>(1) {
* protected Integer computeNext(Integer previous) {
* return (previous == 1 << 30) ? null : previous * 2;
* }
* };}</pre>
*
* @author Chris Povirk
* @since 8.0
* @deprecated This class has been renamed to {@link
* AbstractSequentialIterator}. It is scheduled to be removed in Guava
* release 13.0.
*/
@Beta
@Deprecated
@GwtCompatible
public abstract class AbstractLinkedIterator<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 AbstractLinkedIterator(@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.io.Serializable;
import javax.annotation.Nullable;
/** An ordering that treats {@code null} as greater than all other values. */
@GwtCompatible(serializable = true)
final class NullsLastOrdering<T> extends Ordering<T> implements Serializable {
final Ordering<? super T> ordering;
NullsLastOrdering(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 LEFT_IS_GREATER;
}
if (right == null) {
return RIGHT_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().nullsFirst();
}
@Override public <S extends T> Ordering<S> nullsFirst() {
return ordering.nullsFirst();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override public <S extends T> Ordering<S> nullsLast() {
return (Ordering<S>) this;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof NullsLastOrdering) {
NullsLastOrdering<?> that = (NullsLastOrdering<?>) object;
return this.ordering.equals(that.ordering);
}
return false;
}
@Override public int hashCode() {
return ordering.hashCode() ^ -921210296; // meaningless
}
@Override public String toString() {
return ordering + ".nullsLast()";
}
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 java.io.Serializable;
import java.util.Iterator;
/** An ordering that uses the reverse of the natural order of the values. */
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this??
final class ReverseNaturalOrdering
extends Ordering<Comparable> implements Serializable {
static final ReverseNaturalOrdering INSTANCE = new ReverseNaturalOrdering();
@Override public int compare(Comparable left, Comparable right) {
checkNotNull(left); // right null is caught later
if (left == right) {
return 0;
}
return right.compareTo(left);
}
@Override public <S extends Comparable> Ordering<S> reverse() {
return Ordering.natural();
}
// Override the min/max methods to "hoist" delegation outside loops
@Override public <E extends Comparable> E min(E a, E b) {
return NaturalOrdering.INSTANCE.max(a, b);
}
@Override public <E extends Comparable> E min(E a, E b, E c, E... rest) {
return NaturalOrdering.INSTANCE.max(a, b, c, rest);
}
@Override public <E extends Comparable> E min(Iterator<E> iterator) {
return NaturalOrdering.INSTANCE.max(iterator);
}
@Override public <E extends Comparable> E min(Iterable<E> iterable) {
return NaturalOrdering.INSTANCE.max(iterable);
}
@Override public <E extends Comparable> E max(E a, E b) {
return NaturalOrdering.INSTANCE.min(a, b);
}
@Override public <E extends Comparable> E max(E a, E b, E c, E... rest) {
return NaturalOrdering.INSTANCE.min(a, b, c, rest);
}
@Override public <E extends Comparable> E max(Iterator<E> iterator) {
return NaturalOrdering.INSTANCE.min(iterator);
}
@Override public <E extends Comparable> E max(Iterable<E> iterable) {
return NaturalOrdering.INSTANCE.min(iterable);
}
// preserving singleton-ness gives equals()/hashCode() for free
private Object readResolve() {
return INSTANCE;
}
@Override public String toString() {
return "Ordering.natural().reverse()";
}
private ReverseNaturalOrdering() {}
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
*/
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
| 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.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 = iterator.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(iterator.next(), mutex);
}
};
}
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 javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMultiset} with one or more elements.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial")
// uses writeReplace(), not default serialization
class RegularImmutableMultiset<E> extends ImmutableMultiset<E> {
private final transient ImmutableMap<E, Integer> map;
private final transient int size;
RegularImmutableMultiset(ImmutableMap<E, Integer> map, int size) {
this.map = map;
this.size = size;
}
@Override
boolean isPartialView() {
return map.isPartialView();
}
@Override
public int count(@Nullable Object element) {
Integer value = map.get(element);
return (value == null) ? 0 : value;
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(@Nullable Object element) {
return map.containsKey(element);
}
@Override
public ImmutableSet<E> elementSet() {
return map.keySet();
}
@Override
UnmodifiableIterator<Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Integer>> mapIterator =
map.entrySet().iterator();
return new UnmodifiableIterator<Entry<E>>() {
@Override
public boolean hasNext() {
return mapIterator.hasNext();
}
@Override
public Entry<E> next() {
Map.Entry<E, Integer> mapEntry = mapIterator.next();
return Multisets.immutableEntry(mapEntry.getKey(), mapEntry.getValue());
}
};
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
int distinctElements() {
return map.size();
}
}
| 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.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 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) 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.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A set multimap which forwards all its method calls to another set 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 ForwardingSetMultimap<K, V>
extends ForwardingMultimap<K, V> implements SetMultimap<K, V> {
@Override protected abstract SetMultimap<K, V> delegate();
@Override public Set<Entry<K, V>> entries() {
return delegate().entries();
}
@Override public Set<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override public Set<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@Override public Set<V> replaceValues(K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
}
| 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 static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* A double-ended priority queue, which provides constant-time access to both
* its least element and its greatest element, as determined by the queue's
* specified comparator. If no comparator is given at construction time, the
* natural order of elements is used.
*
* <p>As a {@link Queue} it functions exactly as a {@link PriorityQueue}: its
* head element -- the implicit target of the methods {@link #peek()}, {@link
* #poll()} and {@link #remove()} -- is defined as the <i>least</i> element in
* the queue according to the queue's comparator. But unlike a regular priority
* queue, the methods {@link #peekLast}, {@link #pollLast} and
* {@link #removeLast} are also provided, to act on the <i>greatest</i> element
* in the queue instead.
*
* <p>A min-max priority queue can be configured with a maximum size. If so,
* each time the size of the queue exceeds that value, the queue automatically
* removes its greatest element according to its comparator (which might be the
* element that was just added). This is different from conventional bounded
* queues, which either block or reject new elements when full.
*
* <p>This implementation is based on the
* <a href="http://portal.acm.org/citation.cfm?id=6621">min-max heap</a>
* developed by Atkinson, et al. Unlike many other double-ended priority queues,
* it stores elements in a single array, as compact as the traditional heap data
* structure used in {@link PriorityQueue}.
*
* <p>This class is not thread-safe, and does not accept null elements.
*
* <p><i>Performance notes:</i>
*
* <ul>
* <li>The retrieval operations {@link #peek}, {@link #peekFirst}, {@link
* #peekLast}, {@link #element}, and {@link #size} are constant-time
* <li>The enqueing and dequeing operations ({@link #offer}, {@link #add}, and
* all the forms of {@link #poll} and {@link #remove()}) run in {@code
* O(log n) time}
* <li>The {@link #remove(Object)} and {@link #contains} operations require
* linear ({@code O(n)}) time
* <li>If you only access one end of the queue, and don't use a maximum size,
* this class is functionally equivalent to {@link PriorityQueue}, but
* significantly slower.
* </ul>
*
* @author Sverre Sundsdal
* @author Torbjorn Gannholm
* @since 8.0
*/
// TODO(kevinb): @GwtCompatible
@Beta
public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
/**
* Creates a new min-max priority queue with default settings: natural order,
* no maximum size, no initial contents, and an initial expected size of 11.
*/
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() {
return new Builder<Comparable>(Ordering.natural()).create();
}
/**
* Creates a new min-max priority queue using natural order, no maximum size,
* and initially containing the given elements.
*/
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create(
Iterable<? extends E> initialContents) {
return new Builder<E>(Ordering.<E>natural()).create(initialContents);
}
/**
* Creates and returns a new builder, configured to build {@code
* MinMaxPriorityQueue} instances that use {@code comparator} to determine the
* least and greatest elements.
*/
public static <B> Builder<B> orderedBy(Comparator<B> comparator) {
return new Builder<B>(comparator);
}
/**
* Creates and returns a new builder, configured to build {@code
* MinMaxPriorityQueue} instances sized appropriately to hold {@code
* expectedSize} elements.
*/
public static Builder<Comparable> expectedSize(int expectedSize) {
return new Builder<Comparable>(Ordering.natural())
.expectedSize(expectedSize);
}
/**
* Creates and returns a new builder, configured to build {@code
* MinMaxPriorityQueue} instances that are limited to {@code maximumSize}
* elements. Each time a queue grows beyond this bound, it immediately
* removes its greatest element (according to its comparator), which might be
* the element that was just added.
*/
public static Builder<Comparable> maximumSize(int maximumSize) {
return new Builder<Comparable>(Ordering.natural())
.maximumSize(maximumSize);
}
/**
* The builder class used in creation of min-max priority queues. Instead of
* constructing one directly, use {@link
* MinMaxPriorityQueue#orderedBy(Comparator)}, {@link
* MinMaxPriorityQueue#expectedSize(int)} or {@link
* MinMaxPriorityQueue#maximumSize(int)}.
*
* @param <B> the upper bound on the eventual type that can be produced by
* this builder (for example, a {@code Builder<Number>} can produce a
* {@code Queue<Number>} or {@code Queue<Integer>} but not a {@code
* Queue<Object>}).
* @since 8.0
*/
@Beta
public static final class Builder<B> {
/*
* TODO(kevinb): when the dust settles, see if we still need this or can
* just default to DEFAULT_CAPACITY.
*/
private static final int UNSET_EXPECTED_SIZE = -1;
private final Comparator<B> comparator;
private int expectedSize = UNSET_EXPECTED_SIZE;
private int maximumSize = Integer.MAX_VALUE;
private Builder(Comparator<B> comparator) {
this.comparator = checkNotNull(comparator);
}
/**
* Configures this builder to build min-max priority queues with an initial
* expected size of {@code expectedSize}.
*/
public Builder<B> expectedSize(int expectedSize) {
checkArgument(expectedSize >= 0);
this.expectedSize = expectedSize;
return this;
}
/**
* Configures this builder to build {@code MinMaxPriorityQueue} instances
* that are limited to {@code maximumSize} elements. Each time a queue grows
* beyond this bound, it immediately removes its greatest element (according
* to its comparator), which might be the element that was just added.
*/
public Builder<B> maximumSize(int maximumSize) {
checkArgument(maximumSize > 0);
this.maximumSize = maximumSize;
return this;
}
/**
* Builds a new min-max priority queue using the previously specified
* options, and having no initial contents.
*/
public <T extends B> MinMaxPriorityQueue<T> create() {
return create(Collections.<T>emptySet());
}
/**
* Builds a new min-max priority queue using the previously specified
* options, and having the given initial elements.
*/
public <T extends B> MinMaxPriorityQueue<T> create(
Iterable<? extends T> initialContents) {
MinMaxPriorityQueue<T> queue = new MinMaxPriorityQueue<T>(
this, initialQueueSize(expectedSize, maximumSize, initialContents));
for (T element : initialContents) {
queue.offer(element);
}
return queue;
}
@SuppressWarnings("unchecked") // safe "contravariant cast"
private <T extends B> Ordering<T> ordering() {
return Ordering.from((Comparator<T>) comparator);
}
}
private final Heap minHeap;
private final Heap maxHeap;
@VisibleForTesting final int maximumSize;
private Object[] queue;
private int size;
private int modCount;
private MinMaxPriorityQueue(Builder<? super E> builder, int queueSize) {
Ordering<E> ordering = builder.ordering();
this.minHeap = new Heap(ordering);
this.maxHeap = new Heap(ordering.reverse());
minHeap.otherHeap = maxHeap;
maxHeap.otherHeap = minHeap;
this.maximumSize = builder.maximumSize;
// TODO(kevinb): pad?
this.queue = new Object[queueSize];
}
@Override public int size() {
return size;
}
/**
* Adds the given element to this queue. If this queue has a maximum size,
* after adding {@code element} the queue will automatically evict its
* greatest element (according to its comparator), which may be {@code
* element} itself.
*
* @return {@code true} always
*/
@Override public boolean add(E element) {
offer(element);
return true;
}
@Override public boolean addAll(Collection<? extends E> newElements) {
boolean modified = false;
for (E element : newElements) {
offer(element);
modified = true;
}
return modified;
}
/**
* Adds the given element to this queue. If this queue has a maximum size,
* after adding {@code element} the queue will automatically evict its
* greatest element (according to its comparator), which may be {@code
* element} itself.
*/
@Override public boolean offer(E element) {
checkNotNull(element);
modCount++;
int insertIndex = size++;
growIfNeeded();
// Adds the element to the end of the heap and bubbles it up to the correct
// position.
heapForIndex(insertIndex).bubbleUp(insertIndex, element);
return size <= maximumSize || pollLast() != element;
}
@Override public E poll() {
return isEmpty() ? null : removeAndGet(0);
}
@SuppressWarnings("unchecked") // we must carefully only allow Es to get in
E elementData(int index) {
return (E) queue[index];
}
@Override public E peek() {
return isEmpty() ? null : elementData(0);
}
/**
* Returns the index of the max element.
*/
private int getMaxElementIndex() {
switch (size) {
case 1:
return 0; // The lone element in the queue is the maximum.
case 2:
return 1; // The lone element in the maxHeap is the maximum.
default:
// The max element must sit on the first level of the maxHeap. It is
// actually the *lesser* of the two from the maxHeap's perspective.
return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2;
}
}
/**
* Removes and returns the least element of this queue, or returns {@code
* null} if the queue is empty.
*/
public E pollFirst() {
return poll();
}
/**
* Removes and returns the least element of this queue.
*
* @throws NoSuchElementException if the queue is empty
*/
public E removeFirst() {
return remove();
}
/**
* Retrieves, but does not remove, the least element of this queue, or returns
* {@code null} if the queue is empty.
*/
public E peekFirst() {
return peek();
}
/**
* Removes and returns the greatest element of this queue, or returns {@code
* null} if the queue is empty.
*/
public E pollLast() {
return isEmpty() ? null : removeAndGet(getMaxElementIndex());
}
/**
* Removes and returns the greatest element of this queue.
*
* @throws NoSuchElementException if the queue is empty
*/
public E removeLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return removeAndGet(getMaxElementIndex());
}
/**
* Retrieves, but does not remove, the greatest element of this queue, or
* returns {@code null} if the queue is empty.
*/
public E peekLast() {
return isEmpty() ? null : elementData(getMaxElementIndex());
}
/**
* Removes the element at position {@code index}.
*
* <p>Normally this method leaves the elements at up to {@code index - 1},
* inclusive, untouched. Under these circumstances, it returns {@code null}.
*
* <p>Occasionally, in order to maintain the heap invariant, it must swap a
* later element of the list with one before {@code index}. Under these
* circumstances it returns a pair of elements as a {@link MoveDesc}. The
* first one is the element that was previously at the end of the heap and is
* now at some position before {@code index}. The second element is the one
* that was swapped down to replace the element at {@code index}. This fact is
* used by iterator.remove so as to visit elements during a traversal once and
* only once.
*/
@VisibleForTesting MoveDesc<E> removeAt(int index) {
checkPositionIndex(index, size);
modCount++;
size--;
if (size == index) {
queue[size] = null;
return null;
}
E actualLastElement = elementData(size);
int lastElementAt = heapForIndex(size)
.getCorrectLastElement(actualLastElement);
E toTrickle = elementData(size);
queue[size] = null;
MoveDesc<E> changes = fillHole(index, toTrickle);
if (lastElementAt < index) {
// Last element is moved to before index, swapped with trickled element.
if (changes == null) {
// The trickled element is still after index.
return new MoveDesc<E>(actualLastElement, toTrickle);
} else {
// The trickled element is back before index, but the replaced element
// has now been moved after index.
return new MoveDesc<E>(actualLastElement, changes.replaced);
}
}
// Trickled element was after index to begin with, no adjustment needed.
return changes;
}
private MoveDesc<E> fillHole(int index, E toTrickle) {
Heap heap = heapForIndex(index);
// We consider elementData(index) a "hole", and we want to fill it
// with the last element of the heap, toTrickle.
// Since the last element of the heap is from the bottom level, we
// optimistically fill index position with elements from lower levels,
// moving the hole down. In most cases this reduces the number of
// comparisons with toTrickle, but in some cases we will need to bubble it
// all the way up again.
int vacated = heap.fillHoleAt(index);
// Try to see if toTrickle can be bubbled up min levels.
int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle);
if (bubbledTo == vacated) {
// Could not bubble toTrickle up min levels, try moving
// it from min level to max level (or max to min level) and bubble up
// there.
return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle);
} else {
return (bubbledTo < index)
? new MoveDesc<E>(toTrickle, elementData(index))
: null;
}
}
// Returned from removeAt() to iterator.remove()
static class MoveDesc<E> {
final E toTrickle;
final E replaced;
MoveDesc(E toTrickle, E replaced) {
this.toTrickle = toTrickle;
this.replaced = replaced;
}
}
/**
* Removes and returns the value at {@code index}.
*/
private E removeAndGet(int index) {
E value = elementData(index);
removeAt(index);
return value;
}
private Heap heapForIndex(int i) {
return isEvenLevel(i) ? minHeap : maxHeap;
}
private static final int EVEN_POWERS_OF_TWO = 0x55555555;
private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa;
@VisibleForTesting static boolean isEvenLevel(int index) {
int oneBased = index + 1;
checkState(oneBased > 0, "negative index");
return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO);
}
/**
* Returns {@code true} if the MinMax heap structure holds. This is only used
* in testing.
*
* TODO(kevinb): move to the test class?
*/
@VisibleForTesting boolean isIntact() {
for (int i = 1; i < size; i++) {
if (!heapForIndex(i).verifyIndex(i)) {
return false;
}
}
return true;
}
/**
* Each instance of MinMaxPriortyQueue encapsulates two instances of Heap:
* a min-heap and a max-heap. Conceptually, these might each have their own
* array for storage, but for efficiency's sake they are stored interleaved on
* alternate heap levels in the same array (MMPQ.queue).
*/
private class Heap {
final Ordering<E> ordering;
Heap otherHeap;
Heap(Ordering<E> ordering) {
this.ordering = ordering;
}
int compareElements(int a, int b) {
return ordering.compare(elementData(a), elementData(b));
}
/**
* Tries to move {@code toTrickle} from a min to a max level and
* bubble up there. If it moved before {@code removeIndex} this method
* returns a pair as described in {@link #removeAt}.
*/
MoveDesc<E> tryCrossOverAndBubbleUp(
int removeIndex, int vacated, E toTrickle) {
int crossOver = crossOver(vacated, toTrickle);
if (crossOver == vacated) {
return null;
}
// Successfully crossed over from min to max.
// Bubble up max levels.
E parent;
// If toTrickle is moved up to a parent of removeIndex, the parent is
// placed in removeIndex position. We must return that to the iterator so
// that it knows to skip it.
if (crossOver < removeIndex) {
// We crossed over to the parent level in crossOver, so the parent
// has already been moved.
parent = elementData(removeIndex);
} else {
parent = elementData(getParentIndex(removeIndex));
}
// bubble it up the opposite heap
if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle)
< removeIndex) {
return new MoveDesc<E>(toTrickle, parent);
} else {
return null;
}
}
/**
* Bubbles a value from {@code index} up the appropriate heap if required.
*/
void bubbleUp(int index, E x) {
int crossOver = crossOverUp(index, x);
Heap heap;
if (crossOver == index) {
heap = this;
} else {
index = crossOver;
heap = otherHeap;
}
heap.bubbleUpAlternatingLevels(index, x);
}
/**
* Bubbles a value from {@code index} up the levels of this heap, and
* returns the index the element ended up at.
*/
int bubbleUpAlternatingLevels(int index, E x) {
while (index > 2) {
int grandParentIndex = getGrandparentIndex(index);
E e = elementData(grandParentIndex);
if (ordering.compare(e, x) <= 0) {
break;
}
queue[index] = e;
index = grandParentIndex;
}
queue[index] = x;
return index;
}
/**
* Returns the index of minimum value between {@code index} and
* {@code index + len}, or {@code -1} if {@code index} is greater than
* {@code size}.
*/
int findMin(int index, int len) {
if (index >= size) {
return -1;
}
checkState(index > 0);
int limit = Math.min(index, size - len) + len;
int minIndex = index;
for (int i = index + 1; i < limit; i++) {
if (compareElements(i, minIndex) < 0) {
minIndex = i;
}
}
return minIndex;
}
/**
* Returns the minimum child or {@code -1} if no child exists.
*/
int findMinChild(int index) {
return findMin(getLeftChildIndex(index), 2);
}
/**
* Returns the minimum grand child or -1 if no grand child exists.
*/
int findMinGrandChild(int index) {
int leftChildIndex = getLeftChildIndex(index);
if (leftChildIndex < 0) {
return -1;
}
return findMin(getLeftChildIndex(leftChildIndex), 4);
}
/**
* Moves an element one level up from a min level to a max level
* (or vice versa).
* Returns the new position of the element.
*/
int crossOverUp(int index, E x) {
if (index == 0) {
queue[0] = x;
return 0;
}
int parentIndex = getParentIndex(index);
E parentElement = elementData(parentIndex);
if (parentIndex != 0) {
// This is a guard for the case of the childless uncle.
// Since the end of the array is actually the middle of the heap,
// a smaller childless uncle can become a child of x when we
// bubble up alternate levels, violating the invariant.
int grandparentIndex = getParentIndex(parentIndex);
int uncleIndex = getRightChildIndex(grandparentIndex);
if (uncleIndex != parentIndex
&& getLeftChildIndex(uncleIndex) >= size) {
E uncleElement = elementData(uncleIndex);
if (ordering.compare(uncleElement, parentElement) < 0) {
parentIndex = uncleIndex;
parentElement = uncleElement;
}
}
}
if (ordering.compare(parentElement, x) < 0) {
queue[index] = parentElement;
queue[parentIndex] = x;
return parentIndex;
}
queue[index] = x;
return index;
}
/**
* Returns the conceptually correct last element of the heap.
*
* <p>Since the last element of the array is actually in the
* middle of the sorted structure, a childless uncle node could be
* smaller, which would corrupt the invariant if this element
* becomes the new parent of the uncle. In that case, we first
* switch the last element with its uncle, before returning.
*/
int getCorrectLastElement(E actualLastElement) {
int parentIndex = getParentIndex(size);
if (parentIndex != 0) {
int grandparentIndex = getParentIndex(parentIndex);
int uncleIndex = getRightChildIndex(grandparentIndex);
if (uncleIndex != parentIndex
&& getLeftChildIndex(uncleIndex) >= size) {
E uncleElement = elementData(uncleIndex);
if (ordering.compare(uncleElement, actualLastElement) < 0) {
queue[uncleIndex] = actualLastElement;
queue[size] = uncleElement;
return uncleIndex;
}
}
}
return size;
}
/**
* Crosses an element over to the opposite heap by moving it one level down
* (or up if there are no elements below it).
*
* Returns the new position of the element.
*/
int crossOver(int index, E x) {
int minChildIndex = findMinChild(index);
// TODO(kevinb): split the && into two if's and move crossOverUp so it's
// only called when there's no child.
if ((minChildIndex > 0)
&& (ordering.compare(elementData(minChildIndex), x) < 0)) {
queue[index] = elementData(minChildIndex);
queue[minChildIndex] = x;
return minChildIndex;
}
return crossOverUp(index, x);
}
/**
* Fills the hole at {@code index} by moving in the least of its
* grandchildren to this position, then recursively filling the new hole
* created.
*
* @return the position of the new hole (where the lowest grandchild moved
* from, that had no grandchild to replace it)
*/
int fillHoleAt(int index) {
int minGrandchildIndex;
while ((minGrandchildIndex = findMinGrandChild(index)) > 0) {
queue[index] = elementData(minGrandchildIndex);
index = minGrandchildIndex;
}
return index;
}
private boolean verifyIndex(int i) {
if ((getLeftChildIndex(i) < size)
&& (compareElements(i, getLeftChildIndex(i)) > 0)) {
return false;
}
if ((getRightChildIndex(i) < size)
&& (compareElements(i, getRightChildIndex(i)) > 0)) {
return false;
}
if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) {
return false;
}
if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) {
return false;
}
return true;
}
// These would be static if inner classes could have static members.
private int getLeftChildIndex(int i) {
return i * 2 + 1;
}
private int getRightChildIndex(int i) {
return i * 2 + 2;
}
private int getParentIndex(int i) {
return (i - 1) / 2;
}
private int getGrandparentIndex(int i) {
return getParentIndex(getParentIndex(i)); // (i - 3) / 4
}
}
/**
* Iterates the elements of the queue in no particular order.
*
* If the underlying queue is modified during iteration an exception will be
* thrown.
*/
private class QueueIterator implements Iterator<E> {
private int cursor = -1;
private int expectedModCount = modCount;
// TODO(user): Switch to ArrayDeque once Guava supports it.
private Queue<E> forgetMeNot;
private List<E> skipMe;
private E lastFromForgetMeNot;
private boolean canRemove;
@Override public boolean hasNext() {
checkModCount();
return (nextNotInSkipMe(cursor + 1) < size())
|| ((forgetMeNot != null) && !forgetMeNot.isEmpty());
}
@Override public E next() {
checkModCount();
int tempCursor = nextNotInSkipMe(cursor + 1);
if (tempCursor < size()) {
cursor = tempCursor;
canRemove = true;
return elementData(cursor);
} else if (forgetMeNot != null) {
cursor = size();
lastFromForgetMeNot = forgetMeNot.poll();
if (lastFromForgetMeNot != null) {
canRemove = true;
return lastFromForgetMeNot;
}
}
throw new NoSuchElementException(
"iterator moved past last element in queue.");
}
@Override public void remove() {
checkState(canRemove,
"no calls to remove() since the last call to next()");
checkModCount();
canRemove = false;
expectedModCount++;
if (cursor < size()) {
MoveDesc<E> moved = removeAt(cursor);
if (moved != null) {
if (forgetMeNot == null) {
forgetMeNot = new LinkedList<E>();
skipMe = new ArrayList<E>(3);
}
forgetMeNot.add(moved.toTrickle);
skipMe.add(moved.replaced);
}
cursor--;
} else { // we must have set lastFromForgetMeNot in next()
checkState(removeExact(lastFromForgetMeNot));
lastFromForgetMeNot = null;
}
}
// Finds only this exact instance, not others that are equals()
private boolean containsExact(Iterable<E> elements, E target) {
for (E element : elements) {
if (element == target) {
return true;
}
}
return false;
}
// Removes only this exact instance, not others that are equals()
boolean removeExact(Object target) {
for (int i = 0; i < size; i++) {
if (queue[i] == target) {
removeAt(i);
return true;
}
}
return false;
}
void checkModCount() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* Returns the index of the first element after {@code c} that is not in
* {@code skipMe} and returns {@code size()} if there is no such element.
*/
private int nextNotInSkipMe(int c) {
if (skipMe != null) {
while (c < size() && containsExact(skipMe, elementData(c))) {
c++;
}
}
return c;
}
}
/**
* Returns an iterator over the elements contained in this collection,
* <i>in no particular order</i>.
*
* <p>The iterator is <i>fail-fast</i>: If the MinMaxPriorityQueue is modified
* at any time after the iterator is created, in any way except through the
* iterator's own remove method, the iterator will generally throw a
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw {@code ConcurrentModificationException} on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* @return an iterator over the elements contained in this collection
*/
@Override public Iterator<E> iterator() {
return new QueueIterator();
}
@Override public void clear() {
for (int i = 0; i < size; i++) {
queue[i] = null;
}
size = 0;
}
@Override public Object[] toArray() {
Object[] copyTo = new Object[size];
System.arraycopy(queue, 0, copyTo, 0, size);
return copyTo;
}
/**
* Returns the comparator used to order the elements in this queue. Obeys the
* general contract of {@link PriorityQueue#comparator}, but returns {@link
* Ordering#natural} instead of {@code null} to indicate natural ordering.
*/
public Comparator<? super E> comparator() {
return minHeap.ordering;
}
@VisibleForTesting int capacity() {
return queue.length;
}
// Size/capacity-related methods
private static final int DEFAULT_CAPACITY = 11;
@VisibleForTesting static int initialQueueSize(int configuredExpectedSize,
int maximumSize, Iterable<?> initialContents) {
// Start with what they said, if they said it, otherwise DEFAULT_CAPACITY
int result = (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE)
? DEFAULT_CAPACITY
: configuredExpectedSize;
// Enlarge to contain initial contents
if (initialContents instanceof Collection) {
int initialSize = ((Collection<?>) initialContents).size();
result = Math.max(result, initialSize);
}
// Now cap it at maxSize + 1
return capAtMaximumSize(result, maximumSize);
}
private void growIfNeeded() {
if (size > queue.length) {
int newCapacity = calculateNewCapacity();
Object[] newQueue = new Object[newCapacity];
System.arraycopy(queue, 0, newQueue, 0, queue.length);
queue = newQueue;
}
}
/** Returns ~2x the old capacity if small; ~1.5x otherwise. */
private int calculateNewCapacity() {
int oldCapacity = queue.length;
int newCapacity = (oldCapacity < 64)
? (oldCapacity + 1) * 2
: IntMath.checkedMultiply(oldCapacity / 2, 3);
return capAtMaximumSize(newCapacity, maximumSize);
}
/** There's no reason for the queueSize to ever be more than maxSize + 1 */
private static int capAtMaximumSize(int queueSize, int maximumSize) {
return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow
}
}
| 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) 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) 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 empty immutable map.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
final class EmptyImmutableMap extends ImmutableMap<Object, Object> {
static final EmptyImmutableMap INSTANCE = new EmptyImmutableMap();
private EmptyImmutableMap() {}
@Override public Object get(@Nullable Object key) {
return null;
}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean containsKey(@Nullable Object key) {
return false;
}
@Override public boolean containsValue(@Nullable Object value) {
return false;
}
@Override public ImmutableSet<Entry<Object, Object>> entrySet() {
return ImmutableSet.of();
}
@Override public ImmutableSet<Object> keySet() {
return ImmutableSet.of();
}
@Override public ImmutableCollection<Object> values() {
return ImmutableCollection.EMPTY_IMMUTABLE_COLLECTION;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Map) {
Map<?, ?> that = (Map<?, ?>) object;
return that.isEmpty();
}
return false;
}
@Override boolean isPartialView() {
return false;
}
@Override public int hashCode() {
return 0;
}
@Override public String toString() {
return "{}";
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
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) 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) 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.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@code Multimap} that can hold duplicate key-value pairs and that maintains
* the insertion ordering of values for a given key.
*
* <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods
* each return a {@link List} of values. Though the method signature doesn't say
* so explicitly, the map returned by {@link #asMap} has {@code List} 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 ListMultimap<K, V> extends Multimap<K, V> {
/**
* {@inheritDoc}
*
* <p>Because the values for a given key may have duplicates and follow the
* insertion ordering, this method returns a {@link List}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
List<V> get(@Nullable K key);
/**
* {@inheritDoc}
*
* <p>Because the values for a given key may have duplicates and follow the
* insertion ordering, this method returns a {@link List}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
List<V> removeAll(@Nullable Object key);
/**
* {@inheritDoc}
*
* <p>Because the values for a given key may have duplicates and follow the
* insertion ordering, this method returns a {@link List}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
List<V> replaceValues(K key, Iterable<? extends V> values);
/**
* {@inheritDoc}
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link List} values.
*/
@Override
Map<K, Collection<V>> asMap();
/**
* Compares the specified object to this multimap for equality.
*
* <p>Two {@code ListMultimap} instances are equal if, for each key, they
* contain the same values in the same order. If the value orderings disagree,
* the multimaps will not be considered equal.
*
* <p>An empty {@code ListMultimap} is equal to any other empty {@code
* Multimap}, including an empty {@code SetMultimap}.
*/
@Override
boolean equals(@Nullable Object obj);
}
| 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 java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and
* a {@code HashMap} instance for values-to-keys. Null keys are not permitted,
* but null values are. An {@code EnumHashBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumHashBiMap<K extends Enum<K>, V>
extends AbstractBiMap<K, V> {
private transient Class<K> keyType;
/**
* Returns a new, empty {@code EnumHashBiMap} using the specified key type.
*
* @param keyType the key type
*/
public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
create(Class<K> keyType) {
return new EnumHashBiMap<K, V>(keyType);
}
/**
* Constructs a new bimap with the same mappings as the specified map. If the
* specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new
* bimap has the same key type as the input bimap. Otherwise, the specified
* map must contain at least one mapping, in order to determine the key type.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an
* {@code EnumHashBiMap} instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
create(Map<K, ? extends V> map) {
EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
bimap.putAll(map);
return bimap;
}
private EnumHashBiMap(Class<K> keyType) {
super(WellBehavedMap.wrap(
new EnumMap<K, V>(keyType)),
Maps.<V, K>newHashMapWithExpectedSize(
keyType.getEnumConstants().length));
this.keyType = keyType;
}
// Overriding these three methods to show that values may be null (but not keys)
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override public V put(K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(K key, @Nullable V value) {
return super.forcePut(key, value);
}
/** Returns the associated key type. */
public Class<K> keyType() {
return keyType;
}
/**
* @serialData the key class, number of entries, first key, first value,
* second key, second value, and so on.
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyType);
Serialization.writeMap(this, stream);
}
@SuppressWarnings("unchecked") // reading field populated by writeObject
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyType = (Class<K>) stream.readObject();
setDelegates(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
Serialization.populateMap(this, stream);
}
@GwtIncompatible("only 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 static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.Beta;
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)
@Beta
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) 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 static com.google.common.collect.BoundType.OPEN;
import java.io.Serializable;
import java.util.Comparator;
import javax.annotation.Nullable;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
/**
* A generalized interval on any ordering, for internal use. Supports {@code null}. Unlike
* {@link Range}, this allows the use of an arbitrary comparator. This is designed for use in the
* implementation of subcollections of sorted collection types.
*
* <p>Whenever possible, use {@code Range} instead, which is better supported.
*
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
final class GeneralRange<T> implements Serializable {
/**
* Converts a Range to a GeneralRange.
*/
static <T extends Comparable> GeneralRange<T> from(Range<T> range) {
@Nullable
T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null;
BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN;
@Nullable
T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null;
BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN;
return new GeneralRange<T>(Ordering.natural(), range.hasLowerBound(), lowerEndpoint,
lowerBoundType, range.hasUpperBound(), upperEndpoint, upperBoundType);
}
/**
* Returns the whole range relative to the specified comparator.
*/
static <T> GeneralRange<T> all(Comparator<? super T> comparator) {
return new GeneralRange<T>(comparator, false, null, OPEN, false, null, OPEN);
}
/**
* Returns everything above the endpoint relative to the specified comparator, with the specified
* endpoint behavior.
*/
static <T> GeneralRange<T> downTo(Comparator<? super T> comparator, @Nullable T endpoint,
BoundType boundType) {
return new GeneralRange<T>(comparator, true, endpoint, boundType, false, null, OPEN);
}
/**
* Returns everything below the endpoint relative to the specified comparator, with the specified
* endpoint behavior.
*/
static <T> GeneralRange<T> upTo(Comparator<? super T> comparator, @Nullable T endpoint,
BoundType boundType) {
return new GeneralRange<T>(comparator, false, null, OPEN, true, endpoint, boundType);
}
/**
* Returns everything between the endpoints relative to the specified comparator, with the
* specified endpoint behavior.
*/
static <T> GeneralRange<T> range(Comparator<? super T> comparator, @Nullable T lower,
BoundType lowerType, @Nullable T upper, BoundType upperType) {
return new GeneralRange<T>(comparator, true, lower, lowerType, true, upper, upperType);
}
private final Comparator<? super T> comparator;
private final boolean hasLowerBound;
@Nullable
private final T lowerEndpoint;
private final BoundType lowerBoundType;
private final boolean hasUpperBound;
@Nullable
private final T upperEndpoint;
private final BoundType upperBoundType;
private GeneralRange(Comparator<? super T> comparator, boolean hasLowerBound,
@Nullable T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound,
@Nullable T upperEndpoint, BoundType upperBoundType) {
this.comparator = checkNotNull(comparator);
this.hasLowerBound = hasLowerBound;
this.hasUpperBound = hasUpperBound;
this.lowerEndpoint = lowerEndpoint;
this.lowerBoundType = checkNotNull(lowerBoundType);
this.upperEndpoint = upperEndpoint;
this.upperBoundType = checkNotNull(upperBoundType);
if (hasLowerBound) {
comparator.compare(lowerEndpoint, lowerEndpoint);
}
if (hasUpperBound) {
comparator.compare(upperEndpoint, upperEndpoint);
}
if (hasLowerBound && hasUpperBound) {
int cmp = comparator.compare(lowerEndpoint, upperEndpoint);
// be consistent with Range
checkArgument(cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint,
upperEndpoint);
if (cmp == 0) {
checkArgument(lowerBoundType != OPEN | upperBoundType != OPEN);
}
}
}
Comparator<? super T> comparator() {
return comparator;
}
boolean hasLowerBound() {
return hasLowerBound;
}
boolean hasUpperBound() {
return hasUpperBound;
}
boolean isEmpty() {
return (hasUpperBound() && tooLow(upperEndpoint))
|| (hasLowerBound() && tooHigh(lowerEndpoint));
}
boolean tooLow(@Nullable T t) {
if (!hasLowerBound()) {
return false;
}
T lbound = lowerEndpoint;
int cmp = comparator.compare(t, lbound);
return cmp < 0 | (cmp == 0 & lowerBoundType == OPEN);
}
boolean tooHigh(@Nullable T t) {
if (!hasUpperBound()) {
return false;
}
T ubound = upperEndpoint;
int cmp = comparator.compare(t, ubound);
return cmp > 0 | (cmp == 0 & upperBoundType == OPEN);
}
boolean contains(@Nullable T t) {
return !tooLow(t) && !tooHigh(t);
}
/**
* Returns the intersection of the two ranges, or an empty range if their intersection is empty.
*/
GeneralRange<T> intersect(GeneralRange<T> other) {
checkNotNull(other);
checkArgument(comparator.equals(other.comparator));
boolean hasLowBound = this.hasLowerBound;
@Nullable
T lowEnd = lowerEndpoint;
BoundType lowType = lowerBoundType;
if (!hasLowerBound()) {
hasLowBound = other.hasLowerBound;
lowEnd = other.lowerEndpoint;
lowType = other.lowerBoundType;
} else if (other.hasLowerBound()) {
int cmp = comparator.compare(lowerEndpoint, other.lowerEndpoint);
if (cmp < 0 || (cmp == 0 && other.lowerBoundType == OPEN)) {
lowEnd = other.lowerEndpoint;
lowType = other.lowerBoundType;
}
}
boolean hasUpBound = this.hasUpperBound;
@Nullable
T upEnd = upperEndpoint;
BoundType upType = upperBoundType;
if (!hasUpperBound()) {
hasUpBound = other.hasUpperBound;
upEnd = other.upperEndpoint;
upType = other.upperBoundType;
} else if (other.hasUpperBound()) {
int cmp = comparator.compare(upperEndpoint, other.upperEndpoint);
if (cmp > 0 || (cmp == 0 && other.upperBoundType == OPEN)) {
upEnd = other.upperEndpoint;
upType = other.upperBoundType;
}
}
if (hasLowBound && hasUpBound) {
int cmp = comparator.compare(lowEnd, upEnd);
if (cmp > 0 || (cmp == 0 && lowType == OPEN && upType == OPEN)) {
// force allowed empty range
lowEnd = upEnd;
lowType = OPEN;
upType = CLOSED;
}
}
return new GeneralRange<T>(comparator, hasLowBound, lowEnd, lowType, hasUpBound, upEnd, upType);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof GeneralRange) {
GeneralRange<?> r = (GeneralRange<?>) obj;
return comparator.equals(r.comparator) && hasLowerBound == r.hasLowerBound
&& hasUpperBound == r.hasUpperBound && lowerBoundType.equals(r.lowerBoundType)
&& upperBoundType.equals(r.upperBoundType)
&& Objects.equal(lowerEndpoint, r.lowerEndpoint)
&& Objects.equal(upperEndpoint, r.upperEndpoint);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(comparator, lowerEndpoint, lowerBoundType, upperEndpoint,
upperBoundType);
}
private transient GeneralRange<T> reverse;
/**
* Returns the same range relative to the reversed comparator.
*/
public GeneralRange<T> reverse() {
GeneralRange<T> result = reverse;
if (result == null) {
result =
new GeneralRange<T>(Ordering.from(comparator).reverse(), hasUpperBound, upperEndpoint,
upperBoundType, hasLowerBound, lowerEndpoint, lowerBoundType);
result.reverse = this;
return this.reverse = result;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(comparator).append(":");
switch (lowerBoundType) {
case CLOSED:
builder.append('[');
break;
case OPEN:
builder.append('(');
break;
}
if (hasLowerBound()) {
builder.append(lowerEndpoint);
} else {
builder.append("-\u221e");
}
builder.append(',');
if (hasUpperBound()) {
builder.append(upperEndpoint);
} else {
builder.append("\u221e");
}
switch (upperBoundType) {
case CLOSED:
builder.append(']');
break;
case OPEN:
builder.append(')');
break;
}
return builder.toString();
}
}
| 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.primitives.Ints;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An immutable hash-based multiset. Does not permit null elements.
*
* <p>Its iterator orders elements according to the first appearance of the
* element among the items passed to the factory method or builder. When the
* multiset contains multiple instances of an element, those instances are
* consecutive in the iteration order.
*
* <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
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial") // we're overriding default serialization
// TODO(user): write an efficient asList() implementation
public abstract class ImmutableMultiset<E> extends ImmutableCollection<E>
implements Multiset<E> {
/**
* Returns the empty immutable multiset.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static <E> ImmutableMultiset<E> of() {
return (ImmutableMultiset<E>) EmptyImmutableMultiset.INSTANCE;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if {@code element} is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") // generic array created but never written
public static <E> ImmutableMultiset<E> of(E element) {
return copyOfInternal(element);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2) {
return copyOfInternal(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
return copyOfInternal(e1, e2, e3);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
return copyOfInternal(e1, e2, e3, e4);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
return copyOfInternal(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
int size = others.length + 6;
List<E> all = new ArrayList<E>(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, others);
return copyOf(all);
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.of(2, 3, 1, 3)} yields a multiset with
* elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
* @deprecated use {@link #copyOf(Object[])}. <b>This method is scheduled for
* deletion in January 2012.</b>
* @since 2.0 (changed from varargs in 6.0)
*/
@Deprecated
public static <E> ImmutableMultiset<E> of(E[] elements) {
return copyOf(Arrays.asList(elements));
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset
* with elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 6.0
*/
public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
return copyOf(Arrays.asList(elements));
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields
* a multiset with elements in the order {@code 2, 3, 3, 1}.
*
* <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.
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code elements}
* is an {@code ImmutableMultiset}, no copy will actually be performed, and
* the given multiset itself will be returned.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableMultiset<E> copyOf(
Iterable<? extends E> elements) {
if (elements instanceof ImmutableMultiset) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
if (!result.isPartialView()) {
return result;
}
}
Multiset<? extends E> multiset = (elements instanceof Multiset)
? Multisets.cast(elements)
: LinkedHashMultiset.create(elements);
return copyOfInternal(multiset);
}
private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) {
return copyOf(Arrays.asList(elements));
}
private static <E> ImmutableMultiset<E> copyOfInternal(
Multiset<? extends E> multiset) {
return copyFromEntries(multiset.entrySet());
}
static <E> ImmutableMultiset<E> copyFromEntries(
Collection<? extends Entry<? extends E>> entries) {
long size = 0;
ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
for (Entry<? extends E> entry : entries) {
int count = entry.getCount();
if (count > 0) {
// Since ImmutableMap.Builder throws an NPE if an element is null, no
// other null checks are needed.
builder.put(entry.getElement(), count);
size += count;
}
}
if (size == 0) {
return of();
}
return new RegularImmutableMultiset<E>(builder.build(), Ints.saturatedCast(size));
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example,
* {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
* yields a multiset with elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableMultiset<E> copyOf(
Iterator<? extends E> elements) {
Multiset<E> multiset = LinkedHashMultiset.create();
Iterators.addAll(multiset, elements);
return copyOfInternal(multiset);
}
ImmutableMultiset() {}
@Override public UnmodifiableIterator<E> iterator() {
final Iterator<Entry<E>> entryIterator = entryIterator();
return new UnmodifiableIterator<E>() {
int remaining;
E element;
@Override
public boolean hasNext() {
return (remaining > 0) || entryIterator.hasNext();
}
@Override
public E next() {
if (remaining <= 0) {
Entry<E> entry = entryIterator.next();
element = entry.getElement();
remaining = entry.getCount();
}
remaining--;
return element;
}
};
}
@Override
public boolean contains(@Nullable Object object) {
return count(object) > 0;
}
@Override
public boolean containsAll(Collection<?> targets) {
return elementSet().containsAll(targets);
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public final boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multiset) {
Multiset<?> that = (Multiset<?>) object;
if (this.size() != that.size()) {
return false;
}
for (Entry<?> entry : that.entrySet()) {
if (count(entry.getElement()) != entry.getCount()) {
return false;
}
}
return true;
}
return false;
}
@Override public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override public String toString() {
return entrySet().toString();
}
private transient ImmutableSet<Entry<E>> entrySet;
@Override
public Set<Entry<E>> entrySet() {
ImmutableSet<Entry<E>> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
abstract UnmodifiableIterator<Entry<E>> entryIterator();
abstract int distinctElements();
ImmutableSet<Entry<E>> createEntrySet() {
return new EntrySet<E>(this);
}
static class EntrySet<E> extends ImmutableSet<Entry<E>> {
transient final ImmutableMultiset<E> multiset;
public EntrySet(ImmutableMultiset<E> multiset) {
this.multiset = multiset;
}
@Override
public UnmodifiableIterator<Entry<E>> iterator() {
return multiset.entryIterator();
}
@Override
public int size() {
return multiset.distinctElements();
}
@Override
boolean isPartialView() {
return multiset.isPartialView();
}
@Override
public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = multiset.count(entry.getElement());
return count == entry.getCount();
}
return false;
}
/*
* TODO(hhchan): Revert once we have a separate, manual emulation of this
* class.
*/
@Override
public Object[] toArray() {
Object[] newArray = new Object[size()];
return toArray(newArray);
}
/*
* TODO(hhchan): Revert once we have a separate, manual emulation of this
* class.
*/
@Override
public <T> T[] toArray(T[] other) {
int size = size();
if (other.length < size) {
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires
Object[] otherAsObjectArray = other;
int index = 0;
for (Entry<?> element : this) {
otherAsObjectArray[index++] = element;
}
return other;
}
@Override
public int hashCode() {
return multiset.hashCode();
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
Object writeReplace() {
return new EntrySetSerializedForm<E>(multiset);
}
static class EntrySetSerializedForm<E> implements Serializable {
final ImmutableMultiset<E> multiset;
EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
this.multiset = multiset;
}
Object readResolve() {
return multiset.entrySet();
}
}
private static final long serialVersionUID = 0;
}
private static class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
SerializedForm(Multiset<?> multiset) {
int distinct = multiset.entrySet().size();
elements = new Object[distinct];
counts = new int[distinct];
int i = 0;
for (Entry<?> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
LinkedHashMultiset<Object> multiset =
LinkedHashMultiset.create(elements.length);
for (int i = 0; i < elements.length; i++) {
multiset.add(elements[i], counts[i]);
}
return ImmutableMultiset.copyOf(multiset);
}
private static final long serialVersionUID = 0;
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
Object writeReplace() {
return new SerializedForm(this);
}
/**
* 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 multiset instances, especially {@code
* public static final} multisets ("constant multisets"). Example:
* <pre> {@code
*
* public static final ImmutableMultiset<Bean> BEANS =
* new ImmutableMultiset.Builder<Bean>()
* .addCopies(Bean.COCOA, 4)
* .addCopies(Bean.GARDEN, 6)
* .addCopies(Bean.RED, 8)
* .addCopies(Bean.BLACK_EYED, 10)
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multisets in series.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
final Multiset<E> contents;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMultiset#builder}.
*/
public Builder() {
this(LinkedHashMultiset.<E>create());
}
Builder(Multiset<E> contents) {
this.contents = contents;
}
/**
* Adds {@code element} to the {@code ImmutableMultiset}.
*
* @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) {
contents.add(checkNotNull(element));
return this;
}
/**
* Adds a number of occurrences of an element to this {@code
* ImmutableMultiset}.
*
* @param element the element to add
* @param occurrences the number of occurrences of the element to add. May
* be zero, in which case no change will be made.
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code occurrences} is negative, or
* if this operation would result in more than {@link Integer#MAX_VALUE}
* occurrences of the element
*/
public Builder<E> addCopies(E element, int occurrences) {
contents.add(checkNotNull(element), occurrences);
return this;
}
/**
* Adds or removes the necessary occurrences of an element such that the
* element attains the desired count.
*
* @param element the element to add or remove occurrences of
* @param count the desired count of the element in this multiset
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code count} is negative
*/
public Builder<E> setCount(E element, int count) {
contents.setCount(checkNotNull(element), count);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @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) {
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the {@code Iterable} to add to the {@code
* ImmutableMultiset}
* @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 Multiset) {
Multiset<? extends E> multiset = Multisets.cast(elements);
for (Entry<? extends E> entry : multiset.entrySet()) {
addCopies(entry.getElement(), entry.getCount());
}
} else {
super.addAll(elements);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add to the {@code ImmutableMultiset}
* @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 ImmutableMultiset} based on the contents
* of the {@code Builder}.
*/
@Override public ImmutableMultiset<E> build() {
return copyOf(contents);
}
}
}
| 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.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedSet;
/**
* Factories and utilities pertaining to the {@link Constraint} interface.
*
* @see MapConstraints
* @author Mike Bostock
* @author Jared Levy
* @since 3.0
*/
@Beta
@GwtCompatible
public final class Constraints {
private Constraints() {}
// enum singleton pattern
private enum NotNullConstraint implements Constraint<Object> {
INSTANCE;
@Override
public Object checkElement(Object element) {
return checkNotNull(element);
}
@Override public String toString() {
return "Not null";
}
}
/**
* Returns a constraint that verifies that the element is not null. If the
* element is null, a {@link NullPointerException} is thrown.
*/
// safe to narrow the type since checkElement returns its argument directly
@SuppressWarnings("unchecked")
public static <E> Constraint<E> notNull() {
return (Constraint<E>) NotNullConstraint.INSTANCE;
}
/**
* Returns a constrained view of the specified collection, using the specified
* constraint. Any operations that add new elements to the collection will
* call the provided constraint. However, this method does not verify that
* existing elements satisfy the constraint.
*
* <p>The returned collection is not serializable.
*
* @param collection the collection to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the collection
*/
public static <E> Collection<E> constrainedCollection(
Collection<E> collection, Constraint<? super E> constraint) {
return new ConstrainedCollection<E>(collection, constraint);
}
/** @see Constraints#constrainedCollection */
static class ConstrainedCollection<E> extends ForwardingCollection<E> {
private final Collection<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedCollection(
Collection<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Collection<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
}
/**
* Returns a constrained view of the specified set, using the specified
* constraint. Any operations that add new elements to the set will call the
* provided constraint. However, this method does not verify that existing
* elements satisfy the constraint.
*
* <p>The returned set is not serializable.
*
* @param set the set to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the set
*/
public static <E> Set<E> constrainedSet(
Set<E> set, Constraint<? super E> constraint) {
return new ConstrainedSet<E>(set, constraint);
}
/** @see Constraints#constrainedSet */
static class ConstrainedSet<E> extends ForwardingSet<E> {
private final Set<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedSet(Set<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Set<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
}
/**
* Returns a constrained view of the specified sorted set, using the specified
* constraint. Any operations that add new elements to the sorted set will
* call the provided constraint. However, this method does not verify that
* existing elements satisfy the constraint.
*
* <p>The returned set is not serializable.
*
* @param sortedSet the sorted set to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the sorted set
*/
public static <E> SortedSet<E> constrainedSortedSet(
SortedSet<E> sortedSet, Constraint<? super E> constraint) {
return new ConstrainedSortedSet<E>(sortedSet, constraint);
}
/** @see Constraints#constrainedSortedSet */
private static class ConstrainedSortedSet<E> extends ForwardingSortedSet<E> {
final SortedSet<E> delegate;
final Constraint<? super E> constraint;
ConstrainedSortedSet(
SortedSet<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected SortedSet<E> delegate() {
return delegate;
}
@Override public SortedSet<E> headSet(E toElement) {
return constrainedSortedSet(delegate.headSet(toElement), constraint);
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return constrainedSortedSet(
delegate.subSet(fromElement, toElement), constraint);
}
@Override public SortedSet<E> tailSet(E fromElement) {
return constrainedSortedSet(delegate.tailSet(fromElement), constraint);
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
}
/**
* Returns a constrained view of the specified list, using the specified
* constraint. Any operations that add new elements to the list will call the
* provided constraint. However, this method does not verify that existing
* elements satisfy the constraint.
*
* <p>If {@code list} implements {@link RandomAccess}, so will the returned
* list. The returned list is not serializable.
*
* @param list the list to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the list
*/
public static <E> List<E> constrainedList(
List<E> list, Constraint<? super E> constraint) {
return (list instanceof RandomAccess)
? new ConstrainedRandomAccessList<E>(list, constraint)
: new ConstrainedList<E>(list, constraint);
}
/** @see Constraints#constrainedList */
@GwtCompatible
private static class ConstrainedList<E> extends ForwardingList<E> {
final List<E> delegate;
final Constraint<? super E> constraint;
ConstrainedList(List<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected List<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public void add(int index, E element) {
constraint.checkElement(element);
delegate.add(index, element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
@Override public boolean addAll(int index, Collection<? extends E> elements)
{
return delegate.addAll(index, checkElements(elements, constraint));
}
@Override public ListIterator<E> listIterator() {
return constrainedListIterator(delegate.listIterator(), constraint);
}
@Override public ListIterator<E> listIterator(int index) {
return constrainedListIterator(delegate.listIterator(index), constraint);
}
@Override public E set(int index, E element) {
constraint.checkElement(element);
return delegate.set(index, element);
}
@Override public List<E> subList(int fromIndex, int toIndex) {
return constrainedList(
delegate.subList(fromIndex, toIndex), constraint);
}
}
/** @see Constraints#constrainedList */
static class ConstrainedRandomAccessList<E> extends ConstrainedList<E>
implements RandomAccess {
ConstrainedRandomAccessList(
List<E> delegate, Constraint<? super E> constraint) {
super(delegate, constraint);
}
}
/**
* Returns a constrained view of the specified list iterator, using the
* specified constraint. Any operations that would add new elements to the
* underlying list will be verified by the constraint.
*
* @param listIterator the iterator for which to return a constrained view
* @param constraint the constraint for elements in the list
* @return a constrained view of the specified iterator
*/
private static <E> ListIterator<E> constrainedListIterator(
ListIterator<E> listIterator, Constraint<? super E> constraint) {
return new ConstrainedListIterator<E>(listIterator, constraint);
}
/** @see Constraints#constrainedListIterator */
static class ConstrainedListIterator<E> extends ForwardingListIterator<E> {
private final ListIterator<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedListIterator(
ListIterator<E> delegate, Constraint<? super E> constraint) {
this.delegate = delegate;
this.constraint = constraint;
}
@Override protected ListIterator<E> delegate() {
return delegate;
}
@Override public void add(E element) {
constraint.checkElement(element);
delegate.add(element);
}
@Override public void set(E element) {
constraint.checkElement(element);
delegate.set(element);
}
}
static <E> Collection<E> constrainedTypePreservingCollection(
Collection<E> collection, Constraint<E> constraint) {
if (collection instanceof SortedSet) {
return constrainedSortedSet((SortedSet<E>) collection, constraint);
} else if (collection instanceof Set) {
return constrainedSet((Set<E>) collection, constraint);
} else if (collection instanceof List) {
return constrainedList((List<E>) collection, constraint);
} else {
return constrainedCollection(collection, constraint);
}
}
/**
* Returns a constrained view of the specified multiset, using the specified
* constraint. Any operations that add new elements to the multiset will call
* the provided constraint. However, this method does not verify that
* existing elements satisfy the constraint.
*
* <p>The returned multiset is not serializable.
*
* @param multiset the multiset to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the multiset
*/
public static <E> Multiset<E> constrainedMultiset(
Multiset<E> multiset, Constraint<? super E> constraint) {
return new ConstrainedMultiset<E>(multiset, constraint);
}
/** @see Constraints#constrainedMultiset */
static class ConstrainedMultiset<E> extends ForwardingMultiset<E> {
private Multiset<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedMultiset(
Multiset<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Multiset<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
return standardAdd(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
@Override public int add(E element, int occurrences) {
constraint.checkElement(element);
return delegate.add(element, occurrences);
}
@Override public int setCount(E element, int count) {
constraint.checkElement(element);
return delegate.setCount(element, count);
}
@Override public boolean setCount(E element, int oldCount, int newCount) {
constraint.checkElement(element);
return delegate.setCount(element, oldCount, newCount);
}
}
/*
* TODO(kevinb): For better performance, avoid making a copy of the elements
* by having addAll() call add() repeatedly instead.
*/
private static <E> Collection<E> checkElements(
Collection<E> elements, Constraint<? super E> constraint) {
Collection<E> copy = Lists.newArrayList(elements);
for (E element : copy) {
constraint.checkElement(element);
}
return copy;
}
}
| 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
*/
final class DescendingImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> {
private final transient ImmutableSortedMultiset<E> forward;
DescendingImmutableSortedMultiset(ImmutableSortedMultiset<E> forward) {
super(forward.reverseComparator());
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
ImmutableSortedSet<E> createElementSet() {
return forward.createDescendingElementSet();
}
@Override
ImmutableSortedSet<E> createDescendingElementSet() {
return forward.elementSet();
}
@Override
UnmodifiableIterator<Entry<E>> descendingEntryIterator() {
return forward.entryIterator();
}
@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
UnmodifiableIterator<Entry<E>> entryIterator() {
return forward.descendingEntryIterator();
}
@Override
int distinctElements() {
return forward.distinctElements();
}
@Override
boolean isPartialView() {
return forward.isPartialView();
}
}
| 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) 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.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2.TransformedCollection;
import com.google.common.collect.Maps.EntryTransformer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
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.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static methods acting on or generating a {@code Multimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multimaps">
* {@code Multimaps}</a>.
*
* @author Jared Levy
* @author Robert Konigsberg
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Multimaps {
private Multimaps() {}
/**
* Creates a new {@code Multimap} that uses the provided map and factory. It
* can generate a multimap based on arbitrary {@link Map} and
* {@link Collection} classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* collections generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link ArrayListMultimap#create()}, {@link HashMultimap#create()},
* {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()},
* {@link TreeMultimap#create()}, and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the collections returned by {@code factory}. Those objects should not be
* manually updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty collections that will each hold all
* values for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> Multimap<K, V> newMultimap(Map<K, Collection<V>> map,
final Supplier<? extends Collection<V>> factory) {
return new CustomMultimap<K, V>(map, factory);
}
private static class CustomMultimap<K, V> extends AbstractMultimap<K, V> {
transient Supplier<? extends Collection<V>> factory;
CustomMultimap(Map<K, Collection<V>> map,
Supplier<? extends Collection<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected Collection<V> createCollection() {
return factory.get();
}
// can't use Serialization writeMultimap and populateMultimap methods since
// there's no way to generate the empty backing map.
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends Collection<V>>) stream.readObject();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("java serialization not supported")
private static final long serialVersionUID = 0;
}
/**
* Creates a new {@code ListMultimap} that uses the provided map and factory.
* It can generate a multimap based on arbitrary {@link Map} and {@link List}
* classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. The multimap's {@code get}, {@code
* removeAll}, and {@code replaceValues} methods return {@code RandomAccess}
* lists if the factory does. However, the multimap's {@code get} method
* returns instances of a different class than does {@code factory.get()}.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* lists generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedListMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link ArrayListMultimap#create()} and {@link LinkedListMultimap#create()}
* won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the lists returned by {@code factory}. Those objects should not be manually
* updated, they should be empty when provided, and they should not use soft,
* weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty lists that will each hold all values
* for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> ListMultimap<K, V> newListMultimap(
Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) {
return new CustomListMultimap<K, V>(map, factory);
}
private static class CustomListMultimap<K, V>
extends AbstractListMultimap<K, V> {
transient Supplier<? extends List<V>> factory;
CustomListMultimap(Map<K, Collection<V>> map,
Supplier<? extends List<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected List<V> createCollection() {
return factory.get();
}
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends List<V>>) stream.readObject();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("java serialization not supported")
private static final long serialVersionUID = 0;
}
/**
* Creates a new {@code SetMultimap} that uses the provided map and factory.
* It can generate a multimap based on arbitrary {@link Map} and {@link Set}
* classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* sets generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedSetMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link HashMultimap#create()}, {@link LinkedHashMultimap#create()},
* {@link TreeMultimap#create()}, and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the sets returned by {@code factory}. Those objects should not be manually
* updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty sets that will each hold all values
* for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> SetMultimap<K, V> newSetMultimap(
Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) {
return new CustomSetMultimap<K, V>(map, factory);
}
private static class CustomSetMultimap<K, V>
extends AbstractSetMultimap<K, V> {
transient Supplier<? extends Set<V>> factory;
CustomSetMultimap(Map<K, Collection<V>> map,
Supplier<? extends Set<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected Set<V> createCollection() {
return factory.get();
}
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends Set<V>>) stream.readObject();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
/**
* Creates a new {@code SortedSetMultimap} that uses the provided map and
* factory. It can generate a multimap based on arbitrary {@link Map} and
* {@link SortedSet} classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* sets generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedSortedSetMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link TreeMultimap#create()} and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the sets returned by {@code factory}. Those objects should not be manually
* updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty sorted sets that will each hold
* all values for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> SortedSetMultimap<K, V> newSortedSetMultimap(
Map<K, Collection<V>> map,
final Supplier<? extends SortedSet<V>> factory) {
return new CustomSortedSetMultimap<K, V>(map, factory);
}
private static class CustomSortedSetMultimap<K, V>
extends AbstractSortedSetMultimap<K, V> {
transient Supplier<? extends SortedSet<V>> factory;
transient Comparator<? super V> valueComparator;
CustomSortedSetMultimap(Map<K, Collection<V>> map,
Supplier<? extends SortedSet<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
valueComparator = factory.get().comparator();
}
@Override protected SortedSet<V> createCollection() {
return factory.get();
}
@Override public Comparator<? super V> valueComparator() {
return valueComparator;
}
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends SortedSet<V>>) stream.readObject();
valueComparator = factory.get().comparator();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
/**
* Copies each key-value mapping in {@code source} into {@code dest}, with
* its key and value reversed.
*
* <p>If {@code source} is an {@link ImmutableMultimap}, consider using
* {@link ImmutableMultimap#inverse} instead.
*
* @param source any multimap
* @param dest the multimap to copy into; usually empty
* @return {@code dest}
*/
public static <K, V, M extends Multimap<K, V>> M invertFrom(
Multimap<? extends V, ? extends K> source, M dest) {
checkNotNull(dest);
for (Map.Entry<? extends V, ? extends K> entry : source.entries()) {
dest.put(entry.getValue(), entry.getKey());
}
return dest;
}
/**
* Returns a synchronized (thread-safe) multimap backed by the specified
* multimap. In order to guarantee serial access, it is critical that
* <b>all</b> access to the backing multimap is accomplished through the
* returned multimap.
*
* <p>It is imperative that the user manually synchronize on the returned
* multimap when accessing any of its collection views: <pre> {@code
*
* Multimap<K, V> m = Multimaps.synchronizedMultimap(
* HashMultimap.<K, V>create());
* ...
* Set<K> s = m.keySet(); // Needn't be in synchronized block
* ...
* synchronized (m) { // Synchronizing on m, not s!
* Iterator<K> i = s.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>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that aren't
* synchronized.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped in a synchronized view
* @return a synchronized view of the specified multimap
*/
public static <K, V> Multimap<K, V> synchronizedMultimap(
Multimap<K, V> multimap) {
return Synchronized.multimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified multimap. Query operations on
* the returned multimap "read through" to the specified multimap, and
* attempts to modify the returned multimap, either directly or through the
* multimap's views, result in an {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> Multimap<K, V> unmodifiableMultimap(
Multimap<K, V> delegate) {
if (delegate instanceof UnmodifiableMultimap ||
delegate instanceof ImmutableMultimap) {
return delegate;
}
return new UnmodifiableMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap(
ImmutableMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
private static class UnmodifiableMultimap<K, V>
extends ForwardingMultimap<K, V> implements Serializable {
final Multimap<K, V> delegate;
transient Collection<Entry<K, V>> entries;
transient Multiset<K> keys;
transient Set<K> keySet;
transient Collection<V> values;
transient Map<K, Collection<V>> map;
UnmodifiableMultimap(final Multimap<K, V> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override protected Multimap<K, V> delegate() {
return delegate;
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = map;
if (result == null) {
final Map<K, Collection<V>> unmodifiableMap
= Collections.unmodifiableMap(delegate.asMap());
map = result = new ForwardingMap<K, Collection<V>>() {
@Override protected Map<K, Collection<V>> delegate() {
return unmodifiableMap;
}
Set<Entry<K, Collection<V>>> entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
Set<Entry<K, Collection<V>>> result = entrySet;
return (result == null)
? entrySet
= unmodifiableAsMapEntries(unmodifiableMap.entrySet())
: result;
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = unmodifiableMap.get(key);
return (collection == null)
? null : unmodifiableValueCollection(collection);
}
Collection<Collection<V>> asMapValues;
@Override public Collection<Collection<V>> values() {
Collection<Collection<V>> result = asMapValues;
return (result == null)
? asMapValues
= new UnmodifiableAsMapValues<V>(unmodifiableMap.values())
: result;
}
@Override public boolean containsValue(Object o) {
return values().contains(o);
}
};
}
return result;
}
@Override public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
if (result == null) {
entries = result = unmodifiableEntries(delegate.entries());
}
return result;
}
@Override public Collection<V> get(K key) {
return unmodifiableValueCollection(delegate.get(key));
}
@Override public Multiset<K> keys() {
Multiset<K> result = keys;
if (result == null) {
keys = result = Multisets.unmodifiableMultiset(delegate.keys());
}
return result;
}
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
keySet = result = Collections.unmodifiableSet(delegate.keySet());
}
return result;
}
@Override public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
values = result = Collections.unmodifiableCollection(delegate.values());
}
return result;
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableAsMapValues<V>
extends ForwardingCollection<Collection<V>> {
final Collection<Collection<V>> delegate;
UnmodifiableAsMapValues(Collection<Collection<V>> delegate) {
this.delegate = Collections.unmodifiableCollection(delegate);
}
@Override protected Collection<Collection<V>> delegate() {
return delegate;
}
@Override public Iterator<Collection<V>> iterator() {
final Iterator<Collection<V>> iterator = delegate.iterator();
return new Iterator<Collection<V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Collection<V> next() {
return unmodifiableValueCollection(iterator.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return standardContains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
}
private static class UnmodifiableListMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> {
UnmodifiableListMultimap(ListMultimap<K, V> delegate) {
super(delegate);
}
@Override public ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
return Collections.unmodifiableList(delegate().get(key));
}
@Override public List<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSetMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> {
UnmodifiableSetMultimap(SetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
/*
* Note that this doesn't return a SortedSet when delegate is a
* SortedSetMultiset, unlike (SortedSet<V>) super.get().
*/
return Collections.unmodifiableSet(delegate().get(key));
}
@Override public Set<Map.Entry<K, V>> entries() {
return Maps.unmodifiableEntrySet(delegate().entries());
}
@Override public Set<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSortedSetMultimap<K, V>
extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> {
UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
return Collections.unmodifiableSortedSet(delegate().get(key));
}
@Override public SortedSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super V> valueComparator() {
return delegate().valueComparator();
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) {@code SetMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> synchronizedSetMultimap(
SetMultimap<K, V> multimap) {
return Synchronized.setMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SetMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
SetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSetMultimap ||
delegate instanceof ImmutableSetMultimap) {
return delegate;
}
return new UnmodifiableSetMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
ImmutableSetMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by
* the specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V>
synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) {
return Synchronized.sortedSetMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SortedSetMultimap}.
* Query operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(
SortedSetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSortedSetMultimap) {
return delegate;
}
return new UnmodifiableSortedSetMultimap<K, V>(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code ListMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> synchronizedListMultimap(
ListMultimap<K, V> multimap) {
return Synchronized.listMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code ListMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ListMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableListMultimap ||
delegate instanceof ImmutableListMultimap) {
return delegate;
}
return new UnmodifiableListMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ImmutableListMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns an unmodifiable view of the specified collection, preserving the
* interface for instances of {@code SortedSet}, {@code Set}, {@code List} and
* {@code Collection}, in that order of preference.
*
* @param collection the collection for which to return an unmodifiable view
* @return an unmodifiable view of the collection
*/
private static <V> Collection<V> unmodifiableValueCollection(
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);
}
return Collections.unmodifiableCollection(collection);
}
/**
* Returns an unmodifiable view of the specified multimap {@code asMap} entry.
* The {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}, and the collection returned by {@code
* getValue} is also an unmodifiable (type-preserving) view. This also has the
* side-effect of redefining equals to comply with the Map.Entry contract, and
* to avoid a possible nefarious implementation of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
private static <K, V> Map.Entry<K, Collection<V>> unmodifiableAsMapEntry(
final Map.Entry<K, Collection<V>> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, Collection<V>>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public Collection<V> getValue() {
return unmodifiableValueCollection(entry.getValue());
}
};
}
/**
* Returns an unmodifiable view of the specified collection of entries. The
* {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}. If the specified collection is a {@code
* Set}, the returned collection is also a {@code Set}.
*
* @param entries the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
private static <K, V> Collection<Entry<K, V>> unmodifiableEntries(
Collection<Entry<K, V>> entries) {
if (entries instanceof Set) {
return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries);
}
return new Maps.UnmodifiableEntries<K, V>(
Collections.unmodifiableCollection(entries));
}
/**
* Returns an unmodifiable view of the specified set of {@code asMap} entries.
* The {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}, as do any operations that attempt to modify
* the returned collection.
*
* @param asMapEntries the {@code asMap} entries for which to return an
* unmodifiable view
* @return an unmodifiable view of the collection entries
*/
private static <K, V> Set<Entry<K, Collection<V>>> unmodifiableAsMapEntries(
Set<Entry<K, Collection<V>>> asMapEntries) {
return new UnmodifiableAsMapEntries<K, V>(
Collections.unmodifiableSet(asMapEntries));
}
/** @see Multimaps#unmodifiableAsMapEntries */
static class UnmodifiableAsMapEntries<K, V>
extends ForwardingSet<Entry<K, Collection<V>>> {
private final Set<Entry<K, Collection<V>>> delegate;
UnmodifiableAsMapEntries(Set<Entry<K, Collection<V>>> delegate) {
this.delegate = delegate;
}
@Override protected Set<Entry<K, Collection<V>>> delegate() {
return delegate;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = delegate.iterator();
return new ForwardingIterator<Entry<K, Collection<V>>>() {
@Override protected Iterator<Entry<K, Collection<V>>> delegate() {
return iterator;
}
@Override public Entry<K, Collection<V>> next() {
return unmodifiableAsMapEntry(iterator.next());
}
};
}
@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 equals(@Nullable Object object) {
return standardEquals(object);
}
}
/**
* Returns a multimap view of the specified map. The multimap is backed by the
* map, so changes to the map are reflected in the multimap, and vice versa.
* If the map is modified while an iteration over one of the multimap's
* collection views is in progress (except through the iterator's own {@code
* remove} operation, or through the {@code setValue} operation on a map entry
* returned by the iterator), the results of the iteration are undefined.
*
* <p>The multimap supports mapping removal, which removes the corresponding
* mapping from the map. It does not support any operations which might add
* mappings, such as {@code put}, {@code putAll} or {@code replaceValues}.
*
* <p>The returned multimap will be serializable if the specified map is
* serializable.
*
* @param map the backing map for the returned multimap view
*/
public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) {
return new MapMultimap<K, V>(map);
}
/** @see Multimaps#forMap */
private static class MapMultimap<K, V>
implements SetMultimap<K, V>, Serializable {
final Map<K, V> map;
transient Map<K, Collection<V>> asMap;
MapMultimap(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public boolean containsEntry(Object key, Object value) {
return map.entrySet().contains(Maps.immutableEntry(key, value));
}
@Override
public Set<V> get(final K key) {
return new AbstractSet<V>() {
@Override public Iterator<V> iterator() {
return new Iterator<V>() {
int i;
@Override
public boolean hasNext() {
return (i == 0) && map.containsKey(key);
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
i++;
return map.get(key);
}
@Override
public void remove() {
checkState(i == 1);
i = -1;
map.remove(key);
}
};
}
@Override public int size() {
return map.containsKey(key) ? 1 : 0;
}
};
}
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object key, Object value) {
return map.entrySet().remove(Maps.immutableEntry(key, value));
}
@Override
public Set<V> removeAll(Object key) {
Set<V> values = new HashSet<V>(2);
if (!map.containsKey(key)) {
return values;
}
values.add(map.remove(key));
return values;
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<K> keySet() {
return map.keySet();
}
@Override
public Multiset<K> keys() {
return Multisets.forSet(map.keySet());
}
@Override
public Collection<V> values() {
return map.values();
}
@Override
public Set<Entry<K, V>> entries() {
return map.entrySet();
}
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
if (result == null) {
asMap = result = new AsMap();
}
return result;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return this.size() == that.size() && asMap().equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
private static final MapJoiner JOINER
= Joiner.on("], ").withKeyValueSeparator("=[").useForNull("null");
@Override public String toString() {
if (map.isEmpty()) {
return "{}";
}
StringBuilder builder
= Collections2.newStringBuilderForCollection(map.size()).append('{');
JOINER.appendTo(builder, map);
return builder.append("]}").toString();
}
/** @see MapMultimap#asMap */
class AsMapEntries extends AbstractSet<Entry<K, Collection<V>>> {
@Override public int size() {
return map.size();
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return new Iterator<Entry<K, Collection<V>>>() {
final Iterator<K> keys = map.keySet().iterator();
@Override
public boolean hasNext() {
return keys.hasNext();
}
@Override
public Entry<K, Collection<V>> next() {
final K key = keys.next();
return new AbstractMapEntry<K, Collection<V>>() {
@Override public K getKey() {
return key;
}
@Override public Collection<V> getValue() {
return get(key);
}
};
}
@Override
public void remove() {
keys.remove();
}
};
}
@Override public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
if (!(entry.getValue() instanceof Set)) {
return false;
}
Set<?> set = (Set<?>) entry.getValue();
return (set.size() == 1)
&& containsEntry(entry.getKey(), set.iterator().next());
}
@Override public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
if (!(entry.getValue() instanceof Set)) {
return false;
}
Set<?> set = (Set<?>) entry.getValue();
return (set.size() == 1)
&& map.entrySet().remove(
Maps.immutableEntry(entry.getKey(), set.iterator().next()));
}
}
/** @see MapMultimap#asMap */
class AsMap extends Maps.ImprovedAbstractMap<K, Collection<V>> {
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new AsMapEntries();
}
// The following methods are included for performance.
@Override public boolean containsKey(Object key) {
return map.containsKey(key);
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
Collection<V> collection = MapMultimap.this.get((K) key);
return collection.isEmpty() ? null : collection;
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = removeAll(key);
return collection.isEmpty() ? null : collection;
}
}
private static final long serialVersionUID = 7845222491160860175L;
}
/**
* Returns a view of a multimap where each value is transformed by a function.
* All other properties of the multimap, such as iteration order, are left
* intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
* Function<Integer, String> square = new Function<Integer, String>() {
* public String apply(Integer in) {
* return Integer.toString(in * in);
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformValues(multimap, square);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[4, 16], b=[9, 9], c=[6]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
@Beta
public static <K, V1, V2> Multimap<K, V2> transformValues(
Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a multimap whose values are derived from the original
* multimap's entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* SetMultimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return (value >= 0) ? key : "no" + key;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[a, a], b=[nob]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
@Beta
public static <K, V1, V2> Multimap<K, V2> transformEntries(
Multimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesMultimap<K, V1, V2>(fromMap, transformer);
}
private static class TransformedEntriesMultimap<K, V1, V2>
implements Multimap<K, V2> {
final Multimap<K, V1> fromMultimap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMultimap(Multimap<K, V1> fromMultimap,
final EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMultimap = checkNotNull(fromMultimap);
this.transformer = checkNotNull(transformer);
}
Collection<V2> transform(final K key, Collection<V1> values) {
return Collections2.transform(values, new Function<V1, V2>() {
@Override public V2 apply(V1 value) {
return transformer.transformEntry(key, value);
}
});
}
private transient Map<K, Collection<V2>> asMap;
@Override public Map<K, Collection<V2>> asMap() {
if (asMap == null) {
Map<K, Collection<V2>> aM = Maps.transformEntries(fromMultimap.asMap(),
new EntryTransformer<K, Collection<V1>, Collection<V2>>() {
@Override public Collection<V2> transformEntry(
K key, Collection<V1> value) {
return transform(key, value);
}
});
asMap = aM;
return aM;
}
return asMap;
}
@Override public void clear() {
fromMultimap.clear();
}
@SuppressWarnings("unchecked")
@Override public boolean containsEntry(Object key, Object value) {
Collection<V2> values = get((K) key);
return values.contains(value);
}
@Override public boolean containsKey(Object key) {
return fromMultimap.containsKey(key);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
private transient Collection<Entry<K, V2>> entries;
@Override public Collection<Entry<K, V2>> entries() {
if (entries == null) {
Collection<Entry<K, V2>> es = new TransformedEntries(transformer);
entries = es;
return es;
}
return entries;
}
private class TransformedEntries
extends TransformedCollection<Entry<K, V1>, Entry<K, V2>> {
TransformedEntries(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap.entries(),
new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override public Entry<K, V2> apply(final Entry<K, V1> entry) {
return new AbstractMapEntry<K, V2>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V2 getValue() {
return transformer.transformEntry(
entry.getKey(), entry.getValue());
}
};
}
});
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Collection<V2> values = get((K) entry.getKey());
return values.remove(entry.getValue());
}
return false;
}
}
@Override public Collection<V2> get(final K key) {
return transform(key, fromMultimap.get(key));
}
@Override public boolean isEmpty() {
return fromMultimap.isEmpty();
}
@Override public Set<K> keySet() {
return fromMultimap.keySet();
}
@Override public Multiset<K> keys() {
return fromMultimap.keys();
}
@Override public boolean put(K key, V2 value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(
Multimap<? extends K, ? extends V2> multimap) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object key, Object value) {
return get((K) key).remove(value);
}
@SuppressWarnings("unchecked")
@Override public Collection<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public Collection<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public int size() {
return fromMultimap.size();
}
private transient Collection<V2> values;
@Override public Collection<V2> values() {
if (values == null) {
Collection<V2> vs = Collections2.transform(
fromMultimap.entries(), new Function<Entry<K, V1>, V2>() {
@Override public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(
entry.getKey(), entry.getValue());
}
});
values = vs;
return vs;
}
return values;
}
@Override public boolean equals(Object obj) {
if (obj instanceof Multimap) {
Multimap<?, ?> other = (Multimap<?, ?>) obj;
return asMap().equals(other.asMap());
}
return false;
}
@Override public int hashCode() {
return asMap().hashCode();
}
@Override public String toString() {
return asMap().toString();
}
}
/**
* Returns a view of a {@code ListMultimap} where each value is transformed by
* a function. All other properties of the multimap, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* ListMultimap<String, Integer> multimap
* = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* ListMultimap<String, Double> transformed = Multimaps.transformValues(map,
* sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[2.0, 4.0], b=[3.0]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
@Beta
public static <K, V1, V2> ListMultimap<K, V2> transformValues(
ListMultimap<K, V1> fromMultimap,
final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a {@code ListMultimap} whose values are derived from the
* original multimap's entries. In contrast to
* {@link #transformValues(ListMultimap, Function)}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return key + value;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
@Beta
public static <K, V1, V2> ListMultimap<K, V2> transformEntries(
ListMultimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesListMultimap<K, V1, V2>(fromMap, transformer);
}
private static final class TransformedEntriesListMultimap<K, V1, V2>
extends TransformedEntriesMultimap<K, V1, V2>
implements ListMultimap<K, V2> {
TransformedEntriesListMultimap(ListMultimap<K, V1> fromMultimap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap, transformer);
}
@Override List<V2> transform(final K key, Collection<V1> values) {
return Lists.transform((List<V1>) values, new Function<V1, V2>() {
@Override public V2 apply(V1 value) {
return transformer.transformEntry(key, value);
}
});
}
@Override public List<V2> get(K key) {
return transform(key, fromMultimap.get(key));
}
@SuppressWarnings("unchecked")
@Override public List<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public List<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterable} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input 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.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys, stringLengthFunction);
* System.out.println(index);}</pre>
*
* prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterable<V> values, Function<? super V, K> keyFunction) {
return index(values.iterator(), keyFunction);
}
/**
* <b>Deprecated.</b>
*
* @since 10.0
* @deprecated use {@link #index(Iterator, Function)} by casting {@code
* values} to {@code Iterator<V>}, or better yet, by implementing only
* {@code Iterator} and not {@code Iterable}. <b>This method is scheduled
* for deletion in March 2012.</b>
*/
@Beta
@Deprecated
public static <K, V, I extends Object & Iterable<V> & Iterator<V>>
ImmutableListMultimap<K, V> index(
I values, Function<? super V, K> keyFunction) {
Iterable<V> valuesIterable = checkNotNull(values);
return index(valuesIterable, keyFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterator} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterator. 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.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys.iterator(), stringLengthFunction);
* System.out.println(index);}</pre>
*
* prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
* @since 10.0
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
while (values.hasNext()) {
V value = values.next();
checkNotNull(value, values);
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
static abstract class Keys<K, V> extends AbstractMultiset<K> {
abstract Multimap<K, V> multimap();
@Override Iterator<Multiset.Entry<K>> entryIterator() {
final Iterator<Map.Entry<K, Collection<V>>> backingIterator =
multimap().asMap().entrySet().iterator();
return new Iterator<Multiset.Entry<K>>() {
@Override public boolean hasNext() {
return backingIterator.hasNext();
}
@Override public Multiset.Entry<K> next() {
final Map.Entry<K, Collection<V>> backingEntry =
backingIterator.next();
return new Multisets.AbstractEntry<K>() {
@Override public K getElement() {
return backingEntry.getKey();
}
@Override public int getCount() {
return backingEntry.getValue().size();
}
};
}
@Override public void remove() {
backingIterator.remove();
}
};
}
@Override int distinctElements() {
return multimap().asMap().size();
}
@Override Set<Multiset.Entry<K>> createEntrySet() {
return new KeysEntrySet();
}
class KeysEntrySet extends Multisets.EntrySet<K> {
@Override Multiset<K> multiset() {
return Keys.this;
}
@Override public Iterator<Multiset.Entry<K>> iterator() {
return entryIterator();
}
@Override public int size() {
return distinctElements();
}
@Override public boolean isEmpty() {
return multimap().isEmpty();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Multiset.Entry<?>) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
Collection<V> collection = multimap().asMap().get(entry.getElement());
return collection != null && collection.size() == entry.getCount();
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Multiset.Entry<?>) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
Collection<V> collection = multimap().asMap().get(entry.getElement());
if (collection != null && collection.size() == entry.getCount()) {
collection.clear();
return true;
}
}
return false;
}
}
@Override public boolean contains(@Nullable Object element) {
return multimap().containsKey(element);
}
@Override public Iterator<K> iterator() {
return Iterators.transform(multimap().entries().iterator(),
new Function<Map.Entry<K, V>, K>() {
@Override public K apply(Map.Entry<K, V> entry) {
return entry.getKey();
}
});
}
@Override public int count(@Nullable Object element) {
try {
if (multimap().containsKey(element)) {
Collection<V> values = multimap().asMap().get(element);
return (values == null) ? 0 : values.size();
}
return 0;
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
@Override public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0);
if (occurrences == 0) {
return count(element);
}
Collection<V> values;
try {
values = multimap().asMap().get(element);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
if (values == null) {
return 0;
}
int oldCount = values.size();
if (occurrences >= oldCount) {
values.clear();
} else {
Iterator<V> iterator = values.iterator();
for (int i = 0; i < occurrences; i++) {
iterator.next();
iterator.remove();
}
}
return oldCount;
}
@Override public void clear() {
multimap().clear();
}
@Override public Set<K> elementSet() {
return multimap().keySet();
}
}
static abstract class Values<K, V> extends AbstractCollection<V> {
abstract Multimap<K, V> multimap();
@Override public Iterator<V> iterator() {
final Iterator<Map.Entry<K, V>> backingIterator =
multimap().entries().iterator();
return new Iterator<V>() {
@Override public boolean hasNext() {
return backingIterator.hasNext();
}
@Override public V next() {
return backingIterator.next().getValue();
}
@Override public void remove() {
backingIterator.remove();
}
};
}
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
return multimap().containsValue(o);
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link Multimap#entries()}.
*/
static abstract class Entries<K, V> extends
AbstractCollection<Map.Entry<K, V>> {
abstract Multimap<K, V> multimap();
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Map.Entry<?, ?>) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Map.Entry<?, ?>) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link SetMultimap#entries()}.
*/
static abstract class EntrySet<K, V> extends Entries<K, V> implements
Set<Map.Entry<K, V>> {
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override public boolean equals(@Nullable Object obj) {
return Sets.equalsImpl(this, obj);
}
}
/**
* A skeleton implementation of {@link Multimap#asMap()}.
*/
static abstract class AsMap<K, V> extends
Maps.ImprovedAbstractMap<K, Collection<V>> {
abstract Multimap<K, V> multimap();
@Override public abstract int size();
abstract Iterator<Entry<K, Collection<V>>> entryIterator();
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new EntrySet();
}
void removeValuesForKey(Object key){
multimap().removeAll(key);
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return entryIterator();
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
return containsKey(key) ? multimap().get((K) key) : null;
}
@Override public Collection<V> remove(Object key) {
return containsKey(key) ? multimap().removeAll(key) : null;
}
@Override public Set<K> keySet() {
return multimap().keySet();
}
@Override public boolean isEmpty() {
return multimap().isEmpty();
}
@Override public boolean containsKey(Object key) {
return multimap().containsKey(key);
}
@Override public void clear() {
multimap().clear();
}
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@replaceValues()} methods
* throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} 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.
*
* @since 11.0
*/
@Beta
@GwtIncompatible(value = "untested")
public static <K, V> Multimap<K, V> filterKeys(
Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a value that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@replaceValues()} methods
* throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose value satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} 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.
*
* @since 11.0
*/
@Beta
@GwtIncompatible(value = "untested")
public static <K, V> Multimap<K, V> filterValues(
Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key/value pair that doesn't satisfy the predicate,
* multimap's {@code put()}, {@code putAll()}, and {@replaceValues()} methods
* throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 11.0
*/
@Beta
@GwtIncompatible(value = "untested")
public static <K, V> Multimap<K, V> filterEntries(
Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredMultimap)
? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate)
: new FilteredMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Support removal operations when filtering a filtered multimap. Since a
* filtered multimap has iterators that don't support remove, passing one to
* the FilteredMultimap constructor would lead to a multimap whose removal
* operations would fail. This method combines the predicates to avoid that
* problem.
*/
private static <K, V> Multimap<K, V> filterFiltered(FilteredMultimap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredMultimap<K, V>(map.unfiltered, predicate);
}
private static class FilteredMultimap<K, V> implements Multimap<K, V> {
final Multimap<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
FilteredMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override public int size() {
return entries().size();
}
@Override public boolean isEmpty() {
return entries().isEmpty();
}
@Override public boolean containsKey(Object key) {
return asMap().containsKey(key);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
// This method should be called only when key is a K and value is a V.
@SuppressWarnings("unchecked")
boolean satisfiesPredicate(Object key, Object value) {
return predicate.apply(Maps.immutableEntry((K) key, (V) value));
}
@Override public boolean containsEntry(Object key, Object value) {
return unfiltered.containsEntry(key, value) && satisfiesPredicate(key, value);
}
@Override public boolean put(K key, V value) {
checkArgument(satisfiesPredicate(key, value));
return unfiltered.put(key, value);
}
@Override public boolean remove(Object key, Object value) {
return containsEntry(key, value) ? unfiltered.remove(key, value) : false;
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
for (V value : values) {
checkArgument(satisfiesPredicate(key, value));
}
return unfiltered.putAll(key, values);
}
@Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
checkArgument(satisfiesPredicate(entry.getKey(), entry.getValue()));
}
return unfiltered.putAll(multimap);
}
@Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
for (V value : values) {
checkArgument(satisfiesPredicate(key, value));
}
// Not calling unfiltered.replaceValues() since values that don't satisify
// the filter should remain in the multimap.
Collection<V> oldValues = removeAll(key);
unfiltered.putAll(key, values);
return oldValues;
}
@Override public Collection<V> removeAll(Object key) {
List<V> removed = Lists.newArrayList();
Collection<V> values = unfiltered.asMap().get(key);
if (values != null) {
Iterator<V> iterator = values.iterator();
while (iterator.hasNext()) {
V value = iterator.next();
if (satisfiesPredicate(key, value)) {
removed.add(value);
iterator.remove();
}
}
}
if (unfiltered instanceof SetMultimap) {
return Collections.unmodifiableSet(Sets.newLinkedHashSet(removed));
} else {
return Collections.unmodifiableList(removed);
}
}
@Override public void clear() {
entries().clear();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return asMap().equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return asMap().hashCode();
}
@Override public String toString() {
return asMap().toString();
}
class ValuePredicate implements Predicate<V> {
final K key;
ValuePredicate(K key) {
this.key = key;
}
@Override public boolean apply(V value) {
return satisfiesPredicate(key, value);
}
}
Collection<V> filterCollection(Collection<V> collection, Predicate<V> predicate) {
if (collection instanceof Set) {
return Sets.filter((Set<V>) collection, predicate);
} else {
return Collections2.filter(collection, predicate);
}
}
@Override public Collection<V> get(K key) {
return filterCollection(unfiltered.get(key), new ValuePredicate(key));
}
@Override public Set<K> keySet() {
return asMap().keySet();
}
Collection<V> values;
@Override public Collection<V> values() {
return (values == null) ? values = new Values() : values;
}
class Values extends Multimaps.Values<K, V> {
@Override Multimap<K, V> multimap() {
return FilteredMultimap.this;
}
@Override public boolean contains(@Nullable Object o) {
return Iterators.contains(iterator(), o);
}
// Override remove methods since iterator doesn't support remove.
@Override public boolean remove(Object o) {
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (c.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!c.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
}
Collection<Entry<K, V>> entries;
@Override public Collection<Entry<K, V>> entries() {
return (entries == null)
? entries = Collections2.filter(unfiltered.entries(), predicate)
: entries;
}
/**
* Remove all filtered asMap() entries that satisfy the predicate.
*/
boolean removeEntriesIf(Predicate<Map.Entry<K, Collection<V>>> removalPredicate) {
Iterator<Map.Entry<K, Collection<V>>> iterator = unfiltered.asMap().entrySet().iterator();
boolean changed = false;
while (iterator.hasNext()) {
// Determine whether to remove the filtered values with this key.
Map.Entry<K, Collection<V>> entry = iterator.next();
K key = entry.getKey();
Collection<V> collection = entry.getValue();
Predicate<V> valuePredicate = new ValuePredicate(key);
Collection<V> filteredCollection = filterCollection(collection, valuePredicate);
Map.Entry<K, Collection<V>> filteredEntry = Maps.immutableEntry(key, filteredCollection);
if (removalPredicate.apply(filteredEntry) && !filteredCollection.isEmpty()) {
changed = true;
if (Iterables.all(collection, valuePredicate)) {
iterator.remove(); // Remove all values for the key.
} else {
filteredCollection.clear(); // Remove the filtered values only.
}
}
}
return changed;
}
Map<K, Collection<V>> asMap;
@Override public Map<K, Collection<V>> asMap() {
return (asMap == null) ? asMap = createAsMap() : asMap;
}
static final Predicate<Collection<?>> NOT_EMPTY = new Predicate<Collection<?>>() {
@Override public boolean apply(Collection<?> input) {
return !input.isEmpty();
}
};
Map<K, Collection<V>> createAsMap() {
// Select the values that satisify the predicate.
EntryTransformer<K, Collection<V>, Collection<V>> transformer
= new EntryTransformer<K, Collection<V>, Collection<V>>() {
@Override public Collection<V> transformEntry(K key, Collection<V> collection) {
return filterCollection(collection, new ValuePredicate(key));
}
};
Map<K, Collection<V>> transformed
= Maps.transformEntries(unfiltered.asMap(), transformer);
// Select the keys that have at least one value remaining.
Map<K, Collection<V>> filtered = Maps.filterValues(transformed, NOT_EMPTY);
// Override the removal methods, since removing a map entry should not
// affect values that don't satisfy the filter.
return new AsMap(filtered);
}
class AsMap extends ForwardingMap<K, Collection<V>> {
final Map<K, Collection<V>> delegate;
AsMap(Map<K, Collection<V>> delegate) {
this.delegate = delegate;
}
@Override protected Map<K, Collection<V>> delegate() {
return delegate;
}
@Override public Collection<V> remove(Object o) {
Collection<V> output = FilteredMultimap.this.removeAll(o);
return output.isEmpty() ? null : output;
}
@Override public void clear() {
FilteredMultimap.this.clear();
}
Set<K> keySet;
@Override public Set<K> keySet() {
return (keySet == null) ? keySet = new KeySet() : keySet;
}
class KeySet extends Maps.KeySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public boolean remove(Object o) {
Collection<V> collection = delegate.get(o);
if (collection == null) {
return false;
}
collection.clear();
return true;
}
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry.getKey());
}
};
return removeEntriesIf(removalPredicate);
}
}
Values asMapValues;
@Override public Collection<Collection<V>> values() {
return (asMapValues == null) ? asMapValues = new Values() : asMapValues;
}
class Values extends Maps.Values<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public boolean remove(Object o) {
for (Collection<V> collection : this) {
if (collection.equals(o)) {
collection.clear();
return true;
}
}
return false;
}
@Override public boolean removeAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return c.contains(entry.getValue());
}
};
return removeEntriesIf(removalPredicate);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry.getValue());
}
};
return removeEntriesIf(removalPredicate);
}
}
EntrySet entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
return (entrySet == null) ? entrySet = new EntrySet(super.entrySet()) : entrySet;
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
Set<Map.Entry<K, Collection<V>>> delegateEntries;
public EntrySet(Set<Map.Entry<K, Collection<V>>> delegateEntries) {
this.delegateEntries = delegateEntries;
}
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return delegateEntries.iterator();
}
@Override public boolean remove(Object o) {
if (o instanceof Entry<?, ?>) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Collection<V> collection = delegate.get(entry.getKey());
if (collection != null && collection.equals(entry.getValue())) {
collection.clear();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry);
}
};
return removeEntriesIf(removalPredicate);
}
}
}
AbstractMultiset<K> keys;
@Override public Multiset<K> keys() {
return (keys == null) ? keys = new Keys() : keys;
}
class Keys extends Multimaps.Keys<K, V> {
@Override Multimap<K, V> multimap() {
return FilteredMultimap.this;
}
@Override public int remove(Object o, int occurrences) {
checkArgument(occurrences >= 0);
Collection<V> values = unfiltered.asMap().get(o);
if (values == null) {
return 0;
}
int priorCount = 0;
int removed = 0;
Iterator<V> iterator = values.iterator();
while (iterator.hasNext()) {
if (satisfiesPredicate(o, iterator.next())) {
priorCount++;
if (removed < occurrences) {
iterator.remove();
removed++;
}
}
}
return priorCount;
}
@Override Set<Multiset.Entry<K>> createEntrySet() {
return new EntrySet();
}
class EntrySet extends Multimaps.Keys<K, V>.KeysEntrySet {
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
Multiset.Entry<K> multisetEntry
= Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
return !c.contains(multisetEntry);
}
};
return removeEntriesIf(removalPredicate);
}
}
}
}
// TODO(jlevy): Create methods that filter a SetMultimap or SortedSetMultimap.
}
| 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 javax.annotation.Nullable;
/**
* A local balancing policy for modified nodes in binary search trees.
*
* @author Louis Wasserman
* @param <N> The type of the nodes in the trees that this {@code BstRebalancePolicy} can
* rebalance.
*/
@GwtCompatible
interface BstBalancePolicy<N extends BstNode<?, N>> {
/**
* Constructs a locally balanced tree around the key and value data in {@code source}, and the
* subtrees {@code left} and {@code right}. It is guaranteed that the resulting tree will have
* the same inorder traversal order as the subtree {@code left}, then the entry {@code source},
* then the subtree {@code right}.
*/
N balance(BstNodeFactory<N> nodeFactory, N source, @Nullable N left, @Nullable N right);
/**
* Constructs a locally balanced tree around the subtrees {@code left} and {@code right}. It is
* guaranteed that the resulting tree will have the same inorder traversal order as the subtree
* {@code left}, then the subtree {@code right}.
*/
@Nullable
N combine(BstNodeFactory<N> nodeFactory, @Nullable N left, @Nullable N right);
}
| 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) 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 com.google.common.primitives.Ints;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
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
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> {
private static final int DEFAULT_VALUES_PER_KEY = 8;
@VisibleForTesting
transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
/**
* Map entries with an iteration order corresponding to the order in which the
* key-value pairs were added to the multimap.
*/
// package-private for GWT deserialization
transient Collection<Map.Entry<K, V>> linkedEntries;
/**
* Creates a new, empty {@code LinkedHashMultimap} with the default initial
* capacities.
*/
public static <K, V> LinkedHashMultimap<K, V> create() {
return new LinkedHashMultimap<K, V>();
}
/**
* 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>(expectedKeys, 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) {
return new LinkedHashMultimap<K, V>(multimap);
}
private LinkedHashMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
linkedEntries = Sets.newLinkedHashSet();
}
private LinkedHashMultimap(int expectedKeys, int expectedValuesPerKey) {
super(new LinkedHashMap<K, Collection<V>>(expectedKeys));
Preconditions.checkArgument(expectedValuesPerKey >= 0);
this.expectedValuesPerKey = expectedValuesPerKey;
linkedEntries = new LinkedHashSet<Map.Entry<K, V>>(
(int) Math.min(Ints.MAX_POWER_OF_TWO,
((long) expectedKeys) * expectedValuesPerKey));
}
private LinkedHashMultimap(Multimap<? extends K, ? extends V> multimap) {
super(new LinkedHashMap<K, Collection<V>>(
Maps.capacity(multimap.keySet().size())));
linkedEntries
= new LinkedHashSet<Map.Entry<K, V>>(Maps.capacity(multimap.size()));
putAll(multimap);
}
/**
* {@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>(Maps.capacity(expectedValuesPerKey));
}
/**
* {@inheritDoc}
*
* <p>Creates a decorated {@code LinkedHashSet} 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 {@code LinkedHashSet} containing a collection of
* values for one key
*/
@Override Collection<V> createCollection(@Nullable K key) {
return new SetDecorator(key, createCollection());
}
private class SetDecorator extends ForwardingSet<V> {
final Set<V> delegate;
final K key;
SetDecorator(@Nullable K key, Set<V> delegate) {
this.delegate = delegate;
this.key = key;
}
@Override protected Set<V> delegate() {
return delegate;
}
<E> Map.Entry<K, E> createEntry(@Nullable E value) {
return Maps.immutableEntry(key, value);
}
<E> Collection<Map.Entry<K, E>> createEntries(Collection<E> values) {
// converts a collection of values into a list of key/value map entries
Collection<Map.Entry<K, E>> entries
= Lists.newArrayListWithExpectedSize(values.size());
for (E value : values) {
entries.add(createEntry(value));
}
return entries;
}
@Override public boolean add(@Nullable V value) {
boolean changed = delegate.add(value);
if (changed) {
linkedEntries.add(createEntry(value));
}
return changed;
}
@Override public boolean addAll(Collection<? extends V> values) {
boolean changed = delegate.addAll(values);
if (changed) {
linkedEntries.addAll(createEntries(delegate()));
}
return changed;
}
@Override public void clear() {
for (V value : delegate) {
linkedEntries.remove(createEntry(value));
}
delegate.clear();
}
@Override public Iterator<V> iterator() {
final Iterator<V> delegateIterator = delegate.iterator();
return new Iterator<V>() {
V value;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public V next() {
value = delegateIterator.next();
return value;
}
@Override
public void remove() {
delegateIterator.remove();
linkedEntries.remove(createEntry(value));
}
};
}
@Override public boolean remove(@Nullable Object value) {
boolean changed = delegate.remove(value);
if (changed) {
/*
* linkedEntries.remove() will return false when this method is called
* by entries().iterator().remove()
*/
linkedEntries.remove(createEntry(value));
}
return changed;
}
@Override public boolean removeAll(Collection<?> values) {
boolean changed = delegate.removeAll(values);
if (changed) {
linkedEntries.removeAll(createEntries(values));
}
return changed;
}
@Override public boolean retainAll(Collection<?> values) {
/*
* Calling linkedEntries.retainAll() would incorrectly remove values
* with other keys.
*/
boolean changed = false;
Iterator<V> iterator = delegate.iterator();
while (iterator.hasNext()) {
V value = iterator.next();
if (!values.contains(value)) {
iterator.remove();
linkedEntries.remove(Maps.immutableEntry(key, value));
changed = true;
}
}
return changed;
}
}
/**
* {@inheritDoc}
*
* <p>Generates an iterator across map entries that follows the ordering in
* which the key-value pairs were added to the multimap.
*
* @return a key-value iterator with the correct ordering
*/
@Override Iterator<Map.Entry<K, V>> createEntryIterator() {
final Iterator<Map.Entry<K, V>> delegateIterator = linkedEntries.iterator();
return new Iterator<Map.Entry<K, V>>() {
Map.Entry<K, V> entry;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public Map.Entry<K, V> next() {
entry = delegateIterator.next();
return entry;
}
@Override
public void remove() {
// Remove from iterator first to keep iterator valid.
delegateIterator.remove();
LinkedHashMultimap.this.remove(entry.getKey(), entry.getValue());
}
};
}
/**
* {@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(
@Nullable 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();
}
// Unfortunately, the entries() ordering does not determine the key ordering;
// see the example in the LinkedListMultimap class Javadoc.
/**
* @serialData the number of distinct keys, and then for each distinct key:
* the first key, the number of values for that key, and the key's values,
* followed by successive keys and values from the entries() ordering
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(expectedValuesPerKey);
Serialization.writeMultimap(this, stream);
for (Map.Entry<K, V> entry : linkedEntries) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = stream.readInt();
int distinctKeys = Serialization.readCount(stream);
setMap(new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys)));
linkedEntries = new LinkedHashSet<Map.Entry<K, V>>(
distinctKeys * expectedValuesPerKey);
Serialization.populateMultimap(this, stream, distinctKeys);
linkedEntries.clear(); // will clear and repopulate entries
for (int i = 0; i < size(); i++) {
@SuppressWarnings("unchecked") // reading data stored by writeObject
K key = (K) stream.readObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
V value = (V) stream.readObject();
linkedEntries.add(Maps.immutableEntry(key, value));
}
}
@GwtIncompatible("java serialization not supported")
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
*/
@Beta
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}
*/
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
*/
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}
*/
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
*/
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
*/
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
*/
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
*/
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;
}
}
| 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.checkState;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* This class provides a skeletal implementation of the {@code Iterator}
* interface, to make this interface easier to implement for certain types of
* data sources.
*
* <p>{@code Iterator} requires its implementations to support querying the
* end-of-data status without changing the iterator's state, using the {@link
* #hasNext} method. But many data sources, such as {@link
* java.io.Reader#read()}, do not expose this information; the only way to
* discover whether there is any data left is by trying to retrieve it. These
* types of data sources are ordinarily difficult to write iterators for. But
* using this class, one must implement only the {@link #computeNext} method,
* and invoke the {@link #endOfData} method when appropriate.
*
* <p>Another example is an iterator that skips over null elements in a backing
* iterator. This could be implemented as: <pre> {@code
*
* public static Iterator<String> skipNulls(final Iterator<String> in) {
* return new AbstractIterator<String>() {
* protected String computeNext() {
* while (in.hasNext()) {
* String s = in.next();
* if (s != null) {
* return s;
* }
* }
* return endOfData();
* }
* };
* }}</pre>
*
* This class supports iterators that include null elements.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
// When making changes to this class, please also update the copy at
// com.google.common.base.AbstractIterator
@GwtCompatible
public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> {
private State state = State.NOT_READY;
/** Constructor for use by subclasses. */
protected AbstractIterator() {}
private enum State {
/** We have computed the next element and haven't returned it yet. */
READY,
/** We haven't yet computed or have already returned the element. */
NOT_READY,
/** We have reached the end of the data and are finished. */
DONE,
/** We've suffered an exception and are kaput. */
FAILED,
}
private T next;
/**
* Returns the next element. <b>Note:</b> the implementation must call {@link
* #endOfData()} when there are no elements left in the iteration. Failure to
* do so could result in an infinite loop.
*
* <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls
* this method, as does the first invocation of {@code hasNext} or {@code
* next} following each successful call to {@code next}. Once the
* implementation either invokes {@code endOfData} or throws an exception,
* {@code computeNext} is guaranteed to never be called again.
*
* <p>If this method throws an exception, it will propagate outward to the
* {@code hasNext} or {@code next} invocation that invoked this method. Any
* further attempts to use the iterator will result in an {@link
* IllegalStateException}.
*
* <p>The implementation of this method may not invoke the {@code hasNext},
* {@code next}, or {@link #peek()} methods on this instance; if it does, an
* {@code IllegalStateException} will result.
*
* @return the next element if there was one. If {@code endOfData} was called
* during execution, the return value will be ignored.
* @throws RuntimeException if any unrecoverable error happens. This exception
* will propagate outward to the {@code hasNext()}, {@code next()}, or
* {@code peek()} invocation that invoked this method. Any further
* attempts to use the iterator will result in an
* {@link IllegalStateException}.
*/
protected abstract T computeNext();
/**
* Implementations of {@link #computeNext} <b>must</b> invoke this method when
* there are no elements left in the iteration.
*
* @return {@code null}; a convenience so your {@code computeNext}
* implementation can use the simple statement {@code return endOfData();}
*/
protected final T endOfData() {
state = State.DONE;
return null;
}
@Override
public final boolean hasNext() {
checkState(state != State.FAILED);
switch (state) {
case DONE:
return false;
case READY:
return true;
default:
}
return tryToComputeNext();
}
private boolean tryToComputeNext() {
state = State.FAILED; // temporary pessimism
next = computeNext();
if (state != State.DONE) {
state = State.READY;
return true;
}
return false;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
state = State.NOT_READY;
return next;
}
/**
* Returns the next element in the iteration without advancing the iteration,
* according to the contract of {@link PeekingIterator#peek()}.
*
* <p>Implementations of {@code AbstractIterator} that wish to expose this
* functionality should implement {@code PeekingIterator}.
*/
public final T peek() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return next;
}
}
| 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 java.util.NoSuchElementException;
/**
* A sorted set of contiguous values in a given {@link DiscreteDomain}.
*
* @author Gregory Kick
* @since 10.0
*/
@Beta
@GwtCompatible
@SuppressWarnings("unchecked") // allow ungenerified Comparable types
public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
final DiscreteDomain<C> domain;
ContiguousSet(DiscreteDomain<C> domain) {
super(Ordering.natural());
this.domain = domain;
}
@Override public ContiguousSet<C> headSet(C toElement) {
return headSet(checkNotNull(toElement), false);
}
@Override 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 subSet(fromElement, true, toElement, false);
}
@Override 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 tailSet(checkNotNull(fromElement), true);
}
@Override 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) 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.collect.BstOperations.extractMax;
import static com.google.common.collect.BstOperations.extractMin;
import static com.google.common.collect.BstOperations.insertMax;
import static com.google.common.collect.BstOperations.insertMin;
import static com.google.common.collect.BstSide.LEFT;
import static com.google.common.collect.BstSide.RIGHT;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* A tree-size-based set of balancing policies, based on <a
* href="http://www.swiss.ai.mit.edu/~adams/BB/"> Stephen Adams, "Efficient sets: a balancing
* act."</a>.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class BstCountBasedBalancePolicies {
private BstCountBasedBalancePolicies() {}
private static final int SINGLE_ROTATE_RATIO = 4;
private static final int SECOND_ROTATE_RATIO = 2;
/**
* Returns a balance policy that does no balancing or the bare minimum (for {@code combine}).
*/
public static <N extends BstNode<?, N>> BstBalancePolicy<N> noRebalancePolicy(
final BstAggregate<N> countAggregate) {
checkNotNull(countAggregate);
return new BstBalancePolicy<N>() {
@Override
public N balance(
BstNodeFactory<N> nodeFactory, N source, @Nullable N left, @Nullable N right) {
return checkNotNull(nodeFactory).createNode(source, left, right);
}
@Nullable
@Override
public N combine(BstNodeFactory<N> nodeFactory, @Nullable N left, @Nullable N right) {
if (left == null) {
return right;
} else if (right == null) {
return left;
} else if (countAggregate.treeValue(left) > countAggregate.treeValue(right)) {
return nodeFactory.createNode(
left, left.childOrNull(LEFT), combine(nodeFactory, left.childOrNull(RIGHT), right));
} else {
return nodeFactory.createNode(right, combine(nodeFactory, left, right.childOrNull(LEFT)),
right.childOrNull(RIGHT));
}
}
};
}
/**
* Returns a balance policy that expects the sizes of each side to be at most one node (added or
* removed) away from being balanced. {@code balance} takes {@code O(1)} time, and {@code
* combine} takes {@code O(log n)} time.
*/
public static <K, N extends BstNode<K, N>> BstBalancePolicy<N> singleRebalancePolicy(
final BstAggregate<N> countAggregate) {
checkNotNull(countAggregate);
return new BstBalancePolicy<N>() {
@Override
public N balance(
BstNodeFactory<N> nodeFactory, N source, @Nullable N left, @Nullable N right) {
long countL = countAggregate.treeValue(left);
long countR = countAggregate.treeValue(right);
if (countL + countR > 1) {
if (countR >= SINGLE_ROTATE_RATIO * countL) {
return rotateL(nodeFactory, source, left, right);
} else if (countL >= SINGLE_ROTATE_RATIO * countR) {
return rotateR(nodeFactory, source, left, right);
}
}
return nodeFactory.createNode(source, left, right);
}
private N rotateL(BstNodeFactory<N> nodeFactory, N source, @Nullable N left, N right) {
checkNotNull(right);
N rl = right.childOrNull(LEFT);
N rr = right.childOrNull(RIGHT);
if (countAggregate.treeValue(rl) >= SECOND_ROTATE_RATIO * countAggregate.treeValue(rr)) {
right = singleR(nodeFactory, right, rl, rr);
}
return singleL(nodeFactory, source, left, right);
}
private N rotateR(BstNodeFactory<N> nodeFactory, N source, N left, @Nullable N right) {
checkNotNull(left);
N lr = left.childOrNull(RIGHT);
N ll = left.childOrNull(LEFT);
if (countAggregate.treeValue(lr) >= SECOND_ROTATE_RATIO * countAggregate.treeValue(ll)) {
left = singleL(nodeFactory, left, ll, lr);
}
return singleR(nodeFactory, source, left, right);
}
private N singleL(BstNodeFactory<N> nodeFactory, N source, @Nullable N left, N right) {
checkNotNull(right);
return nodeFactory.createNode(right,
nodeFactory.createNode(source, left, right.childOrNull(LEFT)),
right.childOrNull(RIGHT));
}
private N singleR(BstNodeFactory<N> nodeFactory, N source, N left, @Nullable N right) {
checkNotNull(left);
return nodeFactory.createNode(left, left.childOrNull(LEFT),
nodeFactory.createNode(source, left.childOrNull(RIGHT), right));
}
@Nullable
@Override
public N combine(BstNodeFactory<N> nodeFactory, @Nullable N left, @Nullable N right) {
if (left == null) {
return right;
} else if (right == null) {
return left;
}
N newRootSource;
if (countAggregate.treeValue(left) > countAggregate.treeValue(right)) {
BstMutationResult<K, N> extractLeftMax = extractMax(left, nodeFactory, this);
newRootSource = extractLeftMax.getOriginalTarget();
left = extractLeftMax.getChangedRoot();
} else {
BstMutationResult<K, N> extractRightMin = extractMin(right, nodeFactory, this);
newRootSource = extractRightMin.getOriginalTarget();
right = extractRightMin.getChangedRoot();
}
return nodeFactory.createNode(newRootSource, left, right);
}
};
}
/**
* Returns a balance policy that makes no assumptions on the relative balance of the two sides
* and performs a full rebalancing as necessary. Both {@code balance} and {@code combine} take
* {@code O(log n)} time.
*/
public static <K, N extends BstNode<K, N>> BstBalancePolicy<N> fullRebalancePolicy(
final BstAggregate<N> countAggregate) {
checkNotNull(countAggregate);
final BstBalancePolicy<N> singleBalancePolicy =
BstCountBasedBalancePolicies.<K, N>singleRebalancePolicy(countAggregate);
return new BstBalancePolicy<N>() {
@Override
public N balance(
BstNodeFactory<N> nodeFactory, N source, @Nullable N left, @Nullable N right) {
if (left == null) {
return insertMin(right, source, nodeFactory, singleBalancePolicy);
} else if (right == null) {
return insertMax(left, source, nodeFactory, singleBalancePolicy);
}
long countL = countAggregate.treeValue(left);
long countR = countAggregate.treeValue(right);
if (SINGLE_ROTATE_RATIO * countL <= countR) {
N resultLeft = balance(nodeFactory, source, left, right.childOrNull(LEFT));
return singleBalancePolicy.balance(
nodeFactory, right, resultLeft, right.childOrNull(RIGHT));
} else if (SINGLE_ROTATE_RATIO * countR <= countL) {
N resultRight = balance(nodeFactory, source, left.childOrNull(RIGHT), right);
return singleBalancePolicy.balance(
nodeFactory, left, left.childOrNull(LEFT), resultRight);
} else {
return nodeFactory.createNode(source, left, right);
}
}
@Nullable
@Override
public N combine(BstNodeFactory<N> nodeFactory, @Nullable N left, @Nullable N right) {
if (left == null) {
return right;
} else if (right == null) {
return left;
}
long countL = countAggregate.treeValue(left);
long countR = countAggregate.treeValue(right);
if (SINGLE_ROTATE_RATIO * countL <= countR) {
N resultLeft = combine(nodeFactory, left, right.childOrNull(LEFT));
return singleBalancePolicy.balance(
nodeFactory, right, resultLeft, right.childOrNull(RIGHT));
} else if (SINGLE_ROTATE_RATIO * countR <= countL) {
N resultRight = combine(nodeFactory, left.childOrNull(RIGHT), right);
return singleBalancePolicy.balance(
nodeFactory, left, left.childOrNull(LEFT), resultRight);
} else {
return singleBalancePolicy.combine(nodeFactory, left, right);
}
}
};
}
}
| 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 binarySearch(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 binarySearch(Object key) {
// TODO(kevinb): split this into binarySearch(E) and
// unsafeBinarySearch(Object), use each appropriately. name all methods that
// might throw CCE "unsafe*".
// Pretend the comparator can compare anything. If it turns out it can't
// compare a and b, we should get a CCE on the subsequent line. Only methods
// that are spec'd to throw CCE should call this.
@SuppressWarnings("unchecked")
Comparator<Object> unsafeComparator = (Comparator<Object>) comparator;
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) {
int index;
if (inclusive) {
index = SortedLists.binarySearch(
elements, checkNotNull(toElement), comparator(), FIRST_AFTER, NEXT_HIGHER);
} else {
index = SortedLists.binarySearch(
elements, checkNotNull(toElement), comparator(), FIRST_PRESENT, NEXT_HIGHER);
}
return createSubset(0, index);
}
@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) {
int index;
if (inclusive) {
index = SortedLists.binarySearch(
elements, checkNotNull(fromElement), comparator(), FIRST_PRESENT, NEXT_HIGHER);
} else {
index = SortedLists.binarySearch(
elements, checkNotNull(fromElement), comparator(), FIRST_AFTER, NEXT_HIGHER);
}
return createSubset(index, size());
}
// 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;
}
private ImmutableSortedSet<E> createSubset(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);
}
}
@SuppressWarnings("unchecked")
@Override int indexOf(@Nullable Object target) {
if (target == null) {
return -1;
}
int position;
try {
position = SortedLists.binarySearch(elements, (E) target, comparator(),
ANY_PRESENT, INVERTED_INSERTION_INDEX);
} catch (ClassCastException e) {
return -1;
}
// TODO(kevinb): reconsider if it's really worth making feeble attempts at
// sanity for inconsistent comparators.
// The equals() check is needed when the comparator isn't compatible with
// equals().
return (position >= 0 && elements.get(position).equals(target))
? position : -1;
}
@Override ImmutableList<E> createAsList() {
return new ImmutableSortedAsList<E>(this, elements);
}
}
| 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) 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.checkState;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* A path to a node in a binary search tree, originating at the root.
*
* @author Louis Wasserman
* @param <N> The type of nodes in this binary search tree.
* @param <P> This path type, and the path type of all suffix paths.
*/
@GwtCompatible
abstract class BstPath<N extends BstNode<?, N>, P extends BstPath<N, P>> {
private final N tip;
@Nullable
private final P prefix;
BstPath(N tip, @Nullable P prefix) {
this.tip = checkNotNull(tip);
this.prefix = prefix;
}
/**
* Return the end of this {@code BstPath}, the deepest node in the path.
*/
public final N getTip() {
return tip;
}
/**
* Returns {@code true} if this path has a prefix.
*/
public final boolean hasPrefix() {
return prefix != null;
}
/**
* Returns the prefix of this path, which reaches to the parent of the end of this path. Returns
* {@code null} if this path has no prefix.
*/
@Nullable
public final P prefixOrNull() {
return prefix;
}
/**
* Returns the prefix of this path, which reaches to the parent of the end of this path.
*
* @throws IllegalStateException if this path has no prefix.
*/
public final P getPrefix() {
checkState(hasPrefix());
return prefix;
}
}
| 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) 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 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Multisets.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.primitives.Ints;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Basic implementation of {@code Multiset<E>} backed by an instance of {@code
* Map<E, AtomicInteger>}.
*
* <p>For serialization to work, the subclass must specify explicit {@code
* readObject} and {@code writeObject} methods.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E>
implements Serializable {
private transient Map<E, Count> backingMap;
/*
* Cache the size for efficiency. Using a long lets us avoid the need for
* overflow checking and ensures that size() will function correctly even if
* the multiset had once been larger than Integer.MAX_VALUE.
*/
private transient long size;
/** Standard constructor. */
protected AbstractMapBasedMultiset(Map<E, Count> backingMap) {
this.backingMap = checkNotNull(backingMap);
this.size = super.size();
}
Map<E, Count> backingMap() {
return backingMap;
}
/** Used during deserialization only. The backing map must be empty. */
void setBackingMap(Map<E, Count> backingMap) {
this.backingMap = backingMap;
}
// Required Implementations
/**
* {@inheritDoc}
*
* <p>Invoking {@link Multiset.Entry#getCount} on an entry in the returned
* set always returns the current count of that element in the multiset, as
* opposed to the count at the time the entry was retrieved.
*/
@Override
public Set<Multiset.Entry<E>> entrySet() {
return super.entrySet();
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Count>> backingEntries =
backingMap.entrySet().iterator();
return new Iterator<Multiset.Entry<E>>() {
Map.Entry<E, Count> toRemove;
@Override
public boolean hasNext() {
return backingEntries.hasNext();
}
@Override
public Multiset.Entry<E> next() {
final Map.Entry<E, Count> mapEntry = backingEntries.next();
toRemove = mapEntry;
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return mapEntry.getKey();
}
@Override
public int getCount() {
int count = mapEntry.getValue().get();
if (count == 0) {
Count frequency = backingMap.get(getElement());
if (frequency != null) {
count = frequency.get();
}
}
return count;
}
};
}
@Override
public void remove() {
checkState(toRemove != null,
"no calls to next() since the last call to remove()");
size -= toRemove.getValue().getAndSet(0);
backingEntries.remove();
toRemove = null;
}
};
}
@Override
public void clear() {
for (Count frequency : backingMap.values()) {
frequency.set(0);
}
backingMap.clear();
size = 0L;
}
@Override
int distinctElements() {
return backingMap.size();
}
// Optimizations - Query Operations
@Override public int size() {
return Ints.saturatedCast(size);
}
@Override public Iterator<E> iterator() {
return new MapBasedMultisetIterator();
}
/*
* Not subclassing AbstractMultiset$MultisetIterator because next() needs to
* retrieve the Map.Entry<E, AtomicInteger> entry, which can then be used for
* a more efficient remove() call.
*/
private class MapBasedMultisetIterator implements Iterator<E> {
final Iterator<Map.Entry<E, Count>> entryIterator;
Map.Entry<E, Count> currentEntry;
int occurrencesLeft;
boolean canRemove;
MapBasedMultisetIterator() {
this.entryIterator = backingMap.entrySet().iterator();
}
@Override
public boolean hasNext() {
return occurrencesLeft > 0 || entryIterator.hasNext();
}
@Override
public E next() {
if (occurrencesLeft == 0) {
currentEntry = entryIterator.next();
occurrencesLeft = currentEntry.getValue().get();
}
occurrencesLeft--;
canRemove = true;
return currentEntry.getKey();
}
@Override
public void remove() {
checkState(canRemove,
"no calls to next() since the last call to remove()");
int frequency = currentEntry.getValue().get();
if (frequency <= 0) {
throw new ConcurrentModificationException();
}
if (currentEntry.getValue().addAndGet(-1) == 0) {
entryIterator.remove();
}
size--;
canRemove = false;
}
}
@Override public int count(@Nullable Object element) {
try {
Count frequency = backingMap.get(element);
return (frequency == null) ? 0 : frequency.get();
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
// Optional Operations - Modification Operations
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the call would result in more than
* {@link Integer#MAX_VALUE} occurrences of {@code element} in this
* multiset.
*/
@Override public int add(@Nullable E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
int oldCount;
if (frequency == null) {
oldCount = 0;
backingMap.put(element, new Count(occurrences));
} else {
oldCount = frequency.get();
long newCount = (long) oldCount + (long) occurrences;
checkArgument(newCount <= Integer.MAX_VALUE,
"too many occurrences: %s", newCount);
frequency.getAndAdd(occurrences);
}
size += occurrences;
return oldCount;
}
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
if (frequency == null) {
return 0;
}
int oldCount = frequency.get();
int numberRemoved;
if (oldCount > occurrences) {
numberRemoved = occurrences;
} else {
numberRemoved = oldCount;
backingMap.remove(element);
}
frequency.addAndGet(-numberRemoved);
size -= numberRemoved;
return oldCount;
}
// Roughly a 33% performance improvement over AbstractMultiset.setCount().
@Override public int setCount(E element, int count) {
checkNonnegative(count, "count");
Count existingCounter;
int oldCount;
if (count == 0) {
existingCounter = backingMap.remove(element);
oldCount = getAndSet(existingCounter, count);
} else {
existingCounter = backingMap.get(element);
oldCount = getAndSet(existingCounter, count);
if (existingCounter == null) {
backingMap.put(element, new Count(count));
}
}
size += (count - oldCount);
return oldCount;
}
private static int getAndSet(Count i, int count) {
if (i == null) {
return 0;
}
return i.getAndSet(count);
}
private int removeAllOccurrences(@Nullable Object element,
Map<E, Count> map) {
Count frequency = map.remove(element);
if (frequency == null) {
return 0;
}
int numberRemoved = frequency.getAndSet(0);
size -= numberRemoved;
return numberRemoved;
}
// Views
@Override Set<E> createElementSet() {
return new MapBasedElementSet(backingMap);
}
// TODO(user): once TreeMultiset is replaced with a SortedMultiset
// implementation, replace this with a subclass of Multisets.ElementSet.
class MapBasedElementSet extends ForwardingSet<E> {
// This mapping is the usually the same as 'backingMap', but can be a
// submap in some implementations.
private final Map<E, Count> map;
private final Set<E> delegate;
MapBasedElementSet(Map<E, Count> map) {
this.map = map;
delegate = map.keySet();
}
@Override protected Set<E> delegate() {
return delegate;
}
@Override public Iterator<E> iterator() {
final Iterator<Map.Entry<E, Count>> entries
= map.entrySet().iterator();
return new Iterator<E>() {
Map.Entry<E, Count> toRemove;
@Override
public boolean hasNext() {
return entries.hasNext();
}
@Override
public E next() {
toRemove = entries.next();
return toRemove.getKey();
}
@Override
public void remove() {
checkState(toRemove != null,
"no calls to next() since the last call to remove()");
size -= toRemove.getValue().getAndSet(0);
entries.remove();
toRemove = null;
}
};
}
@Override public boolean remove(Object element) {
return removeAllOccurrences(element, map) != 0;
}
@Override public boolean removeAll(Collection<?> elementsToRemove) {
return Iterators.removeAll(iterator(), elementsToRemove);
}
@Override public boolean retainAll(Collection<?> elementsToRetain) {
return Iterators.retainAll(iterator(), elementsToRetain);
}
@Override public void clear() {
if (map == backingMap) {
AbstractMapBasedMultiset.this.clear();
} else {
Iterator<E> i = iterator();
while (i.hasNext()) {
i.next();
i.remove();
}
}
}
public Map<E, Count> getMap() {
return map;
}
}
// Don't allow default serialization.
@GwtIncompatible("java.io.ObjectStreamException")
@SuppressWarnings("unused") // actually used during deserialization
private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("Stream data required");
}
@GwtIncompatible("not needed in emulated source.")
private static final long serialVersionUID = -2250766705698539974L;
}
| 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.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.MapMaker.RemovalListener;
import com.google.common.collect.MapMaker.RemovalNotification;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* A class exactly like {@link MapMaker}, except restricted in the types of maps it can build.
* For the most part, you should probably just ignore the existence of this class.
*
* @param <K0> the base type for all key types of maps built by this map maker
* @param <V0> the base type for all value types of maps built by this map maker
* @author Kevin Bourrillion
* @since 7.0
*/
@Beta
@GwtCompatible(emulated = true)
public abstract class GenericMapMaker<K0, V0> {
@GwtIncompatible("To be supported")
enum NullListener implements RemovalListener<Object, Object> {
INSTANCE;
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {}
}
// Set by MapMaker, but sits in this class to preserve the type relationship
@GwtIncompatible("To be supported")
RemovalListener<K0, V0> removalListener;
// No subclasses but our own
GenericMapMaker() {}
/**
* See {@link MapMaker#keyEquivalence}.
*/
@GwtIncompatible("To be supported")
abstract GenericMapMaker<K0, V0> keyEquivalence(Equivalence<Object> equivalence);
/**
* See {@link MapMaker#valueEquivalence}.
*/
@GwtIncompatible("To be supported")
abstract GenericMapMaker<K0, V0> valueEquivalence(Equivalence<Object> equivalence);
/**
* See {@link MapMaker#initialCapacity}.
*/
public abstract GenericMapMaker<K0, V0> initialCapacity(int initialCapacity);
/**
* See {@link MapMaker#maximumSize}.
*/
abstract GenericMapMaker<K0, V0> maximumSize(int maximumSize);
/**
* See {@link MapMaker#strongKeys}.
*/
abstract GenericMapMaker<K0, V0> strongKeys();
/**
* See {@link MapMaker#concurrencyLevel}.
*/
public abstract GenericMapMaker<K0, V0> concurrencyLevel(int concurrencyLevel);
/**
* See {@link MapMaker#weakKeys}.
*/
@GwtIncompatible("java.lang.ref.WeakReference")
public abstract GenericMapMaker<K0, V0> weakKeys();
/**
* See {@link MapMaker#strongValues}.
*/
abstract GenericMapMaker<K0, V0> strongValues();
/**
* See {@link MapMaker#softKeys}.
*/
@Deprecated
@GwtIncompatible("java.lang.ref.SoftReference")
public abstract GenericMapMaker<K0, V0> softKeys();
/**
* See {@link MapMaker#weakValues}.
*/
@GwtIncompatible("java.lang.ref.WeakReference")
public abstract GenericMapMaker<K0, V0> weakValues();
/**
* See {@link MapMaker#softValues}.
*/
@GwtIncompatible("java.lang.ref.SoftReference")
public abstract GenericMapMaker<K0, V0> softValues();
/**
* See {@link MapMaker#expiration}.
*/
@Deprecated
public
abstract GenericMapMaker<K0, V0> expiration(long duration, TimeUnit unit);
/**
* See {@link MapMaker#expireAfterWrite}.
*/
abstract GenericMapMaker<K0, V0> expireAfterWrite(long duration, TimeUnit unit);
/**
* See {@link MapMaker#expireAfterAccess}.
*/
@GwtIncompatible("To be supported")
abstract GenericMapMaker<K0, V0> expireAfterAccess(long duration, TimeUnit unit);
/*
* Note that MapMaker's removalListener() is not here, because once you're interacting with a
* GenericMapMaker you've already called that, and shouldn't be calling it again.
*/
@SuppressWarnings("unchecked") // safe covariant cast
@GwtIncompatible("To be supported")
<K extends K0, V extends V0> RemovalListener<K, V> getRemovalListener() {
return (RemovalListener<K, V>) Objects.firstNonNull(removalListener, NullListener.INSTANCE);
}
/**
* See {@link MapMaker#makeMap}.
*/
public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeMap();
/**
* See {@link MapMaker#makeCustomMap}.
*/
@GwtIncompatible("MapMakerInternalMap")
abstract <K, V> MapMakerInternalMap<K, V> makeCustomMap();
/**
* See {@link MapMaker#makeComputingMap}.
*/
@Deprecated
public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction);
}
| 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.io.Serializable;
import javax.annotation.Nullable;
/**
* A mutable value of type {@code int}, for multisets to use in tracking counts of values.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class Count implements Serializable {
private int value;
Count() {
this(0);
}
Count(int value) {
this.value = value;
}
public int get() {
return value;
}
public int getAndAdd(int delta) {
int result = value;
value = result + delta;
return result;
}
public int addAndGet(int delta) {
return value += delta;
}
public void set(int newValue) {
value = newValue;
}
public int getAndSet(int newValue) {
int result = value;
value = newValue;
return result;
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(@Nullable Object obj) {
return obj instanceof Count && ((Count) obj).value == value;
}
@Override
public String toString() {
return Integer.toString(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 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 = 10;
@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) 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.Preconditions;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableSet} with exactly one element.
*
* @author Kevin Bourrillion
* @author Nick Kralevich
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class SingletonImmutableSet<E> extends ImmutableSet<E> {
final transient E element;
// This is transient because it will be recalculated on the first
// call to hashCode().
//
// A race condition is avoided since threads will either see that the value
// is zero and recalculate it themselves, or two threads will see it at
// the same time, and both recalculate it. If the cachedHashCode is 0,
// it will always be recalculated, unfortunately.
private transient int cachedHashCode;
SingletonImmutableSet(E element) {
this.element = Preconditions.checkNotNull(element);
}
SingletonImmutableSet(E element, int hashCode) {
// Guaranteed to be non-null by the presence of the pre-computed hash code.
this.element = element;
cachedHashCode = hashCode;
}
@Override
public int size() {
return 1;
}
@Override public boolean isEmpty() {
return false;
}
@Override public boolean contains(Object target) {
return element.equals(target);
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.singletonIterator(element);
}
@Override boolean isPartialView() {
return false;
}
@Override public Object[] toArray() {
return new Object[] { element };
}
@Override public <T> T[] toArray(T[] array) {
if (array.length == 0) {
array = ObjectArrays.newArray(array, 1);
} else if (array.length > 1) {
array[1] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires.
Object[] objectArray = array;
objectArray[0] = element;
return array;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.size() == 1 && element.equals(that.iterator().next());
}
return false;
}
@Override public final int hashCode() {
// Racy single-check.
int code = cachedHashCode;
if (code == 0) {
cachedHashCode = code = element.hashCode();
}
return code;
}
@Override boolean isHashCodeFast() {
return cachedHashCode != 0;
}
@Override public String toString() {
String elementToString = element.toString();
return new StringBuilder(elementToString.length() + 2)
.append('[')
.append(elementToString)
.append(']')
.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.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.SortedMap;
/**
* An object representing the differences between two sorted maps.
*
* @author Louis Wasserman
* @since 8.0
*/
@Beta
@GwtCompatible
public interface SortedMapDifference<K, V> extends MapDifference<K, V> {
@Override
SortedMap<K, V> entriesOnlyOnLeft();
@Override
SortedMap<K, V> entriesOnlyOnRight();
@Override
SortedMap<K, V> entriesInCommon();
@Override
SortedMap<K, ValueDifference<V>> entriesDiffering();
}
| 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;
/**
* A side of a binary search tree node, used to index its children.
*
* @author Louis Wasserman
*/
@GwtCompatible
enum BstSide {
LEFT {
@Override
public BstSide other() {
return RIGHT;
}
},
RIGHT {
@Override
public BstSide other() {
return LEFT;
}
};
abstract BstSide other();
}
| 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;
}
//Abstract method doesn't exist in 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);
}
}
| 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.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.
*
* @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 = Sets.transform(
delegate.keySet(), new KeyToEntryConverter<K, V>(this));
}
private static class KeyToEntryConverter<K, V>
extends Sets.InvertibleFunction<K, Map.Entry<K, V>> {
final Map<K, V> map;
KeyToEntryConverter(Map<K, V> map) {
this.map = map;
}
@Override public Map.Entry<K, V> apply(final K key) {
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return key;
}
@Override public V getValue() {
return map.get(key);
}
@Override public V setValue(V value) {
return map.put(key, value);
}
};
}
@Override public K invert(Map.Entry<K, V> entry) {
return entry.getKey();
}
}
}
| 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 javax.annotation.Nullable;
/**
* An empty immutable multiset.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
final class EmptyImmutableMultiset extends ImmutableMultiset<Object> {
static final EmptyImmutableMultiset INSTANCE = new EmptyImmutableMultiset();
@Override
public int count(@Nullable Object element) {
return 0;
}
@Override
public ImmutableSet<Object> elementSet() {
return ImmutableSet.of();
}
@Override
public int size() {
return 0;
}
@Override
UnmodifiableIterator<Entry<Object>> entryIterator() {
return Iterators.emptyIterator();
}
@Override
int distinctElements() {
return 0;
}
@Override
boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<Object>> createEntrySet() {
return ImmutableSet.of();
}
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 com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@link BiMap} backed by two {@link HashMap} instances. This implementation
* allows null keys and values. A {@code HashBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class HashBiMap<K, V> extends AbstractBiMap<K, V> {
/**
* Returns a new, empty {@code HashBiMap} with the default initial capacity
* (16).
*/
public static <K, V> HashBiMap<K, V> create() {
return new HashBiMap<K, V>();
}
/**
* Constructs a new, empty bimap with the specified expected size.
*
* @param expectedSize the expected number of entries
* @throws IllegalArgumentException if the specified expected size is
* negative
*/
public static <K, V> HashBiMap<K, V> create(int expectedSize) {
return new HashBiMap<K, V>(expectedSize);
}
/**
* Constructs a new bimap containing initial values from {@code map}. The
* bimap is created with an initial capacity sufficient to hold the mappings
* in the specified map.
*/
public static <K, V> HashBiMap<K, V> create(
Map<? extends K, ? extends V> map) {
HashBiMap<K, V> bimap = create(map.size());
bimap.putAll(map);
return bimap;
}
private HashBiMap() {
super(new HashMap<K, V>(), new HashMap<V, K>());
}
private HashBiMap(int expectedSize) {
super(
Maps.<K, V>newHashMapWithExpectedSize(expectedSize),
Maps.<V, K>newHashMapWithExpectedSize(expectedSize));
}
// Override these two methods to show that keys and values may be null
@Override public V put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(@Nullable K key, @Nullable V value) {
return super.forcePut(key, value);
}
/**
* @serialData the number of entries, first key, first value, second key,
* second value, and so on.
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMap(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int size = Serialization.readCount(stream);
setDelegates(Maps.<K, V>newHashMapWithExpectedSize(size),
Maps.<V, K>newHashMapWithExpectedSize(size));
Serialization.populateMap(this, stream, size);
}
@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;
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 UnmodifiableIterator<E> iterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
private static final Object[] EMPTY_ARRAY = new Object[0];
@Override public Object[] toArray() {
return EMPTY_ARRAY;
}
@Override public <T> T[] toArray(T[] a) {
if (a.length > 0) {
a[0] = null;
}
return a;
}
@Override public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@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;
}
}
| 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.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.annotation.Nullable;
/**
* A list which forwards all its method calls to another list. Subclasses should
* override one or more methods to modify the behavior of the backing list as
* desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p>This class does not implement {@link java.util.RandomAccess}. If the
* delegate supports random access, the {@code ForwardingList} subclass should
* implement the {@code RandomAccess} interface.
*
* <p><b>Warning:</b> The methods of {@code ForwardingList} 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 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 Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingList<E> extends ForwardingCollection<E>
implements List<E> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingList() {}
@Override protected abstract List<E> delegate();
@Override
public void add(int index, E element) {
delegate().add(index, element);
}
@Override
public boolean addAll(int index, Collection<? extends E> elements) {
return delegate().addAll(index, elements);
}
@Override
public E get(int index) {
return delegate().get(index);
}
@Override
public int indexOf(Object element) {
return delegate().indexOf(element);
}
@Override
public int lastIndexOf(Object element) {
return delegate().lastIndexOf(element);
}
@Override
public ListIterator<E> listIterator() {
return delegate().listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate().listIterator(index);
}
@Override
public E remove(int index) {
return delegate().remove(index);
}
@Override
public E set(int index, E element) {
return delegate().set(index, element);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return delegate().subList(fromIndex, toIndex);
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
/**
* A sensible default implementation of {@link #add(Object)}, in terms of
* {@link #add(int, Object)}. If you override {@link #add(int, Object)}, you
* may wish to override {@link #add(Object)} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected boolean standardAdd(E element){
add(size(), element);
return true;
}
/**
* A sensible default implementation of {@link #addAll(int, Collection)}, in
* terms of the {@code add} method of {@link #listIterator(int)}. If you
* override {@link #listIterator(int)}, you may wish to override {@link
* #addAll(int, Collection)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardAddAll(
int index, Iterable<? extends E> elements) {
return Lists.addAllImpl(this, index, elements);
}
/**
* A sensible default implementation of {@link #indexOf}, in terms of {@link
* #listIterator()}. If you override {@link #listIterator()}, you may wish to
* override {@link #indexOf} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardIndexOf(@Nullable Object element) {
return Lists.indexOfImpl(this, element);
}
/**
* A sensible default implementation of {@link #lastIndexOf}, in terms of
* {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you
* may wish to override {@link #lastIndexOf} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected int standardLastIndexOf(@Nullable Object element) {
return Lists.lastIndexOfImpl(this, element);
}
/**
* A sensible default implementation of {@link #iterator}, in terms of
* {@link #listIterator()}. If you override {@link #listIterator()}, you may
* wish to override {@link #iterator} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected Iterator<E> standardIterator() {
return listIterator();
}
/**
* A sensible default implementation of {@link #listIterator()}, in terms of
* {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you
* may wish to override {@link #listIterator()} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected ListIterator<E> standardListIterator(){
return listIterator(0);
}
/**
* A sensible default implementation of {@link #listIterator(int)}, in terms
* of {@link #size} and {@link #get(int)}. If you override either of these
* methods you may wish to override {@link #listIterator(int)} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta protected ListIterator<E> standardListIterator(int start) {
return Lists.listIteratorImpl(this, start);
}
/**
* A sensible default implementation of {@link #subList(int, int)}. If you
* override any other methods, you may wish to override {@link #subList(int,
* int)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected List<E> standardSubList(int fromIndex, int toIndex) {
return Lists.subListImpl(this, fromIndex, toIndex);
}
/**
* A sensible definition of {@link #equals(Object)} in terms of {@link #size}
* and {@link #iterator}. If you override either of those methods, you may
* wish to override {@link #equals(Object)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardEquals(@Nullable Object object) {
return Lists.equalsImpl(this, object);
}
/**
* A sensible definition of {@link #hashCode} in terms of {@link #iterator}.
* If you override {@link #iterator}, you may wish to override {@link
* #hashCode} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardHashCode() {
return Lists.hashCodeImpl(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 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 AbstractSet<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 removeAll(Collection<?> c) {
boolean changed = false;
for (Object obj : c) {
changed |= remove(obj);
}
return changed;
}
@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 AbstractSet<R> {
@Override public Iterator<R> iterator() {
return keyIteratorImpl(Column.this);
}
@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 removeAll(final Collection<?> c) {
boolean changed = false;
for (Object obj : c) {
changed |= remove(obj);
}
return changed;
}
@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 valueIteratorImpl(Column.this);
}
@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 keyIteratorImpl(rowMap());
}
@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() {
final Iterator<Cell<R, C, V>> cellIterator = cellSet().iterator();
return new Iterator<V>() {
@Override public boolean hasNext() {
return cellIterator.hasNext();
}
@Override public V next() {
return cellIterator.next().getValue();
}
@Override public void remove() {
cellIterator.remove();
}
};
}
@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 EntryIterator();
}
@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;
}
}
class EntryIterator implements Iterator<Entry<R, Map<C, V>>> {
final Iterator<R> delegate = backingMap.keySet().iterator();
@Override public boolean hasNext() {
return delegate.hasNext();
}
@Override public Entry<R, Map<C, V>> next() {
R rowKey = delegate.next();
return new ImmutableEntry<R, Map<C, V>>(rowKey, row(rowKey));
}
@Override public void remove() {
delegate.remove();
}
}
}
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() {
final Iterator<C> columnIterator = columnKeySet().iterator();
return new UnmodifiableIterator<Entry<C, Map<R, V>>>() {
@Override public boolean hasNext() {
return columnIterator.hasNext();
}
@Override public Entry<C, Map<R, V>> next() {
C columnKey = columnIterator.next();
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 valueIteratorImpl(ColumnMap.this);
}
@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;
// TODO(kevinb): Move keyIteratorImpl and valueIteratorImpl to Maps, reuse
/**
* Generates the iterator of a map's key set from the map's entry set
* iterator.
*/
static <K, V> Iterator<K> keyIteratorImpl(Map<K, V> map) {
final Iterator<Entry<K, V>> entryIterator = map.entrySet().iterator();
return new Iterator<K>() {
@Override public boolean hasNext() {
return entryIterator.hasNext();
}
@Override public K next() {
return entryIterator.next().getKey();
}
@Override public void remove() {
entryIterator.remove();
}
};
}
/**
* Generates the iterator of a map's value collection from the map's entry set
* iterator.
*/
static <K, V> Iterator<V> valueIteratorImpl(Map<K, V> map) {
final Iterator<Entry<K, V>> entryIterator = map.entrySet().iterator();
return new Iterator<V>() {
@Override public boolean hasNext() {
return entryIterator.hasNext();
}
@Override public V next() {
return entryIterator.next().getValue();
}
@Override public void remove() {
entryIterator.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 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.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
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.Iterator;
import java.util.List;
/**
* 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");
// TODO(user): Maybe move the mathematical methods to a separate
// package-permission class.
}
| 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 = 8;
@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) 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 javax.annotation.Nullable;
/**
* An integer-valued function on binary search tree nodes that adds between nodes.
*
* <p>The value of individual entries must fit into an {@code int}, but the value of an entire
* tree can require a {@code long}.
*
* @author Louis Wasserman
*/
@GwtCompatible
interface BstAggregate<N extends BstNode<?, N>> {
/**
* The total value on an entire subtree. Must be equal to the sum of the {@link #entryValue
* entryValue} of this node and all its descendants.
*/
long treeValue(@Nullable N tree);
/**
* The value on a single entry, ignoring its descendants.
*/
int entryValue(N entry);
}
| 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;
import java.util.List;
/** 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);
}
CompoundOrdering(List<? extends Comparator<? super T>> comparators,
Comparator<? super T> lastComparator) {
this.comparators = new ImmutableList.Builder<Comparator<? super T>>()
.addAll(comparators).add(lastComparator).build();
}
@Override public int compare(T left, T right) {
for (Comparator<? super T> comparator : comparators) {
int result = comparator.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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.