code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
/**
* Represents a {@linkplain System#getProperties() standard system property}.
*
* @author Kurt Alfred Kluever
* @since 15.0
*/
@Beta
@GwtIncompatible("java.lang.System#getProperty")
public enum StandardSystemProperty {
/** Java Runtime Environment version. */
JAVA_VERSION("java.version"),
/** Java Runtime Environment vendor. */
JAVA_VENDOR("java.vendor"),
/** Java vendor URL. */
JAVA_VENDOR_URL("java.vendor.url"),
/** Java installation directory. */
JAVA_HOME("java.home"),
/** Java Virtual Machine specification version. */
JAVA_VM_SPECIFICATION_VERSION("java.vm.specification.version"),
/** Java Virtual Machine specification vendor. */
JAVA_VM_SPECIFICATION_VENDOR("java.vm.specification.vendor"),
/** Java Virtual Machine specification name. */
JAVA_VM_SPECIFICATION_NAME("java.vm.specification.name"),
/** Java Virtual Machine implementation version. */
JAVA_VM_VERSION("java.vm.version"),
/** Java Virtual Machine implementation vendor. */
JAVA_VM_VENDOR("java.vm.vendor"),
/** Java Virtual Machine implementation name. */
JAVA_VM_NAME("java.vm.name"),
/** Java Runtime Environment specification version. */
JAVA_SPECIFICATION_VERSION("java.specification.version"),
/** Java Runtime Environment specification vendor. */
JAVA_SPECIFICATION_VENDOR("java.specification.vendor"),
/** Java Runtime Environment specification name. */
JAVA_SPECIFICATION_NAME("java.specification.name"),
/** Java class format version number. */
JAVA_CLASS_VERSION("java.class.version"),
/** Java class path. */
JAVA_CLASS_PATH("java.class.path"),
/** List of paths to search when loading libraries. */
JAVA_LIBRARY_PATH("java.library.path"),
/** Default temp file path. */
JAVA_IO_TMPDIR("java.io.tmpdir"),
/** Name of JIT compiler to use. */
JAVA_COMPILER("java.compiler"),
/** Path of extension directory or directories. */
JAVA_EXT_DIRS("java.ext.dirs"),
/** Operating system name. */
OS_NAME("os.name"),
/** Operating system architecture. */
OS_ARCH("os.arch"),
/** Operating system version. */
OS_VERSION("os.version"),
/** File separator ("/" on UNIX). */
FILE_SEPARATOR("file.separator"),
/** Path separator (":" on UNIX). */
PATH_SEPARATOR("path.separator"),
/** Line separator ("\n" on UNIX). */
LINE_SEPARATOR("line.separator"),
/** User's account name. */
USER_NAME("user.name"),
/** User's home directory. */
USER_HOME("user.home"),
/** User's current working directory. */
USER_DIR("user.dir");
private final String key;
private StandardSystemProperty(String key) {
this.key = key;
}
/**
* Returns the key used to lookup this system property.
*/
public String key() {
return key;
}
/**
* Returns the current value for this system property by delegating to
* {@link System#getProperty(String)}.
*/
public String value() {
return System.getProperty(key);
}
/**
* Returns a string representation of this system property.
*/
@Override public String toString() {
return key() + "=" + value();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/StandardSystemProperty.java | Java | asf20 | 3,838 |
/*
* 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.base;
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.io.Serializable;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code Function} instances.
*
* <p>All methods return serializable functions as long as they're given serializable parameters.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
* Function}</a>.
*
* @author Mike Bostock
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Functions {
private Functions() {}
/**
* Returns a function that calls {@code toString()} on its argument. The function does not accept
* nulls; it will throw a {@link NullPointerException} when applied to {@code null}.
*
* <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as
* documented at {@link Function#apply}). For example, this function yields different results for
* the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}.
*/
public static Function<Object, String> toStringFunction() {
return ToStringFunction.INSTANCE;
}
// enum singleton pattern
private enum ToStringFunction implements Function<Object, String> {
INSTANCE;
@Override
public String apply(Object o) {
checkNotNull(o); // eager for GWT.
return o.toString();
}
@Override public String toString() {
return "toString";
}
}
/**
* Returns the identity function.
*/
// implementation is "fully variant"; E has become a "pass-through" type
@SuppressWarnings("unchecked")
public static <E> Function<E, E> identity() {
return (Function<E, E>) IdentityFunction.INSTANCE;
}
// enum singleton pattern
private enum IdentityFunction implements Function<Object, Object> {
INSTANCE;
@Override
@Nullable
public Object apply(@Nullable Object o) {
return o;
}
@Override public String toString() {
return "identity";
}
}
/**
* Returns a function which performs a map lookup. The returned function throws an {@link
* IllegalArgumentException} if given a key that does not exist in the map. See also {@link
* #forMap(Map, Object)}, which returns a default value in this case.
*
* <p>Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or can be one), you
* can use {@link com.google.common.collect.Maps#asConverter Maps.asConverter} instead to get a
* function that also supports reverse conversion.
*/
public static <K, V> Function<K, V> forMap(Map<K, V> map) {
return new FunctionForMapNoDefault<K, V>(map);
}
private static class FunctionForMapNoDefault<K, V> implements Function<K, V>, Serializable {
final Map<K, V> map;
FunctionForMapNoDefault(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public V apply(@Nullable K key) {
V result = map.get(key);
checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
return result;
}
@Override public boolean equals(@Nullable Object o) {
if (o instanceof FunctionForMapNoDefault) {
FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
return map.equals(that.map);
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
@Override public String toString() {
return "forMap(" + map + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a function which performs a map lookup with a default value. The function created by
* this method returns {@code defaultValue} for all inputs that do not belong to the map's key
* set. See also {@link #forMap(Map)}, which throws an exception in this case.
*
* @param map source map that determines the function behavior
* @param defaultValue the value to return for inputs that aren't map keys
* @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code
* defaultValue} otherwise
*/
public static <K, V> Function<K, V> forMap(Map<K, ? extends V> map, @Nullable V defaultValue) {
return new ForMapWithDefault<K, V>(map, defaultValue);
}
private static class ForMapWithDefault<K, V> implements Function<K, V>, Serializable {
final Map<K, ? extends V> map;
final V defaultValue;
ForMapWithDefault(Map<K, ? extends V> map, @Nullable V defaultValue) {
this.map = checkNotNull(map);
this.defaultValue = defaultValue;
}
@Override
public V apply(@Nullable K key) {
V result = map.get(key);
return (result != null || map.containsKey(key)) ? result : defaultValue;
}
@Override public boolean equals(@Nullable Object o) {
if (o instanceof ForMapWithDefault) {
ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(map, defaultValue);
}
@Override public String toString() {
return "forMap(" + map + ", defaultValue=" + defaultValue + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition
* is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}.
*
* @param g the second function to apply
* @param f the first function to apply
* @return the composition of {@code f} and {@code g}
* @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a>
*/
public static <A, B, C> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) {
return new FunctionComposition<A, B, C>(g, f);
}
private static class FunctionComposition<A, B, C> implements Function<A, C>, Serializable {
private final Function<B, C> g;
private final Function<A, ? extends B> f;
public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) {
this.g = checkNotNull(g);
this.f = checkNotNull(f);
}
@Override
public C apply(@Nullable A a) {
return g.apply(f.apply(a));
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof FunctionComposition) {
FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
return f.equals(that.f) && g.equals(that.g);
}
return false;
}
@Override public int hashCode() {
return f.hashCode() ^ g.hashCode();
}
@Override public String toString() {
return g + "(" + f + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Creates a function that returns the same boolean output as the given predicate for all inputs.
*
* <p>The returned function is <i>consistent with equals</i> (as documented at {@link
* Function#apply}) if and only if {@code predicate} is itself consistent with equals.
*/
public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
return new PredicateFunction<T>(predicate);
}
/** @see Functions#forPredicate */
private static class PredicateFunction<T> implements Function<T, Boolean>, Serializable {
private final Predicate<T> predicate;
private PredicateFunction(Predicate<T> predicate) {
this.predicate = checkNotNull(predicate);
}
@Override
public Boolean apply(@Nullable T t) {
return predicate.apply(t);
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof PredicateFunction) {
PredicateFunction<?> that = (PredicateFunction<?>) obj;
return predicate.equals(that.predicate);
}
return false;
}
@Override public int hashCode() {
return predicate.hashCode();
}
@Override public String toString() {
return "forPredicate(" + predicate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Creates a function that returns {@code value} for any input.
*
* @param value the constant value for the function to return
* @return a function that always returns {@code value}
*/
public static <E> Function<Object, E> constant(@Nullable E value) {
return new ConstantFunction<E>(value);
}
private static class ConstantFunction<E> implements Function<Object, E>, Serializable {
private final E value;
public ConstantFunction(@Nullable E value) {
this.value = value;
}
@Override
public E apply(@Nullable Object from) {
return value;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof ConstantFunction) {
ConstantFunction<?> that = (ConstantFunction<?>) obj;
return Objects.equal(value, that.value);
}
return false;
}
@Override public int hashCode() {
return (value == null) ? 0 : value.hashCode();
}
@Override public String toString() {
return "constant(" + value + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a function that always returns the result of invoking {@link Supplier#get} on {@code
* supplier}, regardless of its input.
*
* @since 10.0
*/
@Beta
public static <T> Function<Object, T> forSupplier(Supplier<T> supplier) {
return new SupplierFunction<T>(supplier);
}
/** @see Functions#forSupplier*/
private static class SupplierFunction<T> implements Function<Object, T>, Serializable {
private final Supplier<T> supplier;
private SupplierFunction(Supplier<T> supplier) {
this.supplier = checkNotNull(supplier);
}
@Override public T apply(@Nullable Object input) {
return supplier.get();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof SupplierFunction) {
SupplierFunction<?> that = (SupplierFunction<?>) obj;
return this.supplier.equals(that.supplier);
}
return false;
}
@Override public int hashCode() {
return supplier.hashCode();
}
@Override public String toString() {
return "forSupplier(" + supplier + ")";
}
private static final long serialVersionUID = 0;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/Functions.java | Java | asf20 | 11,309 |
/*
* Copyright (C) 2013 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.base;
import static com.google.common.base.Preconditions.format;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* Static convenience methods that serve the same purpose as Java language
* <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html">
* assertions</a>, except that they are always enabled. These methods should be used instead of Java
* assertions whenever there is a chance the check may fail "in real life". Example: <pre> {@code
*
* Bill bill = remoteService.getLastUnpaidBill();
*
* // In case bug 12345 happens again we'd rather just die
* Verify.verify(bill.status() == Status.UNPAID,
* "Unexpected bill status: %s", bill.status());}</pre>
*
* <h3>Comparison to alternatives</h3>
*
* <p><b>Note:</b> In some cases the differences explained below can be subtle. When it's unclear
* which approach to use, <b>don't worry</b> too much about it; just pick something that seems
* reasonable and it will be fine.
*
* <ul>
* <li>If checking whether the <i>caller</i> has violated your method or constructor's contract
* (such as by passing an invalid argument), use the utilities of the {@link Preconditions}
* class instead.
*
* <li>If checking an <i>impossible</i> condition (which <i>cannot</i> happen unless your own class
* or its <i>trusted</i> dependencies is badly broken), this is what ordinary Java assertions
* are for. Note that assertions are not enabled by default; they are essentially considered
* "compiled comments."
*
* <li>An explicit {@code if/throw} (as illustrated above) is always acceptable; we still recommend
* using our {@link VerifyException} exception type. Throwing a plain {@link RuntimeException}
* is frowned upon.
*
* <li>Use of {@link java.util.Objects#requireNonNull(Object)} is generally discouraged, since
* {@link #verifyNotNull(Object)} and {@link Preconditions#checkNotNull(Object)} perform the
* same function with more clarity.
* </ul>
*
* <h3>Warning about performance</h3>
*
* <p>Remember that parameter values for message construction must all be computed eagerly, and
* autoboxing and varargs array creation may happen as well, even when the verification succeeds and
* the message ends up unneeded. Performance-sensitive verification checks should continue to use
* usual form: <pre> {@code
*
* Bill bill = remoteService.getLastUnpaidBill();
* if (bill.status() != Status.UNPAID) {
* throw new VerifyException("Unexpected bill status: " + bill.status());
* }}</pre>
*
* <h3>Only {@code %s} is supported</h3>
*
* <p>As with {@link Preconditions} error message template strings, only the {@code "%s"} specifier
* is supported, not the full range of {@link java.util.Formatter} specifiers. However, note that
* if the number of arguments does not match the number of occurrences of {@code "%s"} in the
* format string, {@code Verify} will still behave as expected, and will still include all argument
* values in the error message; the message will simply not be formatted exactly as intended.
*
* <h3>More information</h3>
*
* See
* <a href="http://code.google.com/p/guava-libraries/wiki/ConditionalFailuresExplained">Conditional
* failures explained</a> in the Guava User Guide for advice on when this class should be used.
*
* @since 17.0
*/
@Beta
@GwtCompatible
public final class Verify {
/**
* Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with no
* message otherwise.
*/
public static void verify(boolean expression) {
if (!expression) {
throw new VerifyException();
}
}
/**
* Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
* custom message otherwise.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws VerifyException if {@code expression} is {@code false}
*/
public static void verify(
boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new VerifyException(format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default
* message otherwise.
*
* @return {@code reference}, guaranteed to be non-null, for convenience
*/
public static <T> T verifyNotNull(@Nullable T reference) {
return verifyNotNull(reference, "expected a non-null reference");
}
/**
* Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom
* message otherwise.
*
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return {@code reference}, guaranteed to be non-null, for convenience
*/
public static <T> T verifyNotNull(
@Nullable T reference,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
verify(reference != null, errorMessageTemplate, errorMessageArgs);
return reference;
}
// TODO(kevinb): consider <T> T verifySingleton(Iterable<T>) to take over for
// Iterables.getOnlyElement()
private Verify() {}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/Verify.java | Java | asf20 | 7,100 |
/*
* 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.base;
import com.google.common.annotations.GwtCompatible;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Jesse Wilson
*/
@GwtCompatible(emulated = true)
final class Platform {
private Platform() {}
/** Calls {@link System#nanoTime()}. */
static long systemNanoTime() {
return System.nanoTime();
}
static CharMatcher precomputeCharMatcher(CharMatcher matcher) {
return matcher.precomputedInternal();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/Platform.java | Java | asf20 | 1,100 |
/*
* 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.base;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
/**
* Weak reference with a {@code finalizeReferent()} method which a background thread invokes after
* the garbage collector reclaims the referent. This is a simpler alternative to using a {@link
* ReferenceQueue}.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
*/
public abstract class FinalizableWeakReference<T> extends WeakReference<T>
implements FinalizableReference {
/**
* Constructs a new finalizable weak reference.
*
* @param referent to weakly reference
* @param queue that should finalize the referent
*/
protected FinalizableWeakReference(T referent, FinalizableReferenceQueue queue) {
super(referent, queue.queue);
queue.cleanUp();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/FinalizableWeakReference.java | Java | asf20 | 1,429 |
/*
* 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of an {@link Optional} containing a reference.
*/
@GwtCompatible
final class Present<T> extends Optional<T> {
private final T reference;
Present(T reference) {
this.reference = reference;
}
@Override public boolean isPresent() {
return true;
}
@Override public T get() {
return reference;
}
@Override public T or(T defaultValue) {
checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)");
return reference;
}
@Override public Optional<T> or(Optional<? extends T> secondChoice) {
checkNotNull(secondChoice);
return this;
}
@Override public T or(Supplier<? extends T> supplier) {
checkNotNull(supplier);
return reference;
}
@Override public T orNull() {
return reference;
}
@Override public Set<T> asSet() {
return Collections.singleton(reference);
}
@Override public <V> Optional<V> transform(Function<? super T, V> function) {
return new Present<V>(checkNotNull(function.apply(reference),
"the Function passed to Optional.transform() must not return null."));
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Present) {
Present<?> other = (Present<?>) object;
return reference.equals(other.reference);
}
return false;
}
@Override public int hashCode() {
return 0x598df91c + reference.hashCode();
}
@Override public String toString() {
return "Optional.of(" + reference + ")";
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/Present.java | Java | asf20 | 2,406 |
/*
* Copyright (C) 2013 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.base;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* Exception thrown upon the failure of a
* <a href="http://code.google.com/p/guava-libraries/wiki/ConditionalFailuresExplained">verification
* check</a>, including those performed by the convenience methods of the {@link Verify} class.
*
* @since 17.0
*/
@Beta
@GwtCompatible
public class VerifyException extends RuntimeException {
/** Constructs a {@code VerifyException} with no message. */
public VerifyException() {}
/** Constructs a {@code VerifyException} with the message {@code message}. */
public VerifyException(@Nullable String message) {
super(message);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/VerifyException.java | Java | asf20 | 1,355 |
/*
* 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.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.nio.charset.Charset;
/**
* Contains constant definitions for the six standard {@link Charset} instances, which are
* guaranteed to be supported by all Java platform implementations.
*
* <p>Assuming you're free to choose, note that <b>{@link #UTF_8} is widely preferred</b>.
*
* <p>See the Guava User Guide article on <a
* href="http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets">
* {@code Charsets}</a>.
*
* @author Mike Bostock
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Charsets {
private Charsets() {}
/**
* US-ASCII: seven-bit ASCII, the Basic Latin block of the Unicode character set (ISO646-US).
*
*/
@GwtIncompatible("Non-UTF-8 Charset")
public static final Charset US_ASCII = Charset.forName("US-ASCII");
/**
* ISO-8859-1: ISO Latin Alphabet Number 1 (ISO-LATIN-1).
*
*/
@GwtIncompatible("Non-UTF-8 Charset")
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
/**
* UTF-8: eight-bit UCS Transformation Format.
*
*/
public static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* UTF-16BE: sixteen-bit UCS Transformation Format, big-endian byte order.
*
*/
@GwtIncompatible("Non-UTF-8 Charset")
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
/**
* UTF-16LE: sixteen-bit UCS Transformation Format, little-endian byte order.
*
*/
@GwtIncompatible("Non-UTF-8 Charset")
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
/**
* UTF-16: sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order
* mark.
*
*/
@GwtIncompatible("Non-UTF-8 Charset")
public static final Charset UTF_16 = Charset.forName("UTF-16");
/*
* Please do not add new Charset references to this class, unless those character encodings are
* part of the set required to be supported by all Java platform implementations! Any Charsets
* initialized here may cause unexpected delays when this class is loaded. See the Charset
* Javadocs for the list of built-in character encodings.
*/
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/Charsets.java | Java | asf20 | 2,877 |
/*
* 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.base;
import com.google.common.annotations.GwtCompatible;
/**
* A class that can supply objects of a single type. Semantically, this could
* be a factory, generator, builder, closure, or something else entirely. No
* guarantees are implied by this interface.
*
* @author Harry Heymann
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface Supplier<T> {
/**
* Retrieves an instance of the appropriate type. The returned object may or
* may not be a new instance, depending on the implementation.
*
* @return an instance of the appropriate type
*/
T get();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/base/Supplier.java | Java | asf20 | 1,251 |
/*
* 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.Objects;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An immutable {@link Table} with reliable user-specified iteration order.
* Does not permit null keys or values.
*
* <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 Gregory Kick
* @since 11.0
*/
@GwtCompatible
// TODO(gak): make serializable
public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V> {
private static final ImmutableTable<Object, Object, Object> EMPTY
= new SparseImmutableTable<Object, Object, Object>(
ImmutableList.<Cell<Object, Object, Object>>of(),
ImmutableSet.of(), ImmutableSet.of());
/** Returns an empty immutable table. */
@SuppressWarnings("unchecked")
public static <R, C, V> ImmutableTable<R, C, V> of() {
return (ImmutableTable<R, C, V>) EMPTY;
}
/** Returns an immutable table containing a single cell. */
public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey,
C columnKey, V value) {
return new SingletonImmutableTable<R, C, V>(rowKey, columnKey, value);
}
/**
* Returns an immutable copy of the provided table.
*
* <p>The {@link Table#cellSet()} iteration order of the provided table
* determines the iteration ordering of all views in the returned table. Note
* that some views of the original table and the copied table may have
* different iteration orders. For more control over the ordering, create a
* {@link Builder} and call {@link Builder#orderRowsBy},
* {@link Builder#orderColumnsBy}, and {@link Builder#putAll}
*
* <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.
*/
public static <R, C, V> ImmutableTable<R, C, V> copyOf(
Table<? extends R, ? extends C, ? extends V> table) {
if (table instanceof ImmutableTable) {
@SuppressWarnings("unchecked")
ImmutableTable<R, C, V> parameterizedTable
= (ImmutableTable<R, C, V>) table;
return parameterizedTable;
} else {
int size = table.size();
switch (size) {
case 0:
return of();
case 1:
Cell<? extends R, ? extends C, ? extends V> onlyCell
= Iterables.getOnlyElement(table.cellSet());
return ImmutableTable.<R, C, V>of(onlyCell.getRowKey(),
onlyCell.getColumnKey(), onlyCell.getValue());
default:
ImmutableSet.Builder<Cell<R, C, V>> cellSetBuilder
= ImmutableSet.builder();
for (Cell<? extends R, ? extends C, ? extends V> cell :
table.cellSet()) {
/*
* Must cast to be able to create a Cell<R, C, V> rather than a
* Cell<? extends R, ? extends C, ? extends V>
*/
cellSetBuilder.add(cellOf((R) cell.getRowKey(),
(C) cell.getColumnKey(), (V) cell.getValue()));
}
return RegularImmutableTable.forCells(cellSetBuilder.build());
}
}
}
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder#ImmutableTable.Builder()} constructor.
*/
public static <R, C, V> Builder<R, C, V> builder() {
return new Builder<R, C, V>();
}
/**
* Verifies that {@code rowKey}, {@code columnKey} and {@code value} are
* non-null, and returns a new entry with those values.
*/
static <R, C, V> Cell<R, C, V> cellOf(R rowKey, C columnKey, V value) {
return Tables.immutableCell(checkNotNull(rowKey), checkNotNull(columnKey),
checkNotNull(value));
}
/**
* A builder for creating immutable table instances, especially {@code public
* static final} tables ("constant tables"). Example: <pre> {@code
*
* static final ImmutableTable<Integer, Character, String> SPREADSHEET =
* new ImmutableTable.Builder<Integer, Character, String>()
* .put(1, 'A', "foo")
* .put(1, 'B', "bar")
* .put(2, 'A', "baz")
* .build();}</pre>
*
* <p>By default, the order in which cells are added to the builder determines
* the iteration ordering of all views in the returned table, with {@link
* #putAll} following the {@link Table#cellSet()} iteration order. However, if
* {@link #orderRowsBy} or {@link #orderColumnsBy} is called, the views are
* sorted by the supplied comparators.
*
* For empty or single-cell immutable tables, {@link #of()} and
* {@link #of(Object, Object, Object)} are even more convenient.
*
* <p>Builder instances can be reused - it is safe to call {@link #build}
* multiple times to build multiple tables in series. Each table is a superset
* of the tables created before it.
*
* @since 11.0
*/
public static final class Builder<R, C, V> {
private final List<Cell<R, C, V>> cells = Lists.newArrayList();
private Comparator<? super R> rowComparator;
private Comparator<? super C> columnComparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableTable#builder}.
*/
public Builder() {}
/**
* Specifies the ordering of the generated table's rows.
*/
public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) {
this.rowComparator = checkNotNull(rowComparator);
return this;
}
/**
* Specifies the ordering of the generated table's columns.
*/
public Builder<R, C, V> orderColumnsBy(
Comparator<? super C> columnComparator) {
this.columnComparator = checkNotNull(columnComparator);
return this;
}
/**
* Associates the ({@code rowKey}, {@code columnKey}) pair with {@code
* value} in the built table. Duplicate key pairs are not allowed and will
* cause {@link #build} to fail.
*/
public Builder<R, C, V> put(R rowKey, C columnKey, V value) {
cells.add(cellOf(rowKey, columnKey, value));
return this;
}
/**
* Adds the given {@code cell} to the table, making it immutable if
* necessary. Duplicate key pairs are not allowed and will cause {@link
* #build} to fail.
*/
public Builder<R, C, V> put(
Cell<? extends R, ? extends C, ? extends V> cell) {
if (cell instanceof Tables.ImmutableCell) {
checkNotNull(cell.getRowKey());
checkNotNull(cell.getColumnKey());
checkNotNull(cell.getValue());
@SuppressWarnings("unchecked") // all supported methods are covariant
Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell;
cells.add(immutableCell);
} else {
put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
return this;
}
/**
* Associates all of the given table's keys and values in the built table.
* Duplicate row key column key pairs are not allowed, and will cause
* {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code table} is null
*/
public Builder<R, C, V> putAll(
Table<? extends R, ? extends C, ? extends V> table) {
for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
put(cell);
}
return this;
}
/**
* Returns a newly-created immutable table.
*
* @throws IllegalArgumentException if duplicate key pairs were added
*/
public ImmutableTable<R, C, V> build() {
int size = cells.size();
switch (size) {
case 0:
return of();
case 1:
return new SingletonImmutableTable<R, C, V>(
Iterables.getOnlyElement(cells));
default:
return RegularImmutableTable.forCells(
cells, rowComparator, columnComparator);
}
}
}
ImmutableTable() {}
@Override public ImmutableSet<Cell<R, C, V>> cellSet() {
return (ImmutableSet<Cell<R, C, V>>) super.cellSet();
}
@Override
abstract ImmutableSet<Cell<R, C, V>> createCellSet();
@Override
final UnmodifiableIterator<Cell<R, C, V>> cellIterator() {
throw new AssertionError("should never be called");
}
@Override
public ImmutableCollection<V> values() {
return (ImmutableCollection<V>) super.values();
}
@Override
abstract ImmutableCollection<V> createValues();
@Override
final Iterator<V> valuesIterator() {
throw new AssertionError("should never be called");
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if {@code columnKey} is {@code null}
*/
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
return Objects.firstNonNull(
(ImmutableMap<R, V>) columnMap().get(columnKey),
ImmutableMap.<R, V>of());
}
@Override public ImmutableSet<C> columnKeySet() {
return columnMap().keySet();
}
/**
* {@inheritDoc}
*
* <p>The value {@code Map<R, V>} instances in the returned map are
* {@link ImmutableMap} instances as well.
*/
@Override public abstract ImmutableMap<C, Map<R, V>> columnMap();
/**
* {@inheritDoc}
*
* @throws NullPointerException if {@code rowKey} is {@code null}
*/
@Override public ImmutableMap<C, V> row(R rowKey) {
checkNotNull(rowKey);
return Objects.firstNonNull(
(ImmutableMap<C, V>) rowMap().get(rowKey),
ImmutableMap.<C, V>of());
}
@Override public ImmutableSet<R> rowKeySet() {
return rowMap().keySet();
}
/**
* {@inheritDoc}
*
* <p>The value {@code Map<C, V>} instances in the returned map are
* {@link ImmutableMap} instances as well.
*/
@Override public abstract ImmutableMap<R, Map<C, V>> rowMap();
@Override
public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
return get(rowKey, columnKey) != null;
}
@Override
public boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final V put(R rowKey, C columnKey, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final void putAll(
Table<? extends R, ? extends C, ? extends V> table) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final V remove(Object rowKey, Object columnKey) {
throw new UnsupportedOperationException();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableTable.java | Java | asf20 | 12,462 |
/*
* 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;
/**
* Provides equivalent behavior to {@link String#intern} for other immutable
* types.
*
* @author Kevin Bourrillion
* @since 3.0
*/
@Beta
public interface Interner<E> {
/**
* Chooses and returns the representative instance for any of a collection of
* instances that are equal to each other. If two {@linkplain Object#equals
* equal} inputs are given to this method, both calls will return the same
* instance. That is, {@code intern(a).equals(a)} always holds, and {@code
* intern(a) == intern(b)} if and only if {@code a.equals(b)}. Note that
* {@code intern(a)} is permitted to return one instance now and a different
* instance later if the original interned instance was garbage-collected.
*
* <p><b>Warning:</b> do not use with mutable objects.
*
* @throws NullPointerException if {@code sample} is null
*/
E intern(E sample);
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Interner.java | Java | asf20 | 1,567 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Predicate;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of {@link Multimaps#filterKeys(SetMultimap, Predicate)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class FilteredKeySetMultimap<K, V> extends FilteredKeyMultimap<K, V>
implements FilteredSetMultimap<K, V> {
FilteredKeySetMultimap(SetMultimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
super(unfiltered, keyPredicate);
}
@Override
public SetMultimap<K, V> unfiltered() {
return (SetMultimap<K, V>) unfiltered;
}
@Override
public Set<V> get(K key) {
return (Set<V>) super.get(key);
}
@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);
}
@Override
public Set<Entry<K, V>> entries() {
return (Set<Entry<K, V>>) super.entries();
}
@Override
Set<Entry<K, V>> createEntries() {
return new EntrySet();
}
class EntrySet extends Entries implements Set<Entry<K, V>> {
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override
public boolean equals(@Nullable Object o) {
return Sets.equalsImpl(this, o);
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/FilteredKeySetMultimap.java | Java | asf20 | 2,075 |
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* 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(getUpperEndpoint()))
|| (hasLowerBound() && tooHigh(getLowerEndpoint()));
}
boolean tooLow(@Nullable T t) {
if (!hasLowerBound()) {
return false;
}
T lbound = getLowerEndpoint();
int cmp = comparator.compare(t, lbound);
return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN);
}
boolean tooHigh(@Nullable T t) {
if (!hasUpperBound()) {
return false;
}
T ubound = getUpperEndpoint();
int cmp = comparator.compare(t, ubound);
return cmp > 0 | (cmp == 0 & getUpperBoundType() == 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 = getLowerEndpoint();
BoundType lowType = getLowerBoundType();
if (!hasLowerBound()) {
hasLowBound = other.hasLowerBound;
lowEnd = other.getLowerEndpoint();
lowType = other.getLowerBoundType();
} else if (other.hasLowerBound()) {
int cmp = comparator.compare(getLowerEndpoint(), other.getLowerEndpoint());
if (cmp < 0 || (cmp == 0 && other.getLowerBoundType() == OPEN)) {
lowEnd = other.getLowerEndpoint();
lowType = other.getLowerBoundType();
}
}
boolean hasUpBound = this.hasUpperBound;
@Nullable
T upEnd = getUpperEndpoint();
BoundType upType = getUpperBoundType();
if (!hasUpperBound()) {
hasUpBound = other.hasUpperBound;
upEnd = other.getUpperEndpoint();
upType = other.getUpperBoundType();
} else if (other.hasUpperBound()) {
int cmp = comparator.compare(getUpperEndpoint(), other.getUpperEndpoint());
if (cmp > 0 || (cmp == 0 && other.getUpperBoundType() == OPEN)) {
upEnd = other.getUpperEndpoint();
upType = other.getUpperBoundType();
}
}
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 && getLowerBoundType().equals(r.getLowerBoundType())
&& getUpperBoundType().equals(r.getUpperBoundType())
&& Objects.equal(getLowerEndpoint(), r.getLowerEndpoint())
&& Objects.equal(getUpperEndpoint(), r.getUpperEndpoint());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(comparator, getLowerEndpoint(), getLowerBoundType(), getUpperEndpoint(),
getUpperBoundType());
}
private transient GeneralRange<T> reverse;
/**
* Returns the same range relative to the reversed comparator.
*/
GeneralRange<T> reverse() {
GeneralRange<T> result = reverse;
if (result == null) {
result = new GeneralRange<T>(
Ordering.from(comparator).reverse(), hasUpperBound, getUpperEndpoint(),
getUpperBoundType(), hasLowerBound, getLowerEndpoint(), getLowerBoundType());
result.reverse = this;
return this.reverse = result;
}
return result;
}
@Override
public String toString() {
return new StringBuilder()
.append(comparator)
.append(":")
.append(lowerBoundType == CLOSED ? '[' : '(')
.append(hasLowerBound ? lowerEndpoint : "-\u221e")
.append(',')
.append(hasUpperBound ? upperEndpoint : "\u221e")
.append(upperBoundType == CLOSED ? ']' : ')')
.toString();
}
T getLowerEndpoint() {
return lowerEndpoint;
}
BoundType getLowerBoundType() {
return lowerBoundType;
}
T getUpperEndpoint() {
return upperEndpoint;
}
BoundType getUpperBoundType() {
return upperBoundType;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/GeneralRange.java | Java | asf20 | 9,479 |
/*
* 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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* An immutable {@code SortedMultiset} that stores its elements in a sorted array. Some instances
* are ordered by an explicit comparator, while others follow the natural sort ordering of their
* elements. Either way, null elements are not supported.
*
* <p>Unlike {@link Multisets#unmodifiableSortedMultiset}, which is a <i>view</i> of a separate
* collection that can still change, an instance of {@code ImmutableSortedMultiset} contains its
* own private data and will <i>never</i> change. This class is convenient for {@code public static
* final} multisets ("constant multisets") and also lets you easily make a "defensive copy" of a
* set provided to your class by a caller.
*
* <p>The multisets returned by the {@link #headMultiset}, {@link #tailMultiset}, and
* {@link #subMultiset} methods share the same array as the original multiset, preventing that
* array from being garbage collected. If this is a concern, the data may be copied into a
* correctly-sized array by calling {@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 ImmutableSortedMultiset} 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>
*
* <p>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 multisets, an {@code ImmutableSortedMultiset} will not function
* correctly if an element is modified after being placed in the multiset. For this reason, and to
* avoid general confusion, it is strongly recommended to place only immutable objects into this
* collection.
*
* <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>.
*
* @author Louis Wasserman
* @since 12.0
*/
@Beta
@GwtIncompatible("hasn't been tested yet")
public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultisetFauxverideShim<E>
implements SortedMultiset<E> {
// TODO(user): GWT compatibility
private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural();
private static final ImmutableSortedMultiset<Comparable> NATURAL_EMPTY_MULTISET =
new EmptyImmutableSortedMultiset<Comparable>(NATURAL_ORDER);
/**
* Returns the empty immutable sorted multiset.
*/
@SuppressWarnings("unchecked")
public static <E> ImmutableSortedMultiset<E> of() {
return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET;
}
/**
* Returns an immutable sorted multiset containing a single element.
*/
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) {
RegularImmutableSortedSet<E> elementSet =
(RegularImmutableSortedSet<E>) ImmutableSortedSet.of(element);
int[] counts = {1};
long[] cumulativeCounts = {0, 1};
return new RegularImmutableSortedMultiset<E>(elementSet, counts, cumulativeCounts, 0, 1);
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2));
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3));
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
E e1, E e2, E e3, E e4) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4));
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
E e1, E e2, E e3, E e4, E e5) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4, e5));
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
int size = remaining.length + 6;
List<E> all = Lists.newArrayListWithCapacity(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, remaining);
return copyOf(Ordering.natural(), all);
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> copyOf(E[] elements) {
return copyOf(Ordering.natural(), Arrays.asList(elements));
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering. To create a copy of a {@code SortedMultiset} 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 multiset<String>}, then {@code
* ImmutableSortedMultiset.copyOf(s)} returns an {@code ImmutableSortedMultiset<String>}
* containing each of the strings in {@code s}, while {@code ImmutableSortedMultiset.of(s)}
* returns an {@code ImmutableSortedMultiset<multiset<String>>} containing one element (the given
* multiset 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> ImmutableSortedMultiset<E> copyOf(Iterable<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedMultisetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by their natural
* ordering.
*
* <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> ImmutableSortedMultiset<E> copyOf(Iterator<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedMultisetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by the given {@code
* Comparator}.
*
* @throws NullPointerException if {@code comparator} or any of {@code elements} is null
*/
public static <E> ImmutableSortedMultiset<E> copyOf(
Comparator<? super E> comparator, Iterator<? extends E> elements) {
checkNotNull(comparator);
return new Builder<E>(comparator).addAll(elements).build();
}
/**
* Returns an immutable sorted multiset containing the given elements sorted by the given {@code
* Comparator}. 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> ImmutableSortedMultiset<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
if (elements instanceof ImmutableSortedMultiset) {
@SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts
ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements;
if (comparator.equals(multiset.comparator())) {
if (multiset.isPartialView()) {
return copyOfSortedEntries(comparator, multiset.entrySet().asList());
} else {
return multiset;
}
}
}
elements = Lists.newArrayList(elements); // defensive copy
TreeMultiset<E> sortedCopy = TreeMultiset.create(checkNotNull(comparator));
Iterables.addAll(sortedCopy, elements);
return copyOfSortedEntries(comparator, sortedCopy.entrySet());
}
/**
* Returns an immutable sorted multiset containing the elements of a sorted multiset, 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 sortedMultiset} is a synchronized or concurrent
* collection that is currently being modified by another thread.
*
* @throws NullPointerException if {@code sortedMultiset} or any of its elements is null
*/
public static <E> ImmutableSortedMultiset<E> copyOfSorted(SortedMultiset<E> sortedMultiset) {
return copyOfSortedEntries(sortedMultiset.comparator(),
Lists.newArrayList(sortedMultiset.entrySet()));
}
private static <E> ImmutableSortedMultiset<E> copyOfSortedEntries(
Comparator<? super E> comparator, Collection<Entry<E>> entries) {
if (entries.isEmpty()) {
return emptyMultiset(comparator);
}
ImmutableList.Builder<E> elementsBuilder = new ImmutableList.Builder<E>(entries.size());
int[] counts = new int[entries.size()];
long[] cumulativeCounts = new long[entries.size() + 1];
int i = 0;
for (Entry<E> entry : entries) {
elementsBuilder.add(entry.getElement());
counts[i] = entry.getCount();
cumulativeCounts[i + 1] = cumulativeCounts[i] + counts[i];
i++;
}
return new RegularImmutableSortedMultiset<E>(
new RegularImmutableSortedSet<E>(elementsBuilder.build(), comparator),
counts, cumulativeCounts, 0, entries.size());
}
@SuppressWarnings("unchecked")
static <E> ImmutableSortedMultiset<E> emptyMultiset(Comparator<? super E> comparator) {
if (NATURAL_ORDER.equals(comparator)) {
return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET;
}
return new EmptyImmutableSortedMultiset<E>(comparator);
}
ImmutableSortedMultiset() {}
@Override
public final Comparator<? super E> comparator() {
return elementSet().comparator();
}
@Override
public abstract ImmutableSortedSet<E> elementSet();
transient ImmutableSortedMultiset<E> descendingMultiset;
@Override
public ImmutableSortedMultiset<E> descendingMultiset() {
ImmutableSortedMultiset<E> result = descendingMultiset;
if (result == null) {
return descendingMultiset = new DescendingImmutableSortedMultiset<E>(this);
}
return result;
}
/**
* {@inheritDoc}
*
* <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final Entry<E> pollFirstEntry() {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final Entry<E> pollLastEntry() {
throw new UnsupportedOperationException();
}
@Override
public abstract ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType);
@Override
public ImmutableSortedMultiset<E> subMultiset(
E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) {
checkArgument(comparator().compare(lowerBound, upperBound) <= 0,
"Expected lowerBound <= upperBound but %s > %s", lowerBound, upperBound);
return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType);
}
@Override
public abstract ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType);
/**
* Returns a builder that creates immutable sorted multisets with an explicit comparator. If the
* comparator has a more general type than the set being generated, such as creating a {@code
* SortedMultiset<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 multisets 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 multisets whose elements are ordered by their
* natural ordering. The sorted multisets 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 multiset instances, especially {@code public static final}
* multisets ("constant multisets"). Example:
*
* <pre> {@code
*
* public static final ImmutableSortedMultiset<Bean> BEANS =
* new ImmutableSortedMultiset.Builder<Bean>()
* .addCopies(Bean.COCOA, 4)
* .addCopies(Bean.GARDEN, 6)
* .addCopies(Bean.RED, 8)
* .addCopies(Bean.BLACK_EYED, 10)
* .build();}</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
* multiple multisets in series.
*
* @since 12.0
*/
public static class Builder<E> extends ImmutableMultiset.Builder<E> {
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by
* {@link ImmutableSortedMultiset#orderedBy(Comparator)}.
*/
public Builder(Comparator<? super E> comparator) {
super(TreeMultiset.<E>create(checkNotNull(comparator)));
}
/**
* Adds {@code element} to the {@code ImmutableSortedMultiset}.
*
* @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 a number of occurrences of an element to this {@code ImmutableSortedMultiset}.
*
* @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
*/
@Override
public Builder<E> addCopies(E element, int occurrences) {
super.addCopies(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
*/
@Override
public Builder<E> setCount(E element, int count) {
super.setCount(element, count);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}.
*
* @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 ImmutableSortedMultiset}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableSortedMultiset}
* @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) {
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}.
*
* @param elements the elements to add to the {@code ImmutableSortedMultiset}
* @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 ImmutableSortedMultiset} based on the contents of the {@code
* Builder}.
*/
@Override
public ImmutableSortedMultiset<E> build() {
return copyOfSorted((SortedMultiset<E>) contents);
}
}
private static final class SerializedForm<E> implements Serializable {
Comparator<? super E> comparator;
E[] elements;
int[] counts;
@SuppressWarnings("unchecked")
SerializedForm(SortedMultiset<E> multiset) {
this.comparator = multiset.comparator();
int n = multiset.entrySet().size();
elements = (E[]) new Object[n];
counts = new int[n];
int i = 0;
for (Entry<E> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
int n = elements.length;
Builder<E> builder = new Builder<E>(comparator);
for (int i = 0; i < n; i++) {
builder.addCopies(elements[i], counts[i]);
}
return builder.build();
}
}
@Override
Object writeReplace() {
return new SerializedForm<E>(this);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSortedMultiset.java | Java | asf20 | 22,261 |
/*
* 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 java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import javax.annotation.Nullable;
/**
* This class provides a skeletal implementation of the {@link SortedMultiset} interface.
*
* <p>The {@link #count} and {@link #size} implementations all iterate across the set returned by
* {@link Multiset#entrySet()}, as do many methods acting on the set returned by
* {@link #elementSet()}. Override those methods for better performance.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
abstract class AbstractSortedMultiset<E> extends AbstractMultiset<E> implements SortedMultiset<E> {
@GwtTransient final Comparator<? super E> comparator;
// needed for serialization
@SuppressWarnings("unchecked")
AbstractSortedMultiset() {
this((Comparator) Ordering.natural());
}
AbstractSortedMultiset(Comparator<? super E> comparator) {
this.comparator = checkNotNull(comparator);
}
@Override
public NavigableSet<E> elementSet() {
return (NavigableSet<E>) super.elementSet();
}
@Override
NavigableSet<E> createElementSet() {
return new SortedMultisets.NavigableElementSet<E>(this);
}
@Override
public Comparator<? super E> comparator() {
return comparator;
}
@Override
public Entry<E> firstEntry() {
Iterator<Entry<E>> entryIterator = entryIterator();
return entryIterator.hasNext() ? entryIterator.next() : null;
}
@Override
public Entry<E> lastEntry() {
Iterator<Entry<E>> entryIterator = descendingEntryIterator();
return entryIterator.hasNext() ? entryIterator.next() : null;
}
@Override
public Entry<E> pollFirstEntry() {
Iterator<Entry<E>> entryIterator = entryIterator();
if (entryIterator.hasNext()) {
Entry<E> result = entryIterator.next();
result = Multisets.immutableEntry(result.getElement(), result.getCount());
entryIterator.remove();
return result;
}
return null;
}
@Override
public Entry<E> pollLastEntry() {
Iterator<Entry<E>> entryIterator = descendingEntryIterator();
if (entryIterator.hasNext()) {
Entry<E> result = entryIterator.next();
result = Multisets.immutableEntry(result.getElement(), result.getCount());
entryIterator.remove();
return result;
}
return null;
}
@Override
public SortedMultiset<E> subMultiset(@Nullable E fromElement, BoundType fromBoundType,
@Nullable E toElement, BoundType toBoundType) {
// These are checked elsewhere, but NullPointerTester wants them checked eagerly.
checkNotNull(fromBoundType);
checkNotNull(toBoundType);
return tailMultiset(fromElement, fromBoundType).headMultiset(toElement, toBoundType);
}
abstract Iterator<Entry<E>> descendingEntryIterator();
Iterator<E> descendingIterator() {
return Multisets.iteratorImpl(descendingMultiset());
}
private transient SortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
SortedMultiset<E> result = descendingMultiset;
return (result == null) ? descendingMultiset = createDescendingMultiset() : result;
}
SortedMultiset<E> createDescendingMultiset() {
return new DescendingMultiset<E>() {
@Override
SortedMultiset<E> forwardMultiset() {
return AbstractSortedMultiset.this;
}
@Override
Iterator<Entry<E>> entryIterator() {
return descendingEntryIterator();
}
@Override
public Iterator<E> iterator() {
return descendingIterator();
}
};
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractSortedMultiset.java | Java | asf20 | 4,310 |
/*
* Copyright (C) 2013 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.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* Implementation for {@link FilteredMultimap#values()}.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class FilteredMultimapValues<K, V> extends AbstractCollection<V> {
private final FilteredMultimap<K, V> multimap;
FilteredMultimapValues(FilteredMultimap<K, V> multimap) {
this.multimap = checkNotNull(multimap);
}
@Override
public Iterator<V> iterator() {
return Maps.valueIterator(multimap.entries().iterator());
}
@Override
public boolean contains(@Nullable Object o) {
return multimap.containsValue(o);
}
@Override
public int size() {
return multimap.size();
}
@Override
public boolean remove(@Nullable Object o) {
Predicate<? super Entry<K, V>> entryPredicate = multimap.entryPredicate();
for (Iterator<Entry<K, V>> unfilteredItr = multimap.unfiltered().entries().iterator();
unfilteredItr.hasNext();) {
Map.Entry<K, V> entry = unfilteredItr.next();
if (entryPredicate.apply(entry) && Objects.equal(entry.getValue(), o)) {
unfilteredItr.remove();
return true;
}
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return Iterables.removeIf(multimap.unfiltered().entries(),
// explicit <Entry<K, V>> is required to build with JDK6
Predicates.<Entry<K, V>>and(multimap.entryPredicate(),
Maps.<V>valuePredicateOnEntries(Predicates.in(c))));
}
@Override
public boolean retainAll(Collection<?> c) {
return Iterables.removeIf(multimap.unfiltered().entries(),
// explicit <Entry<K, V>> is required to build with JDK6
Predicates.<Entry<K, V>>and(multimap.entryPredicate(),
Maps.<V>valuePredicateOnEntries(Predicates.not(Predicates.in(c)))));
}
@Override
public void clear() {
multimap.clear();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/FilteredMultimapValues.java | Java | asf20 | 2,881 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
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>
*
* <p>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; implements {@code NavigableSet} since 12.0)
*/
// 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 NavigableSet<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 construct(Ordering.natural(), 2, 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 construct(Ordering.natural(), 3, 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 construct(Ordering.natural(), 4, 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 construct(Ordering.natural(), 5, 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) {
Comparable[] contents = new Comparable[6 + remaining.length];
contents[0] = e1;
contents[1] = e2;
contents[2] = e3;
contents[3] = e4;
contents[4] = e5;
contents[5] = e6;
System.arraycopy(remaining, 0, contents, 6, remaining.length);
return construct(Ordering.natural(), contents.length, (E[]) contents);
}
// 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 construct(Ordering.natural(), elements.length, elements.clone());
}
/**
* 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 copyOf(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) {
return new Builder<E>(comparator).addAll(elements).build();
}
/**
* 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);
boolean hasSameComparator =
SortedIterables.hasSameComparator(comparator, elements);
if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
@SuppressWarnings("unchecked")
ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
if (!original.isPartialView()) {
return original;
}
}
@SuppressWarnings("unchecked") // elements only contains E's; it's safe.
E[] array = (E[]) Iterables.toArray(elements);
return construct(comparator, array.length, array);
}
/**
* 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) {
return copyOf(comparator, (Iterable<? extends E>) 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
*/
public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
Comparator<? super E> comparator = SortedIterables.comparator(sortedSet);
ImmutableList<E> list = ImmutableList.copyOf(sortedSet);
if (list.isEmpty()) {
return emptySet(comparator);
} else {
return new RegularImmutableSortedSet<E>(list, comparator);
}
}
/**
* Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of
* {@code contents}. If {@code k} is the size of the returned {@code ImmutableSortedSet}, then
* the sorted unique elements are in the first {@code k} positions of {@code contents}, and
* {@code contents[i] == null} for {@code k <= i < n}.
*
* <p>If {@code k == contents.length}, then {@code contents} may no longer be safe for
* modification.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code contents} is
* null
*/
static <E> ImmutableSortedSet<E> construct(
Comparator<? super E> comparator, int n, E... contents) {
if (n == 0) {
return emptySet(comparator);
}
checkElementsNotNull(contents, n);
Arrays.sort(contents, 0, n, comparator);
int uniques = 1;
for (int i = 1; i < n; i++) {
E cur = contents[i];
E prev = contents[uniques - 1];
if (comparator.compare(cur, prev) != 0) {
contents[uniques++] = cur;
}
}
Arrays.fill(contents, uniques, n, null);
return new RegularImmutableSortedSet<E>(
ImmutableList.<E>asImmutableList(contents, uniques), 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.
*/
public static <E extends Comparable<?>> 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}.
*/
public static <E extends Comparable<?>> 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>
*
* <p>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() {
@SuppressWarnings("unchecked") // we're careful to put only E's in here
E[] contentsArray = (E[]) contents;
ImmutableSortedSet<E> result = construct(comparator, size, contentsArray);
this.size = result.size(); // we eliminated duplicates in-place in contentsArray
return result;
}
}
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);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public 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);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public 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);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public 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);
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public E lower(E e) {
return Iterators.getNext(headSet(e, false).descendingIterator(), null);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public E floor(E e) {
return Iterators.getNext(headSet(e, true).descendingIterator(), null);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public E ceiling(E e) {
return Iterables.getFirst(tailSet(e, true), null);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public E higher(E e) {
return Iterables.getFirst(tailSet(e, false), null);
}
@Override
public E first() {
return iterator().next();
}
@Override
public E last() {
return descendingIterator().next();
}
/**
* Guaranteed to throw an exception and leave the set unmodified.
*
* @since 12.0
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@GwtIncompatible("NavigableSet")
@Override
public final E pollFirst() {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the set unmodified.
*
* @since 12.0
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@GwtIncompatible("NavigableSet")
@Override
public final E pollLast() {
throw new UnsupportedOperationException();
}
@GwtIncompatible("NavigableSet")
transient ImmutableSortedSet<E> descendingSet;
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public ImmutableSortedSet<E> descendingSet() {
// racy single-check idiom
ImmutableSortedSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = createDescendingSet();
result.descendingSet = this;
}
return result;
}
@GwtIncompatible("NavigableSet")
ImmutableSortedSet<E> createDescendingSet() {
return new DescendingImmutableSortedSet<E>(this);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public abstract UnmodifiableIterator<E> descendingIterator();
/**
* 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());
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSortedSet.java | Java | asf20 | 30,873 |
/*
* 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;
/**
* 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 ImmutableSet<E> {
private final Object[] elements;
// 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) {
this.elements = 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 size() {
return elements.length;
}
@SuppressWarnings("unchecked") // all elements are E's
@Override
public UnmodifiableIterator<E> iterator() {
return (UnmodifiableIterator<E>) Iterators.forArray(elements);
}
@Override
int copyIntoArray(Object[] dst, int offset) {
System.arraycopy(elements, 0, dst, offset, elements.length);
return offset + elements.length;
}
@Override
ImmutableList<E> createAsList() {
return new RegularImmutableAsList<E>(this, elements);
}
@Override
boolean isPartialView() {
return false;
}
@Override public int hashCode() {
return hashCode;
}
@Override boolean isHashCodeFast() {
return true;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/RegularImmutableSet.java | Java | asf20 | 2,590 |
/*
* 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.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A map which forwards all its method calls to another map. Subclasses should
* override one or more methods to modify the behavior of the backing map as
* desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingMap} forward
* <i>indiscriminately</i> to the methods of the delegate. For example,
* overriding {@link #put} alone <i>will not</i> change the behavior of {@link
* #putAll}, which can lead to unexpected behavior. In this case, you should
* override {@code putAll} as well, either providing your own implementation, or
* delegating to the provided {@code standardPutAll} method.
*
* <p>Each of the {@code standard} methods, where appropriate, use {@link
* Objects#equal} to test equality for both keys and values. This may not be
* the desired behavior for map implementations that use non-standard notions of
* key equality, such as a {@code SortedMap} whose comparator is not consistent
* with {@code equals}.
*
* <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 Kevin Bourrillion
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingMap<K, V> extends ForwardingObject
implements Map<K, V> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingMap() {}
@Override protected abstract Map<K, V> delegate();
@Override
public int size() {
return delegate().size();
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public V remove(Object object) {
return delegate().remove(object);
}
@Override
public void clear() {
delegate().clear();
}
@Override
public boolean containsKey(@Nullable Object key) {
return delegate().containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return delegate().containsValue(value);
}
@Override
public V get(@Nullable Object key) {
return delegate().get(key);
}
@Override
public V put(K key, V value) {
return delegate().put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
delegate().putAll(map);
}
@Override
public Set<K> keySet() {
return delegate().keySet();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override
public Set<Entry<K, V>> entrySet() {
return delegate().entrySet();
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
/**
* A sensible definition of {@link #putAll(Map)} in terms of {@link
* #put(Object, Object)}. If you override {@link #put(Object, Object)}, you
* may wish to override {@link #putAll(Map)} to forward to this
* implementation.
*
* @since 7.0
*/
protected void standardPutAll(Map<? extends K, ? extends V> map) {
Maps.putAllImpl(this, map);
}
/**
* A sensible, albeit inefficient, definition of {@link #remove} in terms of
* the {@code iterator} method of {@link #entrySet}. If you override {@link
* #entrySet}, you may wish to override {@link #remove} to forward to this
* implementation.
*
* <p>Alternately, you may wish to override {@link #remove} with {@code
* keySet().remove}, assuming that approach would not lead to an infinite
* loop.
*
* @since 7.0
*/
@Beta protected V standardRemove(@Nullable Object key) {
Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
while (entryIterator.hasNext()) {
Entry<K, V> entry = entryIterator.next();
if (Objects.equal(entry.getKey(), key)) {
V value = entry.getValue();
entryIterator.remove();
return value;
}
}
return null;
}
/**
* A sensible definition of {@link #clear} in terms of the {@code iterator}
* method of {@link #entrySet}. In many cases, you may wish to override
* {@link #clear} to forward to this implementation.
*
* @since 7.0
*/
protected void standardClear() {
Iterators.clear(entrySet().iterator());
}
/**
* A sensible implementation of {@link Map#keySet} in terms of the following
* methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey},
* {@link ForwardingMap#isEmpty}, {@link ForwardingMap#remove}, {@link
* ForwardingMap#size}, and the {@link Set#iterator} method of {@link
* ForwardingMap#entrySet}. In many cases, you may wish to override {@link
* ForwardingMap#keySet} to forward to this implementation or a subclass
* thereof.
*
* @since 10.0
*/
@Beta
protected class StandardKeySet extends Maps.KeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardKeySet() {
super(ForwardingMap.this);
}
}
/**
* A sensible, albeit inefficient, definition of {@link #containsKey} in terms
* of the {@code iterator} method of {@link #entrySet}. If you override {@link
* #entrySet}, you may wish to override {@link #containsKey} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardContainsKey(@Nullable Object key) {
return Maps.containsKeyImpl(this, key);
}
/**
* A sensible implementation of {@link Map#values} in terms of the following
* methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsValue},
* {@link ForwardingMap#isEmpty}, {@link ForwardingMap#size}, and the {@link
* Set#iterator} method of {@link ForwardingMap#entrySet}. In many cases, you
* may wish to override {@link ForwardingMap#values} to forward to this
* implementation or a subclass thereof.
*
* @since 10.0
*/
@Beta
protected class StandardValues extends Maps.Values<K, V> {
/** Constructor for use by subclasses. */
public StandardValues() {
super(ForwardingMap.this);
}
}
/**
* A sensible definition of {@link #containsValue} in terms of the {@code
* iterator} method of {@link #entrySet}. If you override {@link #entrySet},
* you may wish to override {@link #containsValue} to forward to this
* implementation.
*
* @since 7.0
*/
protected boolean standardContainsValue(@Nullable Object value) {
return Maps.containsValueImpl(this, value);
}
/**
* A sensible implementation of {@link Map#entrySet} in terms of the following
* methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey},
* {@link ForwardingMap#get}, {@link ForwardingMap#isEmpty}, {@link
* ForwardingMap#remove}, and {@link ForwardingMap#size}. In many cases, you
* may wish to override {@link #entrySet} to forward to this implementation
* or a subclass thereof.
*
* @since 10.0
*/
@Beta
protected abstract class StandardEntrySet extends Maps.EntrySet<K, V> {
/** Constructor for use by subclasses. */
public StandardEntrySet() {}
@Override
Map<K, V> map() {
return ForwardingMap.this;
}
}
/**
* A sensible definition of {@link #isEmpty} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #isEmpty} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardIsEmpty() {
return !entrySet().iterator().hasNext();
}
/**
* A sensible definition of {@link #equals} in terms of the {@code equals}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #equals} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardEquals(@Nullable Object object) {
return Maps.equalsImpl(this, object);
}
/**
* A sensible definition of {@link #hashCode} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #hashCode} to forward to this implementation.
*
* @since 7.0
*/
protected int standardHashCode() {
return Sets.hashCodeImpl(entrySet());
}
/**
* A sensible definition of {@link #toString} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #toString} to forward to this implementation.
*
* @since 7.0
*/
protected String standardToString() {
return Maps.toStringImpl(this);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingMap.java | Java | asf20 | 9,659 |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* List returned by {@code ImmutableSortedSet.asList()} when the set isn't empty.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial")
final class ImmutableSortedAsList<E> extends RegularImmutableAsList<E>
implements SortedIterable<E> {
ImmutableSortedAsList(
ImmutableSortedSet<E> backingSet, ImmutableList<E> backingList) {
super(backingSet, backingList);
}
@Override
ImmutableSortedSet<E> delegateCollection() {
return (ImmutableSortedSet<E>) super.delegateCollection();
}
@Override public Comparator<? super E> comparator() {
return delegateCollection().comparator();
}
// Override indexOf() and lastIndexOf() to be O(log N) instead of O(N).
@GwtIncompatible("ImmutableSortedSet.indexOf")
// TODO(cpovirk): consider manual binary search under GWT to preserve O(log N) lookup
@Override public int indexOf(@Nullable Object target) {
int index = delegateCollection().indexOf(target);
// 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 (index >= 0 && get(index).equals(target)) ? index : -1;
}
@GwtIncompatible("ImmutableSortedSet.indexOf")
@Override public int lastIndexOf(@Nullable Object target) {
return indexOf(target);
}
@Override
public boolean contains(Object target) {
// Necessary for ISS's with comparators inconsistent with equals.
return indexOf(target) >= 0;
}
@GwtIncompatible("super.subListUnchecked does not exist; inherited subList is valid if slow")
/*
* TODO(cpovirk): if we start to override indexOf/lastIndexOf under GWT, we'll want some way to
* override subList to return an ImmutableSortedAsList for better performance. Right now, I'm not
* sure there's any performance hit from our failure to override subListUnchecked under GWT
*/
@Override
ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
return new RegularImmutableSortedSet<E>(
super.subListUnchecked(fromIndex, toIndex), comparator())
.asList();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSortedAsList.java | Java | asf20 | 3,020 |
/*
* 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.checkNotNull;
import static java.util.Arrays.asList;
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.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* An immutable {@link SetMultimap} with reliable user-specified key and value
* iteration order. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableSetMultimap(SetMultimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableSetMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableSetMultimap} 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 Mike Ward
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableSetMultimap<K, V>
extends ImmutableMultimap<K, V>
implements SetMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableSetMultimap<K, V> of() {
return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.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.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.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.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.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 {@link Builder}.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Multimap for {@link ImmutableSetMultimap.Builder} that maintains key
* and value orderings and performs better than {@link LinkedHashMultimap}.
*/
private static class BuilderMultimap<K, V> extends AbstractMapBasedMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Sets.newLinkedHashSet();
}
private static final long serialVersionUID = 0;
}
/**
* A builder for creating immutable {@code SetMultimap} instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableSetMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* <p>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 ImmutableSetMultimap#builder}.
*/
public Builder() {
builderMultimap = new BuilderMultimap<K, V>();
}
/**
* Adds a key-value mapping to the built multimap if it is not already
* present.
*/
@Override public Builder<K, V> put(K key, V value) {
builderMultimap.put(checkNotNull(key), checkNotNull(value));
return this;
}
/**
* Adds an entry to the built multimap if it is not already present.
*
* @since 11.0
*/
@Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
builderMultimap.put(
checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
return this;
}
@Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
Collection<V> collection = builderMultimap.get(checkNotNull(key));
for (V value : values) {
collection.add(checkNotNull(value));
}
return this;
}
@Override public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
@Override public Builder<K, V> putAll(
Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
this.keyComparator = checkNotNull(keyComparator);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* <p>If this method is called, the sets returned by the {@code get()}
* method of the generated multimap and its {@link Multimap#asMap()} view
* are {@link ImmutableSortedSet} instances. However, serialization does not
* preserve that property, though it does maintain the key and value
* ordering.
*
* @since 8.0
*/
// TODO: Make serialization behavior consistent.
@Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/**
* Returns a newly-created immutable set multimap.
*/
@Override public ImmutableSetMultimap<K, V> build() {
if (keyComparator != null) {
Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>();
List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList(
builderMultimap.asMap().entrySet());
Collections.sort(
entries,
Ordering.from(keyComparator).<K>onKeys());
for (Map.Entry<K, Collection<V>> entry : entries) {
sortedCopy.putAll(entry.getKey(), entry.getValue());
}
builderMultimap = sortedCopy;
}
return copyOf(builderMultimap, valueComparator);
}
}
/**
* Returns an immutable set 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.
* Repeated occurrences of an entry in the multimap after the first are
* ignored.
*
* <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> ImmutableSetMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
return copyOf(multimap, null);
}
private static <K, V> ImmutableSetMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap,
Comparator<? super V> valueComparator) {
checkNotNull(multimap); // eager for GWT
if (multimap.isEmpty() && valueComparator == null) {
return of();
}
if (multimap instanceof ImmutableSetMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableSetMultimap<K, V> kvMultimap
= (ImmutableSetMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
ImmutableMap.Builder<K, ImmutableSet<V>> builder = ImmutableMap.builder();
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
K key = entry.getKey();
Collection<? extends V> values = entry.getValue();
ImmutableSet<V> set = valueSet(valueComparator, values);
if (!set.isEmpty()) {
builder.put(key, set);
size += set.size();
}
}
return new ImmutableSetMultimap<K, V>(
builder.build(), size, valueComparator);
}
/**
* Returned by get() when a missing key is provided. Also holds the
* comparator, if any, used for values.
*/
private final transient ImmutableSet<V> emptySet;
ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size,
@Nullable Comparator<? super V> valueComparator) {
super(map, size);
this.emptySet = emptySet(valueComparator);
}
// views
/**
* Returns an immutable set of the values for the given key. If no mappings
* in the multimap have the provided key, an empty immutable set is returned.
* The values are in the same order as the parameters used to build this
* multimap.
*/
@Override public ImmutableSet<V> get(@Nullable K key) {
// This cast is safe as its type is known in constructor.
ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
return firstNonNull(set, emptySet);
}
private transient ImmutableSetMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a set multimap cannot contain multiple pairs with
* the same key and value, this method returns an {@code ImmutableSetMultimap}
* rather than the {@code ImmutableMultimap} specified in the {@code
* ImmutableMultimap} class.
*
* @since 11.0
*/
public ImmutableSetMultimap<V, K> inverse() {
ImmutableSetMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableSetMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private transient ImmutableSet<Entry<K, V>> entries;
/**
* Returns an immutable collection of all key-value pairs in the multimap.
* Its iterator traverses the values for the first key, the values for the
* second key, and so on.
*/
@Override public ImmutableSet<Entry<K, V>> entries() {
ImmutableSet<Entry<K, V>> result = entries;
return (result == null)
? (entries = new EntrySet<K, V>(this))
: result;
}
private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
private transient final ImmutableSetMultimap<K, V> multimap;
EntrySet(ImmutableSetMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override
public boolean contains(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
return multimap.containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@Override
public int size() {
return multimap.size();
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return multimap.entryIterator();
}
@Override
boolean isPartialView() {
return false;
}
}
private static <V> ImmutableSet<V> valueSet(
@Nullable Comparator<? super V> valueComparator,
Collection<? extends V> values) {
return (valueComparator == null)
? ImmutableSet.copyOf(values)
: ImmutableSortedSet.copyOf(valueComparator, values);
}
private static <V> ImmutableSet<V> emptySet(
@Nullable Comparator<? super V> valueComparator) {
return (valueComparator == null)
? ImmutableSet.<V>of()
: ImmutableSortedSet.<V>emptySet(valueComparator);
}
/**
* @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();
stream.writeObject(valueComparator());
Serialization.writeMultimap(this, stream);
}
@Nullable Comparator<? super V> valueComparator() {
return emptySet instanceof ImmutableSortedSet
? ((ImmutableSortedSet<V>) emptySet).comparator()
: null;
}
@GwtIncompatible("java.io.ObjectInputStream")
// Serialization type safety is at the caller's mercy.
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
Comparator<Object> valueComparator =
(Comparator<Object>) stream.readObject();
int keyCount = stream.readInt();
if (keyCount < 0) {
throw new InvalidObjectException("Invalid key count " + keyCount);
}
ImmutableMap.Builder<Object, ImmutableSet<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();
}
ImmutableSet<Object> valueSet = valueSet(valueComparator, asList(array));
if (valueSet.size() != array.length) {
throw new InvalidObjectException(
"Duplicate key-value pairs exist for key " + key);
}
builder.put(key, valueSet);
tmpSize += valueCount;
}
ImmutableMap<Object, ImmutableSet<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);
FieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(
this, emptySet(valueComparator));
}
@GwtIncompatible("not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSetMultimap.java | Java | asf20 | 18,287 |
/*
* 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.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.collect.MapMakerInternalMap.ReferenceEntry;
import java.util.concurrent.ConcurrentMap;
/**
* Contains static methods pertaining to instances of {@link Interner}.
*
* @author Kevin Bourrillion
* @since 3.0
*/
@Beta
public final class Interners {
private Interners() {}
/**
* Returns a new thread-safe interner which retains a strong reference to each instance it has
* interned, thus preventing these instances from being garbage-collected. If this retention is
* acceptable, this implementation may perform better than {@link #newWeakInterner}. Note that
* unlike {@link String#intern}, using this interner does not consume memory in the permanent
* generation.
*/
public static <E> Interner<E> newStrongInterner() {
final ConcurrentMap<E, E> map = new MapMaker().makeMap();
return new Interner<E>() {
@Override public E intern(E sample) {
E canonical = map.putIfAbsent(checkNotNull(sample), sample);
return (canonical == null) ? sample : canonical;
}
};
}
/**
* Returns a new thread-safe interner which retains a weak reference to each instance it has
* interned, and so does not prevent these instances from being garbage-collected. This most
* likely does not perform as well as {@link #newStrongInterner}, but is the best alternative
* when the memory usage of that implementation is unacceptable. Note that unlike {@link
* String#intern}, using this interner does not consume memory in the permanent generation.
*/
@GwtIncompatible("java.lang.ref.WeakReference")
public static <E> Interner<E> newWeakInterner() {
return new WeakInterner<E>();
}
private static class WeakInterner<E> implements Interner<E> {
// MapMaker is our friend, we know about this type
private final MapMakerInternalMap<E, Dummy> map = new MapMaker()
.weakKeys()
.keyEquivalence(Equivalence.equals())
.makeCustomMap();
@Override public E intern(E sample) {
while (true) {
// trying to read the canonical...
ReferenceEntry<E, Dummy> entry = map.getEntry(sample);
if (entry != null) {
E canonical = entry.getKey();
if (canonical != null) { // only matters if weak/soft keys are used
return canonical;
}
}
// didn't see it, trying to put it instead...
Dummy sneaky = map.putIfAbsent(sample, Dummy.VALUE);
if (sneaky == null) {
return sample;
} else {
/* Someone beat us to it! Trying again...
*
* Technically this loop not guaranteed to terminate, so theoretically (extremely
* unlikely) this thread might starve, but even then, there is always going to be another
* thread doing progress here.
*/
}
}
}
private enum Dummy { VALUE }
}
/**
* Returns a function that delegates to the {@link Interner#intern} method of the given interner.
*
* @since 8.0
*/
public static <E> Function<E, E> asFunction(Interner<E> interner) {
return new InternerFunction<E>(checkNotNull(interner));
}
private static class InternerFunction<E> implements Function<E, E> {
private final Interner<E> interner;
public InternerFunction(Interner<E> interner) {
this.interner = interner;
}
@Override public E apply(E input) {
return interner.intern(input);
}
@Override public int hashCode() {
return interner.hashCode();
}
@Override public boolean equals(Object other) {
if (other instanceof InternerFunction) {
InternerFunction<?> that = (InternerFunction<?>) other;
return interner.equals(that.interner);
}
return false;
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Interners.java | Java | asf20 | 4,663 |
/*
* 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/EnumBiMap.java | Java | asf20 | 5,013 |
/*
* 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 com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link Set} instances. Also see this
* class's counterparts {@link Lists}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets">
* {@code Sets}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Chris Povirk
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Sets {
private Sets() {}
/**
* {@link AbstractSet} substitute without the potentially-quadratic
* {@code removeAll} implementation.
*/
abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
@Override
public boolean removeAll(Collection<?> c) {
return removeAllImpl(this, c);
}
@Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(checkNotNull(c)); // GWT compatibility
}
}
/**
* Returns an immutable set instance containing the given enum elements.
* Internally, the returned set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration
* order, not the order in which the elements are provided to the method.
*
* @param anElement one of the elements the set should contain
* @param otherElements the rest of the elements the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
E anElement, E... otherElements) {
return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
}
/**
* Returns an immutable set instance containing the given enum elements.
* Internally, the returned set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration
* order, not the order in which the elements appear in the given collection.
*
* @param elements the elements, all of the same {@code enum} type, that the
* set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
Iterable<E> elements) {
if (elements instanceof ImmutableEnumSet) {
return (ImmutableEnumSet<E>) elements;
} else if (elements instanceof Collection) {
Collection<E> collection = (Collection<E>) elements;
if (collection.isEmpty()) {
return ImmutableSet.of();
} else {
return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
}
} else {
Iterator<E> itr = elements.iterator();
if (itr.hasNext()) {
EnumSet<E> enumSet = EnumSet.of(itr.next());
Iterators.addAll(enumSet, itr);
return ImmutableEnumSet.asImmutable(enumSet);
} else {
return ImmutableSet.of();
}
}
}
/**
* Returns a new {@code EnumSet} instance containing the given elements.
* Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an
* exception on an empty collection, and it may be called on any iterable, not
* just a {@code Collection}.
*/
public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable,
Class<E> elementType) {
EnumSet<E> set = EnumSet.noneOf(elementType);
Iterables.addAll(set, iterable);
return set;
}
// HashSet
/**
* Creates a <i>mutable</i>, empty {@code HashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSet#of()} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#noneOf} instead.
*
* @return a new, empty {@code HashSet}
*/
public static <E> HashSet<E> newHashSet() {
return new HashSet<E>();
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or
* {@link ImmutableSet#copyOf(Object[])} (for an array) instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#of(Enum, Enum[])} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(E... elements) {
HashSet<E> set = newHashSetWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a {@code HashSet} 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 set.
*
* @param expectedSize the number of elements you expect to add to the
* returned set
* @return a new, empty {@code HashSet} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
return new HashSet<E>(Maps.capacity(expectedSize));
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use
* {@link #newEnumSet(Iterable, Class)} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? new HashSet<E>(Collections2.cast(elements))
: newHashSet(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an
* {@link EnumSet} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
HashSet<E> set = newHashSet();
Iterators.addAll(set, elements);
return set;
}
/**
* Creates a thread-safe set backed by a hash map. The set is backed by a
* {@link ConcurrentHashMap} instance, and thus carries the same concurrency
* guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
* used as an element. The set is serializable.
*
* @return a new, empty thread-safe {@code Set}
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet() {
return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}
/**
* Creates a thread-safe set backed by a hash map and containing the given
* elements. The set is backed by a {@link ConcurrentHashMap} instance, and
* thus carries the same concurrency guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
* used as an element. The set is serializable.
*
* @param elements the elements that the set should contain
* @return a new thread-safe set containing those elements (minus duplicates)
* @throws NullPointerException if {@code elements} or any of its contents is
* null
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet(
Iterable<? extends E> elements) {
Set<E> set = newConcurrentHashSet();
Iterables.addAll(set, elements);
return set;
}
// LinkedHashSet
/**
* Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSet#of()} instead.
*
* @return a new, empty {@code LinkedHashSet}
*/
public static <E> LinkedHashSet<E> newLinkedHashSet() {
return new LinkedHashSet<E>();
}
/**
* Creates a {@code LinkedHashSet} 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 set.
*
* @param expectedSize the number of elements you expect to add to the
* returned set
* @return a new, empty {@code LinkedHashSet} with enough capacity to hold
* {@code expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 11.0
*/
public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
int expectedSize) {
return new LinkedHashSet<E>(Maps.capacity(expectedSize));
}
/**
* Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the
* given elements in order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code LinkedHashSet} containing those elements (minus
* duplicates)
*/
public static <E> LinkedHashSet<E> newLinkedHashSet(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<E>(Collections2.cast(elements));
}
LinkedHashSet<E> set = newLinkedHashSet();
Iterables.addAll(set, elements);
return set;
}
// TreeSet
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the
* natural sort ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedSet#of()} instead.
*
* @return a new, empty {@code TreeSet}
*/
public static <E extends Comparable> TreeSet<E> newTreeSet() {
return new TreeSet<E>();
}
/**
* Creates a <i>mutable</i> {@code TreeSet} instance containing the given
* elements sorted by their natural ordering.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit
* comparator, this method has different behavior than
* {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with
* that comparator.
*
* @param elements the elements that the set should contain
* @return a new {@code TreeSet} containing those elements (minus duplicates)
*/
public static <E extends Comparable> TreeSet<E> newTreeSet(
Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
Iterables.addAll(set, elements);
return set;
}
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedSet.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to use to sort the set
* @return a new, empty {@code TreeSet}
* @throws NullPointerException if {@code comparator} is null
*/
public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
return new TreeSet<E>(checkNotNull(comparator));
}
/**
* Creates an empty {@code Set} that uses identity to determine equality. It
* compares object references, instead of calling {@code equals}, to
* determine whether a provided object matches an element in the set. For
* example, {@code contains} returns {@code false} when passed an object that
* equals a set member, but isn't the same instance. This behavior is similar
* to the way {@code IdentityHashMap} handles key lookups.
*
* @since 8.0
*/
public static <E> Set<E> newIdentityHashSet() {
return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
}
/**
* Creates an empty {@code CopyOnWriteArraySet} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link Set}, use
* {@link Collections#emptySet} instead.
*
* @return a new, empty {@code CopyOnWriteArraySet}
* @since 12.0
*/
@GwtIncompatible("CopyOnWriteArraySet")
public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
return new CopyOnWriteArraySet<E>();
}
/**
* Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code CopyOnWriteArraySet} containing those elements
* @since 12.0
*/
@GwtIncompatible("CopyOnWriteArraySet")
public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
Iterable<? extends E> elements) {
// We copy elements to an ArrayList first, rather than incurring the
// quadratic cost of adding them to the COWAS directly.
Collection<? extends E> elementsCollection = (elements instanceof Collection)
? Collections2.cast(elements)
: Lists.newArrayList(elements);
return new CopyOnWriteArraySet<E>(elementsCollection);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in
* the specified collection. If the collection is an {@link EnumSet}, this
* method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
* the specified collection must contain at least one element, in order to
* determine the element type. If the collection could be empty, use
* {@link #complementOf(Collection, Class)} instead of this method.
*
* @param collection the collection whose complement should be stored in the
* enum set
* @return a new, modifiable {@code EnumSet} containing all values of the enum
* that aren't present in the given collection
* @throws IllegalArgumentException if {@code collection} is not an
* {@code EnumSet} instance and contains no elements
*/
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection) {
if (collection instanceof EnumSet) {
return EnumSet.complementOf((EnumSet<E>) collection);
}
checkArgument(!collection.isEmpty(),
"collection is empty; use the other version of this method");
Class<E> type = collection.iterator().next().getDeclaringClass();
return makeComplementByHand(collection, type);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in
* the specified collection. This is equivalent to
* {@link EnumSet#complementOf}, but can act on any input collection, as long
* as the elements are of enum type.
*
* @param collection the collection whose complement should be stored in the
* {@code EnumSet}
* @param type the type of the elements in the set
* @return a new, modifiable {@code EnumSet} initially containing all the
* values of the enum not present in the given collection
*/
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection, Class<E> type) {
checkNotNull(collection);
return (collection instanceof EnumSet)
? EnumSet.complementOf((EnumSet<E>) collection)
: makeComplementByHand(collection, type);
}
private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
Collection<E> collection, Class<E> type) {
EnumSet<E> result = EnumSet.allOf(type);
result.removeAll(collection);
return result;
}
/**
* Returns a set backed by the specified map. The resulting set displays
* the same ordering, concurrency, and performance characteristics as the
* backing map. In essence, this factory method provides a {@link Set}
* implementation corresponding to any {@link Map} implementation. There is no
* need to use this method on a {@link Map} implementation that already has a
* corresponding {@link Set} implementation (such as {@link java.util.HashMap}
* or {@link java.util.TreeMap}).
*
* <p>Each method invocation on the set returned by this method results in
* exactly one method invocation on the backing map or its {@code keySet}
* view, with one exception. The {@code addAll} method is implemented as a
* sequence of {@code put} invocations on the backing map.
*
* <p>The specified map must be empty at the time this method is invoked,
* and should not be accessed directly after this method returns. These
* conditions are ensured if the map is created empty, passed directly
* to this method, and no reference to the map is retained, as illustrated
* in the following code fragment: <pre> {@code
*
* Set<Object> identityHashSet = Sets.newSetFromMap(
* new IdentityHashMap<Object, Boolean>());}</pre>
*
* <p>This method has the same behavior as the JDK 6 method
* {@code Collections.newSetFromMap()}. The returned set is serializable if
* the backing map is.
*
* @param map the backing map
* @return the set backed by the map
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
return Platform.newSetFromMap(map);
}
/**
* An unmodifiable view of a set which may be backed by other sets; this view
* will change as the backing sets do. Contains methods to copy the data into
* a new set which will then remain stable. There is usually no reason to
* retain a reference of type {@code SetView}; typically, you either use it
* as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
* {@link #copyInto} and forget the {@code SetView} itself.
*
* @since 2.0 (imported from Google Collections Library)
*/
public abstract static class SetView<E> extends AbstractSet<E> {
private SetView() {} // no subclasses but our own
/**
* Returns an immutable copy of the current contents of this set view.
* Does not support null elements.
*
* <p><b>Warning:</b> this may have unexpected results if a backing set of
* this view uses a nonstandard notion of equivalence, for example if it is
* a {@link TreeSet} using a comparator that is inconsistent with {@link
* Object#equals(Object)}.
*/
public ImmutableSet<E> immutableCopy() {
return ImmutableSet.copyOf(this);
}
/**
* Copies the current contents of this set view into an existing set. This
* method has equivalent behavior to {@code set.addAll(this)}, assuming that
* all the sets involved are based on the same notion of equivalence.
*
* @return a reference to {@code set}, for convenience
*/
// Note: S should logically extend Set<? super E> but can't due to either
// some javac bug or some weirdness in the spec, not sure which.
public <S extends Set<E>> S copyInto(S set) {
set.addAll(this);
return set;
}
}
/**
* Returns an unmodifiable <b>view</b> of the union of two sets. The returned
* set contains all elements that are contained in either backing set.
* Iterating over the returned set iterates first over all the elements of
* {@code set1}, then over each element of {@code set2}, in order, that is not
* contained in {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on
* different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
* the {@link Map#keySet} of an {@code IdentityHashMap} all are).
*
* <p><b>Note:</b> The returned view performs better when {@code set1} is the
* smaller of the two sets. If you have reason to believe one of your sets
* will generally be smaller than the other, pass it first.
*
* <p>Further, note that the current implementation is not suitable for nested
* {@code union} views, i.e. the following should be avoided when in a loop:
* {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
* set has a cubic complexity to the depth of the nesting.
*/
public static <E> SetView<E> union(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Set<? extends E> set2minus1 = difference(set2, set1);
return new SetView<E>() {
@Override public int size() {
return set1.size() + set2minus1.size();
}
@Override public boolean isEmpty() {
return set1.isEmpty() && set2.isEmpty();
}
@Override public Iterator<E> iterator() {
return Iterators.unmodifiableIterator(
Iterators.concat(set1.iterator(), set2minus1.iterator()));
}
@Override public boolean contains(Object object) {
return set1.contains(object) || set2.contains(object);
}
@Override public <S extends Set<E>> S copyInto(S set) {
set.addAll(set1);
set.addAll(set2);
return set;
}
@Override public ImmutableSet<E> immutableCopy() {
return new ImmutableSet.Builder<E>()
.addAll(set1).addAll(set2).build();
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the intersection of two sets. The
* returned set contains all elements that are contained by both backing sets.
* The iteration order of the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*
* <p><b>Note:</b> The returned view performs slightly better when {@code
* set1} is the smaller of the two sets. If you have reason to believe one of
* your sets will generally be smaller than the other, pass it first.
* Unfortunately, since this method sets the generic type of the returned set
* based on the type of the first set passed, this could in rare cases force
* you to make a cast, for example: <pre> {@code
*
* Set<Object> aFewBadObjects = ...
* Set<String> manyBadStrings = ...
*
* // impossible for a non-String to be in the intersection
* SuppressWarnings("unchecked")
* Set<String> badStrings = (Set) Sets.intersection(
* aFewBadObjects, manyBadStrings);}</pre>
*
* <p>This is unfortunate, but should come up only very rarely.
*/
public static <E> SetView<E> intersection(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Predicate<Object> inSet2 = Predicates.in(set2);
return new SetView<E>() {
@Override public Iterator<E> iterator() {
return Iterators.filter(set1.iterator(), inSet2);
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean isEmpty() {
return !iterator().hasNext();
}
@Override public boolean contains(Object object) {
return set1.contains(object) && set2.contains(object);
}
@Override public boolean containsAll(Collection<?> collection) {
return set1.containsAll(collection)
&& set2.containsAll(collection);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the difference of two sets. The
* returned set contains all elements that are contained by {@code set1} and
* not contained by {@code set2}. {@code set2} may also contain elements not
* present in {@code set1}; these are simply ignored. The iteration order of
* the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*/
public static <E> SetView<E> difference(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
return new SetView<E>() {
@Override public Iterator<E> iterator() {
return Iterators.filter(set1.iterator(), notInSet2);
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean isEmpty() {
return set2.containsAll(set1);
}
@Override public boolean contains(Object element) {
return set1.contains(element) && !set2.contains(element);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the symmetric difference of two
* sets. The returned set contains all elements that are contained in either
* {@code set1} or {@code set2} but not in both. The iteration order of the
* returned set is undefined.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*
* @since 3.0
*/
public static <E> SetView<E> symmetricDifference(
Set<? extends E> set1, Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
// TODO(kevinb): Replace this with a more efficient implementation
return difference(union(set1, set2), intersection(set1, set2));
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* returned set is a live view of {@code unfiltered}; changes to one affect
* the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set'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 set, only
* elements that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate
* across every element in the underlying set 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 to omit that last sentence when building GWT javadoc?
public static <E> Set<E> filter(
Set<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof SortedSet) {
return filter((SortedSet<E>) unfiltered, predicate);
}
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredSet<E>(
(Set<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSet<E> extends FilteredCollection<E>
implements Set<E> {
FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override public boolean equals(@Nullable Object object) {
return equalsImpl(this, object);
}
@Override public int hashCode() {
return hashCodeImpl(this);
}
}
/**
* Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
* satisfy a predicate. The returned set is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set'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 set,
* only elements that satisfy the filter will be removed from the underlying
* set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across
* every element in the underlying set 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.)
*
* @since 11.0
*/
public static <E> SortedSet<E> filter(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
return Platform.setsFilterSortedSet(unfiltered, predicate);
}
static <E> SortedSet<E> filterSortedIgnoreNavigable(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredSortedSet<E>(
(SortedSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSortedSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSortedSet<E> extends FilteredSet<E>
implements SortedSet<E> {
FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override
public Comparator<? super E> comparator() {
return ((SortedSet<E>) unfiltered).comparator();
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement),
predicate);
}
@Override
public SortedSet<E> headSet(E toElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
}
@Override
public E first() {
return iterator().next();
}
@Override
public E last() {
SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
while (true) {
E element = sortedUnfiltered.last();
if (predicate.apply(element)) {
return element;
}
sortedUnfiltered = sortedUnfiltered.headSet(element);
}
}
}
/**
* Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that
* satisfy a predicate. The returned set is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set'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 set,
* only elements that satisfy the filter will be removed from the underlying
* set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across
* every element in the underlying set 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.)
*
* @since 14.0
*/
@GwtIncompatible("NavigableSet")
@SuppressWarnings("unchecked")
public static <E> NavigableSet<E> filter(
NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredNavigableSet<E>(
(NavigableSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredNavigableSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
@GwtIncompatible("NavigableSet")
private static class FilteredNavigableSet<E> extends FilteredSortedSet<E>
implements NavigableSet<E> {
FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
NavigableSet<E> unfiltered() {
return (NavigableSet<E>) unfiltered;
}
@Override
@Nullable
public E lower(E e) {
return Iterators.getNext(headSet(e, false).descendingIterator(), null);
}
@Override
@Nullable
public E floor(E e) {
return Iterators.getNext(headSet(e, true).descendingIterator(), null);
}
@Override
public E ceiling(E e) {
return Iterables.getFirst(tailSet(e, true), null);
}
@Override
public E higher(E e) {
return Iterables.getFirst(tailSet(e, false), null);
}
@Override
public E pollFirst() {
return Iterables.removeFirstMatching(unfiltered(), predicate);
}
@Override
public E pollLast() {
return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate);
}
@Override
public NavigableSet<E> descendingSet() {
return Sets.filter(unfiltered().descendingSet(), predicate);
}
@Override
public Iterator<E> descendingIterator() {
return Iterators.filter(unfiltered().descendingIterator(), predicate);
}
@Override
public E last() {
return descendingIterator().next();
}
@Override
public NavigableSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return filter(
unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate);
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return filter(unfiltered().headSet(toElement, inclusive), predicate);
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return filter(unfiltered().tailSet(fromElement, inclusive), predicate);
}
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given sets in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example: <pre> {@code
*
* Sets.cartesianProduct(ImmutableList.of(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C")))}</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be
* empty. If no sets at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size
* {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian set is constructed, the
* input sets are merely copied. Only as the resulting set is iterated are the
* individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that
* the elements chosen from those sets should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable set containing immutable
* lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets},
* or any element of a provided set is null
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(
List<? extends Set<? extends B>> sets) {
return CartesianSet.create(sets);
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given sets in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example: <pre> {@code
*
* Sets.cartesianProduct(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C"))}</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be
* empty. If no sets at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size
* {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian set is constructed, the
* input sets are merely copied. Only as the resulting set is iterated are the
* individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that
* the elements chosen from those sets should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable set containing immutable
* lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets},
* or any element of a provided set is null
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(
Set<? extends B>... sets) {
return cartesianProduct(Arrays.asList(sets));
}
private static final class CartesianSet<E>
extends ForwardingCollection<List<E>> implements Set<List<E>> {
private transient final ImmutableList<ImmutableSet<E>> axes;
private transient final CartesianList<E> delegate;
static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
ImmutableList.Builder<ImmutableSet<E>> axesBuilder =
new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
for (Set<? extends E> set : sets) {
ImmutableSet<E> copy = ImmutableSet.copyOf(set);
if (copy.isEmpty()) {
return ImmutableSet.of();
}
axesBuilder.add(copy);
}
final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() {
@Override
public int size() {
return axes.size();
}
@Override
public List<E> get(int index) {
return axes.get(index).asList();
}
@Override
boolean isPartialView() {
return true;
}
};
return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
}
private CartesianSet(
ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
this.axes = axes;
this.delegate = delegate;
}
@Override
protected Collection<List<E>> delegate() {
return delegate;
}
@Override public boolean equals(@Nullable Object object) {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
if (object instanceof CartesianSet) {
CartesianSet<?> that = (CartesianSet<?>) object;
return this.axes.equals(that.axes);
}
return super.equals(object);
}
@Override
public int hashCode() {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
// It's a weird formula, but tests prove it works.
int adjust = size() - 1;
for (int i = 0; i < axes.size(); i++) {
adjust *= 31;
adjust = ~~adjust;
// in GWT, we have to deal with integer overflow carefully
}
int hash = 1;
for (Set<E> axis : axes) {
hash = 31 * hash + (size() / axis.size() * axis.hashCode());
hash = ~~hash;
}
hash += adjust;
return ~~hash;
}
}
/**
* Returns the set of all possible subsets of {@code set}. For example,
* {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
* {1}, {2}, {1, 2}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they
* appeared in the input set. The order in which these subsets appear in the
* outer set is undefined. Note that the power set of the empty set is not the
* empty set, but a one-element set containing the empty set.
*
* <p>The returned set and its constituent sets use {@code equals} to decide
* whether two elements are identical, even if the input set uses a different
* concept of equivalence.
*
* <p><i>Performance notes:</i> while the power set of a set with size {@code
* n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
* power set is constructed, the input set is merely copied. Only as the
* power set is iterated are the individual subsets created, and these subsets
* themselves occupy only a small constant amount of memory.
*
* @param set the set of elements to construct a power set from
* @return the power set, as an immutable set of immutable sets
* @throws IllegalArgumentException if {@code set} has more than 30 unique
* elements (causing the power set size to exceed the {@code int} range)
* @throws NullPointerException if {@code set} is or contains {@code null}
* @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
* Wikipedia</a>
* @since 4.0
*/
@GwtCompatible(serializable = false)
public static <E> Set<Set<E>> powerSet(Set<E> set) {
return new PowerSet<E>(set);
}
private static final class SubSet<E> extends AbstractSet<E> {
private final ImmutableMap<E, Integer> inputSet;
private final int mask;
SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
this.inputSet = inputSet;
this.mask = mask;
}
@Override
public Iterator<E> iterator() {
return new UnmodifiableIterator<E>() {
final ImmutableList<E> elements = inputSet.keySet().asList();
int remainingSetBits = mask;
@Override
public boolean hasNext() {
return remainingSetBits != 0;
}
@Override
public E next() {
int index = Integer.numberOfTrailingZeros(remainingSetBits);
if (index == 32) {
throw new NoSuchElementException();
}
remainingSetBits &= ~(1 << index);
return elements.get(index);
}
};
}
@Override
public int size() {
return Integer.bitCount(mask);
}
@Override
public boolean contains(@Nullable Object o) {
Integer index = inputSet.get(o);
return index != null && (mask & (1 << index)) != 0;
}
}
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableMap<E, Integer> inputSet;
PowerSet(Set<E> input) {
ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
int i = 0;
for (E e : checkNotNull(input)) {
builder.put(e, i++);
}
this.inputSet = builder.build();
checkArgument(inputSet.size() <= 30,
"Too many elements to create power set: %s > 30", inputSet.size());
}
@Override public int size() {
return 1 << inputSet.size();
}
@Override public boolean isEmpty() {
return false;
}
@Override public Iterator<Set<E>> iterator() {
return new AbstractIndexedListIterator<Set<E>>(size()) {
@Override protected Set<E> get(final int setBits) {
return new SubSet<E>(inputSet, setBits);
}
};
}
@Override public boolean contains(@Nullable Object obj) {
if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
return inputSet.keySet().containsAll(set);
}
return false;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof PowerSet) {
PowerSet<?> that = (PowerSet<?>) obj;
return inputSet.equals(that.inputSet);
}
return super.equals(obj);
}
@Override public int hashCode() {
/*
* The sum of the sums of the hash codes in each subset is just the sum of
* each input element's hash code times the number of sets that element
* appears in. Each element appears in exactly half of the 2^n sets, so:
*/
return inputSet.keySet().hashCode() << (inputSet.size() - 1);
}
@Override public String toString() {
return "powerSet(" + inputSet + ")";
}
}
/**
* An implementation for {@link Set#hashCode()}.
*/
static int hashCodeImpl(Set<?> s) {
int hashCode = 0;
for (Object o : s) {
hashCode += o != null ? o.hashCode() : 0;
hashCode = ~~hashCode;
// Needed to deal with unusual integer overflow in GWT.
}
return hashCode;
}
/**
* An implementation for {@link Set#equals(Object)}.
*/
static boolean equalsImpl(Set<?> s, @Nullable Object object) {
if (s == object) {
return true;
}
if (object instanceof Set) {
Set<?> o = (Set<?>) object;
try {
return s.size() == o.size() && s.containsAll(o);
} catch (NullPointerException ignored) {
return false;
} catch (ClassCastException ignored) {
return false;
}
}
return false;
}
/**
* Returns an unmodifiable view of the specified navigable set. This method
* allows modules to provide users with "read-only" access to internal
* navigable sets. Query operations on the returned set "read through" to the
* specified set, and attempts to modify the returned set, whether direct or
* via its collection views, result in an
* {@code UnsupportedOperationException}.
*
* <p>The returned navigable set will be serializable if the specified
* navigable set is serializable.
*
* @param set the navigable set for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified navigable set
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
public static <E> NavigableSet<E> unmodifiableNavigableSet(
NavigableSet<E> set) {
if (set instanceof ImmutableSortedSet
|| set instanceof UnmodifiableNavigableSet) {
return set;
}
return new UnmodifiableNavigableSet<E>(set);
}
@GwtIncompatible("NavigableSet")
static final class UnmodifiableNavigableSet<E>
extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable {
private final NavigableSet<E> delegate;
UnmodifiableNavigableSet(NavigableSet<E> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
protected SortedSet<E> delegate() {
return Collections.unmodifiableSortedSet(delegate);
}
@Override
public E lower(E e) {
return delegate.lower(e);
}
@Override
public E floor(E e) {
return delegate.floor(e);
}
@Override
public E ceiling(E e) {
return delegate.ceiling(e);
}
@Override
public E higher(E e) {
return delegate.higher(e);
}
@Override
public E pollFirst() {
throw new UnsupportedOperationException();
}
@Override
public E pollLast() {
throw new UnsupportedOperationException();
}
private transient UnmodifiableNavigableSet<E> descendingSet;
@Override
public NavigableSet<E> descendingSet() {
UnmodifiableNavigableSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = new UnmodifiableNavigableSet<E>(
delegate.descendingSet());
result.descendingSet = this;
}
return result;
}
@Override
public Iterator<E> descendingIterator() {
return Iterators.unmodifiableIterator(delegate.descendingIterator());
}
@Override
public NavigableSet<E> subSet(
E fromElement,
boolean fromInclusive,
E toElement,
boolean toInclusive) {
return unmodifiableNavigableSet(delegate.subSet(
fromElement,
fromInclusive,
toElement,
toInclusive));
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return unmodifiableNavigableSet(
delegate.tailSet(fromElement, inclusive));
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) navigable set backed by the specified
* navigable set. In order to guarantee serial access, it is critical that
* <b>all</b> access to the backing navigable set is accomplished
* through the returned navigable set (or its views).
*
* <p>It is imperative that the user manually synchronize on the returned
* sorted set when iterating over it or any of its {@code descendingSet},
* {@code subSet}, {@code headSet}, or {@code tailSet} views. <pre> {@code
*
* NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
* ...
* synchronized (set) {
* // Must be in the synchronized block
* Iterator<E> it = set.iterator();
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* <p>or: <pre> {@code
*
* NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
* NavigableSet<E> set2 = set.descendingSet().headSet(foo);
* ...
* synchronized (set) { // Note: set, not set2!!!
* // Must be in the synchronized block
* Iterator<E> it = set2.descendingIterator();
* while (it.hasNext())
* foo(it.next());
* }
* }}</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned navigable set will be serializable if the specified
* navigable set is serializable.
*
* @param navigableSet the navigable set to be "wrapped" in a synchronized
* navigable set.
* @return a synchronized view of the specified navigable set.
* @since 13.0
*/
@GwtIncompatible("NavigableSet")
public static <E> NavigableSet<E> synchronizedNavigableSet(
NavigableSet<E> navigableSet) {
return Synchronized.navigableSet(navigableSet);
}
/**
* Remove each element in an iterable from a set.
*/
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
boolean changed = false;
while (iterator.hasNext()) {
changed |= set.remove(iterator.next());
}
return changed;
}
static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
checkNotNull(collection); // for GWT
if (collection instanceof Multiset) {
collection = ((Multiset<?>) collection).elementSet();
}
/*
* AbstractSet.removeAll(List) has quadratic behavior if the list size
* is just less than the set's size. We augment the test by
* assuming that sets have fast contains() performance, and other
* collections don't. See
* http://code.google.com/p/guava-libraries/issues/detail?id=1013
*/
if (collection instanceof Set && collection.size() > set.size()) {
return Iterators.removeAll(set.iterator(), collection);
} else {
return removeAllImpl(set, collection.iterator());
}
}
@GwtIncompatible("NavigableSet")
static class DescendingSet<E> extends ForwardingNavigableSet<E> {
private final NavigableSet<E> forward;
DescendingSet(NavigableSet<E> forward) {
this.forward = forward;
}
@Override
protected NavigableSet<E> delegate() {
return forward;
}
@Override
public E lower(E e) {
return forward.higher(e);
}
@Override
public E floor(E e) {
return forward.ceiling(e);
}
@Override
public E ceiling(E e) {
return forward.floor(e);
}
@Override
public E higher(E e) {
return forward.lower(e);
}
@Override
public E pollFirst() {
return forward.pollLast();
}
@Override
public E pollLast() {
return forward.pollFirst();
}
@Override
public NavigableSet<E> descendingSet() {
return forward;
}
@Override
public Iterator<E> descendingIterator() {
return forward.iterator();
}
@Override
public NavigableSet<E> subSet(
E fromElement,
boolean fromInclusive,
E toElement,
boolean toInclusive) {
return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return forward.tailSet(toElement, inclusive).descendingSet();
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return forward.headSet(fromElement, inclusive).descendingSet();
}
@SuppressWarnings("unchecked")
@Override
public Comparator<? super E> comparator() {
Comparator<? super E> forwardComparator = forward.comparator();
if (forwardComparator == null) {
return (Comparator) Ordering.natural().reverse();
} else {
return reverse(forwardComparator);
}
}
// 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 E first() {
return forward.last();
}
@Override
public SortedSet<E> headSet(E toElement) {
return standardHeadSet(toElement);
}
@Override
public E last() {
return forward.first();
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return standardSubSet(fromElement, toElement);
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return standardTailSet(fromElement);
}
@Override
public Iterator<E> iterator() {
return forward.descendingIterator();
}
@Override
public Object[] toArray() {
return standardToArray();
}
@Override
public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override
public String toString() {
return standardToString();
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Sets.java | Java | asf20 | 60,037 |
/*
* 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.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Maps.ImprovedAbstractMap;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link Multimap} interface. This class represents
* a multimap as a map that associates each key with a collection of values. All
* methods of {@link Multimap} are supported, including those specified as
* optional in the interface.
*
* <p>To implement a multimap, a subclass must define the method {@link
* #createCollection()}, which creates an empty collection of values for a key.
*
* <p>The multimap constructor takes a map that has a single entry for each
* distinct key. When you insert a key-value pair with a key that isn't already
* in the multimap, {@code AbstractMapBasedMultimap} calls {@link #createCollection()}
* to create the collection of values for that key. The subclass should not call
* {@link #createCollection()} directly, and a new instance should be created
* every time the method is called.
*
* <p>For example, the subclass could pass a {@link java.util.TreeMap} during
* construction, and {@link #createCollection()} could return a {@link
* java.util.TreeSet}, in which case the multimap's iterators would propagate
* through the keys and values in sorted order.
*
* <p>Keys and values may be null, as long as the underlying collection classes
* support null elements.
*
* <p>The collections created by {@link #createCollection()} may or may not
* allow duplicates. If the collection, such as a {@link Set}, does not support
* duplicates, an added key-value pair will replace an existing pair with the
* same key and value, if such a pair is present. With collections like {@link
* List} that allow duplicates, the collection will keep the existing key-value
* pairs while adding a new pair.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap, even if the underlying map and {@link #createCollection()} method
* return threadsafe classes. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedMultimap}.
*
* <p>For serialization to work, the subclass must specify explicit
* {@code readObject} and {@code writeObject} methods.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultimap<K, V> extends AbstractMultimap<K, V>
implements Serializable {
/*
* Here's an outline of the overall design.
*
* The map variable contains the collection of values associated with each
* key. When a key-value pair is added to a multimap that didn't previously
* contain any values for that key, a new collection generated by
* createCollection is added to the map. That same collection instance
* remains in the map as long as the multimap has any values for the key. If
* all values for the key are removed, the key and collection are removed
* from the map.
*
* The get method returns a WrappedCollection, which decorates the collection
* in the map (if the key is present) or an empty collection (if the key is
* not present). When the collection delegate in the WrappedCollection is
* empty, the multimap may contain subsequently added values for that key. To
* handle that situation, the WrappedCollection checks whether map contains
* an entry for the provided key, and if so replaces the delegate.
*/
private transient Map<K, Collection<V>> map;
private transient int totalSize;
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @throws IllegalArgumentException if {@code map} is not empty
*/
protected AbstractMapBasedMultimap(Map<K, Collection<V>> map) {
checkArgument(map.isEmpty());
this.map = map;
}
/** Used during deserialization only. */
final void setMap(Map<K, Collection<V>> map) {
this.map = map;
totalSize = 0;
for (Collection<V> values : map.values()) {
checkArgument(!values.isEmpty());
totalSize += values.size();
}
}
/**
* Creates an unmodifiable, empty collection of values.
*
* <p>This is used in {@link #removeAll} on an empty key.
*/
Collection<V> createUnmodifiableEmptyCollection() {
return unmodifiableCollectionSubclass(createCollection());
}
/**
* Creates the collection of values for a single key.
*
* <p>Collections with weak, soft, or phantom references are not supported.
* Each call to {@code createCollection} should create a new instance.
*
* <p>The returned collection class determines whether duplicate key-value
* pairs are allowed.
*
* @return an empty collection of values
*/
abstract Collection<V> createCollection();
/**
* Creates the collection of values for an explicitly provided key. By
* default, it simply calls {@link #createCollection()}, which is the correct
* behavior for most implementations. The {@link LinkedHashMultimap} class
* overrides it.
*
* @param key key to associate with values in the collection
* @return an empty collection of values
*/
Collection<V> createCollection(@Nullable K key) {
return createCollection();
}
Map<K, Collection<V>> backingMap() {
return map;
}
// Query Operations
@Override
public int size() {
return totalSize;
}
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
// Modification Operations
@Override
public boolean put(@Nullable K key, @Nullable V value) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
if (collection.add(value)) {
totalSize++;
map.put(key, collection);
return true;
} else {
throw new AssertionError("New Collection violated the Collection spec");
}
} else if (collection.add(value)) {
totalSize++;
return true;
} else {
return false;
}
}
private Collection<V> getOrCreateCollection(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
map.put(key, collection);
}
return collection;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
Iterator<? extends V> iterator = values.iterator();
if (!iterator.hasNext()) {
return removeAll(key);
}
// TODO(user): investigate atomic failure?
Collection<V> collection = getOrCreateCollection(key);
Collection<V> oldValues = createCollection();
oldValues.addAll(collection);
totalSize -= collection.size();
collection.clear();
while (iterator.hasNext()) {
if (collection.add(iterator.next())) {
totalSize++;
}
}
return unmodifiableCollectionSubclass(oldValues);
}
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> removeAll(@Nullable Object key) {
Collection<V> collection = map.remove(key);
if (collection == null) {
return createUnmodifiableEmptyCollection();
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return unmodifiableCollectionSubclass(output);
}
Collection<V> unmodifiableCollectionSubclass(Collection<V> collection) {
// We don't deal with NavigableSet here yet for GWT reasons -- instead,
// non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
} else {
return Collections.unmodifiableCollection(collection);
}
}
@Override
public void clear() {
// Clear each collection, to make previously returned collections empty.
for (Collection<V> collection : map.values()) {
collection.clear();
}
map.clear();
totalSize = 0;
}
// Views
/**
* {@inheritDoc}
*
* <p>The returned collection is not serializable.
*/
@Override
public Collection<V> get(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key, collection);
}
/**
* Generates a decorated collection that remains consistent with the values in
* the multimap for the provided key. Changes to the multimap may alter the
* returned collection, and vice versa.
*/
Collection<V> wrapCollection(@Nullable K key, Collection<V> collection) {
// We don't deal with NavigableSet here yet for GWT reasons -- instead,
// non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
if (collection instanceof SortedSet) {
return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
} else if (collection instanceof Set) {
return new WrappedSet(key, (Set<V>) collection);
} else if (collection instanceof List) {
return wrapList(key, (List<V>) collection, null);
} else {
return new WrappedCollection(key, collection, null);
}
}
private List<V> wrapList(
@Nullable K key, List<V> list, @Nullable WrappedCollection ancestor) {
return (list instanceof RandomAccess)
? new RandomAccessWrappedList(key, list, ancestor)
: new WrappedList(key, list, ancestor);
}
/**
* Collection decorator that stays in sync with the multimap values for a key.
* There are two kinds of wrapped collections: full and subcollections. Both
* have a delegate pointing to the underlying collection class.
*
* <p>Full collections, identified by a null ancestor field, contain all
* multimap values for a given key. Its delegate is a value in {@link
* AbstractMapBasedMultimap#map} whenever the delegate is non-empty. The {@code
* refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure
* that the {@code WrappedCollection} and map remain consistent.
*
* <p>A subcollection, such as a sublist, contains some of the values for a
* given key. Its ancestor field points to the full wrapped collection with
* all values for the key. The subcollection {@code refreshIfEmpty}, {@code
* removeIfEmpty}, and {@code addToMap} methods call the corresponding methods
* of the full wrapped collection.
*/
private class WrappedCollection extends AbstractCollection<V> {
final K key;
Collection<V> delegate;
final WrappedCollection ancestor;
final Collection<V> ancestorDelegate;
WrappedCollection(@Nullable K key, Collection<V> delegate,
@Nullable WrappedCollection ancestor) {
this.key = key;
this.delegate = delegate;
this.ancestor = ancestor;
this.ancestorDelegate
= (ancestor == null) ? null : ancestor.getDelegate();
}
/**
* If the delegate collection is empty, but the multimap has values for the
* key, replace the delegate with the new collection for the key.
*
* <p>For a subcollection, refresh its ancestor and validate that the
* ancestor delegate hasn't changed.
*/
void refreshIfEmpty() {
if (ancestor != null) {
ancestor.refreshIfEmpty();
if (ancestor.getDelegate() != ancestorDelegate) {
throw new ConcurrentModificationException();
}
} else if (delegate.isEmpty()) {
Collection<V> newDelegate = map.get(key);
if (newDelegate != null) {
delegate = newDelegate;
}
}
}
/**
* If collection is empty, remove it from {@code AbstractMapBasedMultimap.this.map}.
* For subcollections, check whether the ancestor collection is empty.
*/
void removeIfEmpty() {
if (ancestor != null) {
ancestor.removeIfEmpty();
} else if (delegate.isEmpty()) {
map.remove(key);
}
}
K getKey() {
return key;
}
/**
* Add the delegate to the map. Other {@code WrappedCollection} methods
* should call this method after adding elements to a previously empty
* collection.
*
* <p>Subcollection add the ancestor's delegate instead.
*/
void addToMap() {
if (ancestor != null) {
ancestor.addToMap();
} else {
map.put(key, delegate);
}
}
@Override public int size() {
refreshIfEmpty();
return delegate.size();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
refreshIfEmpty();
return delegate.equals(object);
}
@Override public int hashCode() {
refreshIfEmpty();
return delegate.hashCode();
}
@Override public String toString() {
refreshIfEmpty();
return delegate.toString();
}
Collection<V> getDelegate() {
return delegate;
}
@Override public Iterator<V> iterator() {
refreshIfEmpty();
return new WrappedIterator();
}
/** Collection iterator for {@code WrappedCollection}. */
class WrappedIterator implements Iterator<V> {
final Iterator<V> delegateIterator;
final Collection<V> originalDelegate = delegate;
WrappedIterator() {
delegateIterator = iteratorOrListIterator(delegate);
}
WrappedIterator(Iterator<V> delegateIterator) {
this.delegateIterator = delegateIterator;
}
/**
* If the delegate changed since the iterator was created, the iterator is
* no longer valid.
*/
void validateIterator() {
refreshIfEmpty();
if (delegate != originalDelegate) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
validateIterator();
return delegateIterator.hasNext();
}
@Override
public V next() {
validateIterator();
return delegateIterator.next();
}
@Override
public void remove() {
delegateIterator.remove();
totalSize--;
removeIfEmpty();
}
Iterator<V> getDelegateIterator() {
validateIterator();
return delegateIterator;
}
}
@Override public boolean add(V value) {
refreshIfEmpty();
boolean wasEmpty = delegate.isEmpty();
boolean changed = delegate.add(value);
if (changed) {
totalSize++;
if (wasEmpty) {
addToMap();
}
}
return changed;
}
WrappedCollection getAncestor() {
return ancestor;
}
// The following methods are provided for better performance.
@Override public boolean addAll(Collection<? extends V> collection) {
if (collection.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.addAll(collection);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override public boolean contains(Object o) {
refreshIfEmpty();
return delegate.contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
refreshIfEmpty();
return delegate.containsAll(c);
}
@Override public void clear() {
int oldSize = size(); // calls refreshIfEmpty
if (oldSize == 0) {
return;
}
delegate.clear();
totalSize -= oldSize;
removeIfEmpty(); // maybe shouldn't be removed if this is a sublist
}
@Override public boolean remove(Object o) {
refreshIfEmpty();
boolean changed = delegate.remove(o);
if (changed) {
totalSize--;
removeIfEmpty();
}
return changed;
}
@Override public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.removeAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
checkNotNull(c);
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.retainAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
private Iterator<V> iteratorOrListIterator(Collection<V> collection) {
return (collection instanceof List)
? ((List<V>) collection).listIterator()
: collection.iterator();
}
/** Set decorator that stays in sync with the multimap values for a key. */
private class WrappedSet extends WrappedCollection implements Set<V> {
WrappedSet(@Nullable K key, Set<V> delegate) {
super(key, delegate, null);
}
@Override
public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
// Guava issue 1013: AbstractSet and most JDK set implementations are
// susceptible to quadratic removeAll performance on lists;
// use a slightly smarter implementation here
boolean changed = Sets.removeAllImpl((Set<V>) delegate, c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
/**
* SortedSet decorator that stays in sync with the multimap values for a key.
*/
private class WrappedSortedSet extends WrappedCollection
implements SortedSet<V> {
WrappedSortedSet(@Nullable K key, SortedSet<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
SortedSet<V> getSortedSetDelegate() {
return (SortedSet<V>) getDelegate();
}
@Override
public Comparator<? super V> comparator() {
return getSortedSetDelegate().comparator();
}
@Override
public V first() {
refreshIfEmpty();
return getSortedSetDelegate().first();
}
@Override
public V last() {
refreshIfEmpty();
return getSortedSetDelegate().last();
}
@Override
public SortedSet<V> headSet(V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().headSet(toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> subSet(V fromElement, V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().subSet(fromElement, toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> tailSet(V fromElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().tailSet(fromElement),
(getAncestor() == null) ? this : getAncestor());
}
}
@GwtIncompatible("NavigableSet")
class WrappedNavigableSet extends WrappedSortedSet implements NavigableSet<V> {
WrappedNavigableSet(
@Nullable K key, NavigableSet<V> delegate, @Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
@Override
NavigableSet<V> getSortedSetDelegate() {
return (NavigableSet<V>) super.getSortedSetDelegate();
}
@Override
public V lower(V v) {
return getSortedSetDelegate().lower(v);
}
@Override
public V floor(V v) {
return getSortedSetDelegate().floor(v);
}
@Override
public V ceiling(V v) {
return getSortedSetDelegate().ceiling(v);
}
@Override
public V higher(V v) {
return getSortedSetDelegate().higher(v);
}
@Override
public V pollFirst() {
return Iterators.pollNext(iterator());
}
@Override
public V pollLast() {
return Iterators.pollNext(descendingIterator());
}
private NavigableSet<V> wrap(NavigableSet<V> wrapped) {
return new WrappedNavigableSet(key, wrapped,
(getAncestor() == null) ? this : getAncestor());
}
@Override
public NavigableSet<V> descendingSet() {
return wrap(getSortedSetDelegate().descendingSet());
}
@Override
public Iterator<V> descendingIterator() {
return new WrappedIterator(getSortedSetDelegate().descendingIterator());
}
@Override
public NavigableSet<V> subSet(
V fromElement, boolean fromInclusive, V toElement, boolean toInclusive) {
return wrap(
getSortedSetDelegate().subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<V> headSet(V toElement, boolean inclusive) {
return wrap(getSortedSetDelegate().headSet(toElement, inclusive));
}
@Override
public NavigableSet<V> tailSet(V fromElement, boolean inclusive) {
return wrap(getSortedSetDelegate().tailSet(fromElement, inclusive));
}
}
/** List decorator that stays in sync with the multimap values for a key. */
private class WrappedList extends WrappedCollection implements List<V> {
WrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
List<V> getListDelegate() {
return (List<V>) getDelegate();
}
@Override
public boolean addAll(int index, Collection<? extends V> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = getListDelegate().addAll(index, c);
if (changed) {
int newSize = getDelegate().size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override
public V get(int index) {
refreshIfEmpty();
return getListDelegate().get(index);
}
@Override
public V set(int index, V element) {
refreshIfEmpty();
return getListDelegate().set(index, element);
}
@Override
public void add(int index, V element) {
refreshIfEmpty();
boolean wasEmpty = getDelegate().isEmpty();
getListDelegate().add(index, element);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
@Override
public V remove(int index) {
refreshIfEmpty();
V value = getListDelegate().remove(index);
totalSize--;
removeIfEmpty();
return value;
}
@Override
public int indexOf(Object o) {
refreshIfEmpty();
return getListDelegate().indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
refreshIfEmpty();
return getListDelegate().lastIndexOf(o);
}
@Override
public ListIterator<V> listIterator() {
refreshIfEmpty();
return new WrappedListIterator();
}
@Override
public ListIterator<V> listIterator(int index) {
refreshIfEmpty();
return new WrappedListIterator(index);
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
refreshIfEmpty();
return wrapList(getKey(),
getListDelegate().subList(fromIndex, toIndex),
(getAncestor() == null) ? this : getAncestor());
}
/** ListIterator decorator. */
private class WrappedListIterator extends WrappedIterator
implements ListIterator<V> {
WrappedListIterator() {}
public WrappedListIterator(int index) {
super(getListDelegate().listIterator(index));
}
private ListIterator<V> getDelegateListIterator() {
return (ListIterator<V>) getDelegateIterator();
}
@Override
public boolean hasPrevious() {
return getDelegateListIterator().hasPrevious();
}
@Override
public V previous() {
return getDelegateListIterator().previous();
}
@Override
public int nextIndex() {
return getDelegateListIterator().nextIndex();
}
@Override
public int previousIndex() {
return getDelegateListIterator().previousIndex();
}
@Override
public void set(V value) {
getDelegateListIterator().set(value);
}
@Override
public void add(V value) {
boolean wasEmpty = isEmpty();
getDelegateListIterator().add(value);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
}
}
/**
* List decorator that stays in sync with the multimap values for a key and
* supports rapid random access.
*/
private class RandomAccessWrappedList extends WrappedList
implements RandomAccess {
RandomAccessWrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
}
@Override
Set<K> createKeySet() {
// TreeMultimap uses NavigableKeySet explicitly, but we don't handle that here for GWT
// compatibility reasons
return (map instanceof SortedMap)
? new SortedKeySet((SortedMap<K, Collection<V>>) map) : new KeySet(map);
}
private class KeySet extends Maps.KeySet<K, Collection<V>> {
KeySet(final Map<K, Collection<V>> subMap) {
super(subMap);
}
@Override public Iterator<K> iterator() {
final Iterator<Map.Entry<K, Collection<V>>> entryIterator
= map().entrySet().iterator();
return new Iterator<K>() {
Map.Entry<K, Collection<V>> entry;
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public K next() {
entry = entryIterator.next();
return entry.getKey();
}
@Override
public void remove() {
checkRemove(entry != null);
Collection<V> collection = entry.getValue();
entryIterator.remove();
totalSize -= collection.size();
collection.clear();
}
};
}
// The following methods are included for better performance.
@Override public boolean remove(Object key) {
int count = 0;
Collection<V> collection = map().remove(key);
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count > 0;
}
@Override
public void clear() {
Iterators.clear(iterator());
}
@Override public boolean containsAll(Collection<?> c) {
return map().keySet().containsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return this == object || this.map().keySet().equals(object);
}
@Override public int hashCode() {
return map().keySet().hashCode();
}
}
private class SortedKeySet extends KeySet implements SortedSet<K> {
SortedKeySet(SortedMap<K, Collection<V>> subMap) {
super(subMap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) super.map();
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K first() {
return sortedMap().firstKey();
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet(sortedMap().headMap(toElement));
}
@Override
public K last() {
return sortedMap().lastKey();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet(sortedMap().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet(sortedMap().tailMap(fromElement));
}
}
@GwtIncompatible("NavigableSet")
class NavigableKeySet extends SortedKeySet implements NavigableSet<K> {
NavigableKeySet(NavigableMap<K, Collection<V>> subMap) {
super(subMap);
}
@Override
NavigableMap<K, Collection<V>> sortedMap() {
return (NavigableMap<K, Collection<V>>) super.sortedMap();
}
@Override
public K lower(K k) {
return sortedMap().lowerKey(k);
}
@Override
public K floor(K k) {
return sortedMap().floorKey(k);
}
@Override
public K ceiling(K k) {
return sortedMap().ceilingKey(k);
}
@Override
public K higher(K k) {
return sortedMap().higherKey(k);
}
@Override
public K pollFirst() {
return Iterators.pollNext(iterator());
}
@Override
public K pollLast() {
return Iterators.pollNext(descendingIterator());
}
@Override
public NavigableSet<K> descendingSet() {
return new NavigableKeySet(sortedMap().descendingMap());
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return new NavigableKeySet(sortedMap().headMap(toElement, inclusive));
}
@Override
public NavigableSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public NavigableSet<K> subSet(
K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return new NavigableKeySet(
sortedMap().subMap(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return new NavigableKeySet(sortedMap().tailMap(fromElement, inclusive));
}
}
/**
* Removes all values for the provided key. Unlike {@link #removeAll}, it
* returns the number of removed mappings.
*/
private int removeValuesForKey(Object key) {
Collection<V> collection = Maps.safeRemove(map, key);
int count = 0;
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count;
}
private abstract class Itr<T> implements Iterator<T> {
final Iterator<Map.Entry<K, Collection<V>>> keyIterator;
K key;
Collection<V> collection;
Iterator<V> valueIterator;
Itr() {
keyIterator = map.entrySet().iterator();
key = null;
collection = null;
valueIterator = Iterators.emptyModifiableIterator();
}
abstract T output(K key, V value);
@Override
public boolean hasNext() {
return keyIterator.hasNext() || valueIterator.hasNext();
}
@Override
public T next() {
if (!valueIterator.hasNext()) {
Map.Entry<K, Collection<V>> mapEntry = keyIterator.next();
key = mapEntry.getKey();
collection = mapEntry.getValue();
valueIterator = collection.iterator();
}
return output(key, valueIterator.next());
}
@Override
public void remove() {
valueIterator.remove();
if (collection.isEmpty()) {
keyIterator.remove();
}
totalSize--;
}
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*/
@Override public Collection<V> values() {
return super.values();
}
@Override
Iterator<V> valueIterator() {
return new Itr<V>() {
@Override
V output(K key, V value) {
return value;
}
};
}
/*
* TODO(kevinb): should we copy this javadoc to each concrete class, so that
* classes like LinkedHashMultimap that need to say something different are
* still able to {@inheritDoc} all the way from Multimap?
*/
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the
* multimap, taken at the time the entry is returned by a method call to the
* collection or its iterator.
*/
@Override
public Collection<Map.Entry<K, V>> entries() {
return super.entries();
}
/**
* Returns an iterator across all key-value map entries, used by {@code
* entries().iterator()} and {@code values().iterator()}. The default
* behavior, which traverses the values for one key, the values for a second
* key, and so on, suffices for most {@code AbstractMapBasedMultimap} implementations.
*
* @return an iterator across map entries
*/
@Override
Iterator<Map.Entry<K, V>> entryIterator() {
return new Itr<Map.Entry<K, V>>() {
@Override
Entry<K, V> output(K key, V value) {
return Maps.immutableEntry(key, value);
}
};
}
@Override
Map<K, Collection<V>> createAsMap() {
// TreeMultimap uses NavigableAsMap explicitly, but we don't handle that here for GWT
// compatibility reasons
return (map instanceof SortedMap)
? new SortedAsMap((SortedMap<K, Collection<V>>) map) : new AsMap(map);
}
private class AsMap extends ImprovedAbstractMap<K, Collection<V>> {
/**
* Usually the same as map, but smaller for the headMap(), tailMap(), or
* subMap() of a SortedAsMap.
*/
final transient Map<K, Collection<V>> submap;
AsMap(Map<K, Collection<V>> submap) {
this.submap = submap;
}
@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 Maps.safeContainsKey(submap, key);
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = Maps.safeGet(submap, key);
if (collection == null) {
return null;
}
@SuppressWarnings("unchecked")
K k = (K) key;
return wrapCollection(k, collection);
}
@Override public Set<K> keySet() {
return AbstractMapBasedMultimap.this.keySet();
}
@Override
public int size() {
return submap.size();
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = submap.remove(key);
if (collection == null) {
return null;
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return output;
}
@Override public boolean equals(@Nullable Object object) {
return this == object || submap.equals(object);
}
@Override public int hashCode() {
return submap.hashCode();
}
@Override public String toString() {
return submap.toString();
}
@Override
public void clear() {
if (submap == map) {
AbstractMapBasedMultimap.this.clear();
} else {
Iterators.clear(new AsMapIterator());
}
}
Entry<K, Collection<V>> wrapEntry(Entry<K, Collection<V>> entry) {
K key = entry.getKey();
return Maps.immutableEntry(key, wrapCollection(key, entry.getValue()));
}
class AsMapEntries extends Maps.EntrySet<K, Collection<V>> {
@Override
Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return new AsMapIterator();
}
// The following methods are included for performance.
@Override public boolean contains(Object o) {
return Collections2.safeContains(submap.entrySet(), o);
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
/** Iterator across all keys and value collections. */
class AsMapIterator implements Iterator<Map.Entry<K, Collection<V>>> {
final Iterator<Map.Entry<K, Collection<V>>> delegateIterator
= submap.entrySet().iterator();
Collection<V> collection;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public Map.Entry<K, Collection<V>> next() {
Map.Entry<K, Collection<V>> entry = delegateIterator.next();
collection = entry.getValue();
return wrapEntry(entry);
}
@Override
public void remove() {
delegateIterator.remove();
totalSize -= collection.size();
collection.clear();
}
}
}
private class SortedAsMap extends AsMap
implements SortedMap<K, Collection<V>> {
SortedAsMap(SortedMap<K, Collection<V>> submap) {
super(submap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) submap;
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K firstKey() {
return sortedMap().firstKey();
}
@Override
public K lastKey() {
return sortedMap().lastKey();
}
@Override
public SortedMap<K, Collection<V>> headMap(K toKey) {
return new SortedAsMap(sortedMap().headMap(toKey));
}
@Override
public SortedMap<K, Collection<V>> subMap(K fromKey, K toKey) {
return new SortedAsMap(sortedMap().subMap(fromKey, toKey));
}
@Override
public SortedMap<K, Collection<V>> tailMap(K fromKey) {
return new SortedAsMap(sortedMap().tailMap(fromKey));
}
SortedSet<K> sortedKeySet;
// returns a SortedSet, even though returning a Set would be sufficient to
// satisfy the SortedMap.keySet() interface
@Override public SortedSet<K> keySet() {
SortedSet<K> result = sortedKeySet;
return (result == null) ? sortedKeySet = createKeySet() : result;
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet(sortedMap());
}
}
@GwtIncompatible("NavigableAsMap")
class NavigableAsMap extends SortedAsMap implements NavigableMap<K, Collection<V>> {
NavigableAsMap(NavigableMap<K, Collection<V>> submap) {
super(submap);
}
@Override
NavigableMap<K, Collection<V>> sortedMap() {
return (NavigableMap<K, Collection<V>>) super.sortedMap();
}
@Override
public Entry<K, Collection<V>> lowerEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().lowerEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K lowerKey(K key) {
return sortedMap().lowerKey(key);
}
@Override
public Entry<K, Collection<V>> floorEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().floorEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K floorKey(K key) {
return sortedMap().floorKey(key);
}
@Override
public Entry<K, Collection<V>> ceilingEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().ceilingEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K ceilingKey(K key) {
return sortedMap().ceilingKey(key);
}
@Override
public Entry<K, Collection<V>> higherEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().higherEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K higherKey(K key) {
return sortedMap().higherKey(key);
}
@Override
public Entry<K, Collection<V>> firstEntry() {
Entry<K, Collection<V>> entry = sortedMap().firstEntry();
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public Entry<K, Collection<V>> lastEntry() {
Entry<K, Collection<V>> entry = sortedMap().lastEntry();
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public Entry<K, Collection<V>> pollFirstEntry() {
return pollAsMapEntry(entrySet().iterator());
}
@Override
public Entry<K, Collection<V>> pollLastEntry() {
return pollAsMapEntry(descendingMap().entrySet().iterator());
}
Map.Entry<K, Collection<V>> pollAsMapEntry(Iterator<Entry<K, Collection<V>>> entryIterator) {
if (!entryIterator.hasNext()) {
return null;
}
Entry<K, Collection<V>> entry = entryIterator.next();
Collection<V> output = createCollection();
output.addAll(entry.getValue());
entryIterator.remove();
return Maps.immutableEntry(entry.getKey(), unmodifiableCollectionSubclass(output));
}
@Override
public NavigableMap<K, Collection<V>> descendingMap() {
return new NavigableAsMap(sortedMap().descendingMap());
}
@Override
public NavigableSet<K> keySet() {
return (NavigableSet<K>) super.keySet();
}
@Override
NavigableSet<K> createKeySet() {
return new NavigableKeySet(sortedMap());
}
@Override
public NavigableSet<K> navigableKeySet() {
return keySet();
}
@Override
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
@Override
public NavigableMap<K, Collection<V>> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, Collection<V>> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return new NavigableAsMap(sortedMap().subMap(fromKey, fromInclusive, toKey, toInclusive));
}
@Override
public NavigableMap<K, Collection<V>> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, Collection<V>> headMap(K toKey, boolean inclusive) {
return new NavigableAsMap(sortedMap().headMap(toKey, inclusive));
}
@Override
public NavigableMap<K, Collection<V>> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, Collection<V>> tailMap(K fromKey, boolean inclusive) {
return new NavigableAsMap(sortedMap().tailMap(fromKey, inclusive));
}
}
private static final long serialVersionUID = 2447537837011683357L;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractMapBasedMultimap.java | Java | asf20 | 44,549 |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.collect.ObjectArrays.arraysCopyOf;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
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 {
private static final ImmutableList<Object> EMPTY =
new RegularImmutableList<Object>(ObjectArrays.EMPTY_ARRAY);
/**
* 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>) EMPTY;
}
/**
* 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()
? ImmutableList.<E>asImmutableList(list.toArray())
: list;
}
return construct(elements.toArray());
}
/**
* 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) {
// We special-case for 0 or 1 elements, but going further is madness.
if (!elements.hasNext()) {
return of();
}
E first = elements.next();
if (!elements.hasNext()) {
return of(first);
} else {
return new ImmutableList.Builder<E>()
.add(first)
.addAll(elements)
.build();
}
}
/**
* 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 new RegularImmutableList<E>(checkElementsNotNull(elements.clone()));
}
}
/**
* Views the array as an immutable list. Checks for nulls; does not copy.
*/
private static <E> ImmutableList<E> construct(Object... elements) {
return asImmutableList(checkElementsNotNull(elements));
}
/**
* Views the array as an immutable list. Does not check for nulls; does not copy.
*
* <p>The array must be internally created.
*/
static <E> ImmutableList<E> asImmutableList(Object[] elements) {
return asImmutableList(elements, elements.length);
}
/**
* Views the array as an immutable list. Copies if the specified range does not cover the complete
* array. Does not check for nulls.
*/
static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) {
switch (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:
if (length < elements.length) {
elements = arraysCopyOf(elements, length);
}
return new RegularImmutableList<E>(elements);
}
}
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 UnmodifiableListIterator<E> listIterator(int index) {
return new AbstractIndexedListIterator<E>(size(), index) {
@Override
protected E get(int index) {
return ImmutableList.this.get(index);
}
};
}
@Override
public int indexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.indexOfImpl(this, object);
}
@Override
public int lastIndexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
}
@Override
public boolean contains(@Nullable Object object) {
return indexOf(object) >= 0;
}
// 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 ImmutableList<E> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
int length = toIndex - fromIndex;
switch (length) {
case 0:
return of();
case 1:
return of(get(fromIndex));
default:
return subListUnchecked(fromIndex, toIndex);
}
}
/**
* Called by the default implementation of {@link #subList} when {@code
* toIndex - fromIndex > 1}, after index validation has already been
* performed.
*/
ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
return new SubList(fromIndex, toIndex - fromIndex);
}
class SubList extends ImmutableList<E> {
transient final int offset;
transient final int length;
SubList(int offset, int length) {
this.offset = offset;
this.length = length;
}
@Override
public int size() {
return length;
}
@Override
public E get(int index) {
checkElementIndex(index, length);
return ImmutableList.this.get(index + offset);
}
@Override
public ImmutableList<E> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, length);
return ImmutableList.this.subList(fromIndex + offset, toIndex + offset);
}
@Override
boolean isPartialView() {
return true;
}
}
/**
* Guaranteed to throw an exception and leave the list unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@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
* @deprecated Unsupported operation.
*/
@Deprecated
@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
* @deprecated Unsupported operation.
*/
@Deprecated
@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
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final E remove(int index) {
throw new UnsupportedOperationException();
}
/**
* Returns this list instance.
*
* @since 2.0
*/
@Override public final ImmutableList<E> asList() {
return this;
}
@Override
int copyIntoArray(Object[] dst, int offset) {
// this loop is faster for RandomAccess instances, which ImmutableLists are
int size = size();
for (int i = 0; i < size; i++) {
dst[offset + i] = get(i);
}
return offset + size;
}
/**
* 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 final transient ImmutableList<E> forwardList;
ReverseImmutableList(ImmutableList<E> backingList) {
this.forwardList = backingList;
}
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 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) {
checkPositionIndexes(fromIndex, toIndex, size());
return forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)).reverse();
}
@Override public E get(int index) {
checkElementIndex(index, size());
return forwardList.get(reverseIndex(index));
}
@Override public int size() {
return forwardList.size();
}
@Override boolean isPartialView() {
return forwardList.isPartialView();
}
}
@Override public boolean equals(@Nullable Object obj) {
return Lists.equalsImpl(this, obj);
}
@Override public int hashCode() {
int hashCode = 1;
int n = size();
for (int i = 0; i < n; i++) {
hashCode = 31 * hashCode + get(i).hashCode();
hashCode = ~~hashCode;
// needed to deal with GWT integer overflow
}
return hashCode;
}
/*
* Serializes ImmutableLists as their logical contents. This ensures that
* implementation types do not leak into the serialized representation.
*/
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>
*
* <p>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.ArrayBasedBuilder<E> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableList#builder}.
*/
public Builder() {
this(DEFAULT_INITIAL_CAPACITY);
}
// TODO(user): consider exposing this
Builder(int capacity) {
super(capacity);
}
/**
* 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) {
super.add(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) {
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) {
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 asImmutableList(contents, size);
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableList.java | Java | asf20 | 21,797 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Predicate;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of {@link Multimaps#filterKeys(Multimap, Predicate)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
class FilteredKeyMultimap<K, V> extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> {
final Multimap<K, V> unfiltered;
final Predicate<? super K> keyPredicate;
FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
this.unfiltered = checkNotNull(unfiltered);
this.keyPredicate = checkNotNull(keyPredicate);
}
@Override
public Multimap<K, V> unfiltered() {
return unfiltered;
}
@Override
public Predicate<? super Entry<K, V>> entryPredicate() {
return Maps.keyPredicateOnEntries(keyPredicate);
}
@Override
public int size() {
int size = 0;
for (Collection<V> collection : asMap().values()) {
size += collection.size();
}
return size;
}
@Override
public boolean containsKey(@Nullable Object key) {
if (unfiltered.containsKey(key)) {
@SuppressWarnings("unchecked") // k is equal to a K, if not one itself
K k = (K) key;
return keyPredicate.apply(k);
}
return false;
}
@Override
public Collection<V> removeAll(Object key) {
return containsKey(key) ? unfiltered.removeAll(key) : unmodifiableEmptyCollection();
}
Collection<V> unmodifiableEmptyCollection() {
if (unfiltered instanceof SetMultimap) {
return ImmutableSet.of();
} else {
return ImmutableList.of();
}
}
@Override
public void clear() {
keySet().clear();
}
@Override
Set<K> createKeySet() {
return Sets.filter(unfiltered.keySet(), keyPredicate);
}
@Override
public Collection<V> get(K key) {
if (keyPredicate.apply(key)) {
return unfiltered.get(key);
} else if (unfiltered instanceof SetMultimap) {
return new AddRejectingSet<K, V>(key);
} else {
return new AddRejectingList<K, V>(key);
}
}
static class AddRejectingSet<K, V> extends ForwardingSet<V> {
final K key;
AddRejectingSet(K key) {
this.key = key;
}
@Override
public boolean add(V element) {
throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
}
@Override
public boolean addAll(Collection<? extends V> collection) {
checkNotNull(collection);
throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
}
@Override
protected Set<V> delegate() {
return Collections.emptySet();
}
}
static class AddRejectingList<K, V> extends ForwardingList<V> {
final K key;
AddRejectingList(K key) {
this.key = key;
}
@Override
public boolean add(V v) {
add(0, v);
return true;
}
@Override
public boolean addAll(Collection<? extends V> collection) {
addAll(0, collection);
return true;
}
@Override
public void add(int index, V element) {
checkPositionIndex(index, 0);
throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
}
@Override
public boolean addAll(int index, Collection<? extends V> elements) {
checkNotNull(elements);
checkPositionIndex(index, 0);
throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
}
@Override
protected List<V> delegate() {
return Collections.emptyList();
}
}
@Override
Iterator<Entry<K, V>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
Collection<Entry<K, V>> createEntries() {
return new Entries();
}
class Entries extends ForwardingCollection<Entry<K, V>> {
@Override
protected Collection<Entry<K, V>> delegate() {
return Collections2.filter(unfiltered.entries(), entryPredicate());
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(@Nullable Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
if (unfiltered.containsKey(entry.getKey())
// if this holds, then we know entry.getKey() is a K
&& keyPredicate.apply((K) entry.getKey())) {
return unfiltered.remove(entry.getKey(), entry.getValue());
}
}
return false;
}
}
@Override
Collection<V> createValues() {
return new FilteredMultimapValues<K, V>(this);
}
@Override
Map<K, Collection<V>> createAsMap() {
return Maps.filterKeys(unfiltered.asMap(), keyPredicate);
}
@Override
Multiset<K> createKeys() {
return Multisets.filter(unfiltered.keys(), keyPredicate);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/FilteredKeyMultimap.java | Java | asf20 | 5,675 |
/*
* 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.io.Serializable;
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> implements Serializable {
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;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/MapConstraints.java | Java | asf20 | 27,282 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.SortedSet;
/**
* Superinterface of {@link SortedMultiset} to introduce a bridge method for
* {@code elementSet()}, to ensure binary compatibility with older Guava versions
* that specified {@code elementSet()} to return {@code SortedSet}.
*
* @author Louis Wasserman
*/
interface SortedMultisetBridge<E> extends Multiset<E> {
@Override
SortedSet<E> elementSet();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SortedMultisetBridge.java | Java | asf20 | 1,032 |
/*
* 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;
/**
* "Overrides" the {@link ImmutableSet} static methods that lack
* {@link ImmutableSortedSet} equivalents with deprecated, exception-throwing
* versions. This prevents accidents like the following: <pre> {@code
*
* List<Object> objects = ...;
* // Sort them:
* Set<Object> sorted = ImmutableSortedSet.copyOf(objects);
* // BAD CODE! The returned set is actually an unsorted ImmutableSet!}</pre>
*
* <p>While we could put the overrides in {@link ImmutableSortedSet} itself, it
* seems clearer to separate these "do not call" methods from those intended for
* normal use.
*
* @author Chris Povirk
*/
abstract class ImmutableSortedSetFauxverideShim<E> extends ImmutableSet<E> {
/**
* Not supported. Use {@link ImmutableSortedSet#naturalOrder}, which offers
* better type-safety, instead. This method exists only to hide
* {@link ImmutableSet#builder} from consumers of {@code ImmutableSortedSet}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedSet#naturalOrder}, which offers
* better type-safety.
*/
@Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass a parameter of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable)}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(E element) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable)}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(E e1, E e2) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable)}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable)}.
* </b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(
* Comparable, Comparable, Comparable, Comparable, Comparable)}. </b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable,
* Comparable, Comparable, Comparable...)}. </b>
*/
@Deprecated public static <E> ImmutableSortedSet<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 set that may contain
* non-{@code Comparable} elements.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#copyOf(Comparable[])}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<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 ImmutableSortedSet (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 ImmutableSortedSet matches that in ImmutableSet.
*
* The result is that ImmutableSortedSet.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 ImmutableSortedSet wouldn't "inherit" too-permissive factory
* methods from ImmutableSet.
*/
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSortedSetFauxverideShim.java | Java | asf20 | 6,997 |
/*
* 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.collect.CollectPreconditions.checkEntryNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMapEntry.TerminalEntry;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* Bimap with two or more mappings.
*
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
static final double MAX_LOAD_FACTOR = 1.2;
private final transient ImmutableMapEntry<K, V>[] keyTable;
private final transient ImmutableMapEntry<K, V>[] valueTable;
private final transient ImmutableMapEntry<K, V>[] entries;
private final transient int mask;
private final transient int hashCode;
RegularImmutableBiMap(TerminalEntry<?, ?>... entriesToAdd) {
this(entriesToAdd.length, entriesToAdd);
}
/**
* Constructor for RegularImmutableBiMap that takes as input an array of {@code TerminalEntry}
* entries. Assumes that these entries have already been checked for null.
*
* <p>This allows reuse of the entry objects from the array in the actual implementation.
*/
RegularImmutableBiMap(int n, TerminalEntry<?, ?>[] entriesToAdd) {
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
this.mask = tableSize - 1;
ImmutableMapEntry<K, V>[] keyTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] valueTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] entries = createEntryArray(n);
int hashCode = 0;
for (int i = 0; i < n; i++) {
@SuppressWarnings("unchecked")
TerminalEntry<K, V> entry = (TerminalEntry<K, V>) entriesToAdd[i];
K key = entry.getKey();
V value = entry.getValue();
int keyHash = key.hashCode();
int valueHash = value.hashCode();
int keyBucket = Hashing.smear(keyHash) & mask;
int valueBucket = Hashing.smear(valueHash) & mask;
ImmutableMapEntry<K, V> nextInKeyBucket = keyTable[keyBucket];
for (ImmutableMapEntry<K, V> keyEntry = nextInKeyBucket; keyEntry != null;
keyEntry = keyEntry.getNextInKeyBucket()) {
checkNoConflict(!key.equals(keyEntry.getKey()), "key", entry, keyEntry);
}
ImmutableMapEntry<K, V> nextInValueBucket = valueTable[valueBucket];
for (ImmutableMapEntry<K, V> valueEntry = nextInValueBucket; valueEntry != null;
valueEntry = valueEntry.getNextInValueBucket()) {
checkNoConflict(!value.equals(valueEntry.getValue()), "value", entry, valueEntry);
}
ImmutableMapEntry<K, V> newEntry =
(nextInKeyBucket == null && nextInValueBucket == null)
? entry
: new NonTerminalBiMapEntry<K, V>(entry, nextInKeyBucket, nextInValueBucket);
keyTable[keyBucket] = newEntry;
valueTable[valueBucket] = newEntry;
entries[i] = newEntry;
hashCode += keyHash ^ valueHash;
}
this.keyTable = keyTable;
this.valueTable = valueTable;
this.entries = entries;
this.hashCode = hashCode;
}
/**
* Constructor for RegularImmutableBiMap that makes no assumptions about the input entries.
*/
RegularImmutableBiMap(Entry<?, ?>[] entriesToAdd) {
int n = entriesToAdd.length;
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
this.mask = tableSize - 1;
ImmutableMapEntry<K, V>[] keyTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] valueTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] entries = createEntryArray(n);
int hashCode = 0;
for (int i = 0; i < n; i++) {
@SuppressWarnings("unchecked")
Entry<K, V> entry = (Entry<K, V>) entriesToAdd[i];
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int keyHash = key.hashCode();
int valueHash = value.hashCode();
int keyBucket = Hashing.smear(keyHash) & mask;
int valueBucket = Hashing.smear(valueHash) & mask;
ImmutableMapEntry<K, V> nextInKeyBucket = keyTable[keyBucket];
for (ImmutableMapEntry<K, V> keyEntry = nextInKeyBucket; keyEntry != null;
keyEntry = keyEntry.getNextInKeyBucket()) {
checkNoConflict(!key.equals(keyEntry.getKey()), "key", entry, keyEntry);
}
ImmutableMapEntry<K, V> nextInValueBucket = valueTable[valueBucket];
for (ImmutableMapEntry<K, V> valueEntry = nextInValueBucket; valueEntry != null;
valueEntry = valueEntry.getNextInValueBucket()) {
checkNoConflict(!value.equals(valueEntry.getValue()), "value", entry, valueEntry);
}
ImmutableMapEntry<K, V> newEntry =
(nextInKeyBucket == null && nextInValueBucket == null)
? new TerminalEntry<K, V>(key, value)
: new NonTerminalBiMapEntry<K, V>(key, value, nextInKeyBucket, nextInValueBucket);
keyTable[keyBucket] = newEntry;
valueTable[valueBucket] = newEntry;
entries[i] = newEntry;
hashCode += keyHash ^ valueHash;
}
this.keyTable = keyTable;
this.valueTable = valueTable;
this.entries = entries;
this.hashCode = hashCode;
}
private static final class NonTerminalBiMapEntry<K, V> extends ImmutableMapEntry<K, V> {
@Nullable private final ImmutableMapEntry<K, V> nextInKeyBucket;
@Nullable private final ImmutableMapEntry<K, V> nextInValueBucket;
NonTerminalBiMapEntry(K key, V value, @Nullable ImmutableMapEntry<K, V> nextInKeyBucket,
@Nullable ImmutableMapEntry<K, V> nextInValueBucket) {
super(key, value);
this.nextInKeyBucket = nextInKeyBucket;
this.nextInValueBucket = nextInValueBucket;
}
NonTerminalBiMapEntry(ImmutableMapEntry<K, V> contents,
@Nullable ImmutableMapEntry<K, V> nextInKeyBucket,
@Nullable ImmutableMapEntry<K, V> nextInValueBucket) {
super(contents);
this.nextInKeyBucket = nextInKeyBucket;
this.nextInValueBucket = nextInValueBucket;
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInKeyBucket() {
return nextInKeyBucket;
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInValueBucket() {
return nextInValueBucket;
}
}
@SuppressWarnings("unchecked")
private static <K, V> ImmutableMapEntry<K, V>[] createEntryArray(int length) {
return new ImmutableMapEntry[length];
}
@Override
@Nullable
public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int bucket = Hashing.smear(key.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = keyTable[bucket]; entry != null;
entry = entry.getNextInKeyBucket()) {
if (key.equals(entry.getKey())) {
return entry.getValue();
}
}
return null;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet<K, V>() {
@Override
ImmutableMap<K, V> map() {
return RegularImmutableBiMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<K, V>> createAsList() {
return new RegularImmutableAsList<Entry<K, V>>(this, entries);
}
@Override
boolean isHashCodeFast() {
return true;
}
@Override
public int hashCode() {
return hashCode;
}
};
}
@Override
boolean isPartialView() {
return false;
}
@Override
public int size() {
return entries.length;
}
private transient ImmutableBiMap<V, K> inverse;
@Override
public ImmutableBiMap<V, K> inverse() {
ImmutableBiMap<V, K> result = inverse;
return (result == null) ? inverse = new Inverse() : result;
}
private final class Inverse extends ImmutableBiMap<V, K> {
@Override
public int size() {
return inverse().size();
}
@Override
public ImmutableBiMap<K, V> inverse() {
return RegularImmutableBiMap.this;
}
@Override
public K get(@Nullable Object value) {
if (value == null) {
return null;
}
int bucket = Hashing.smear(value.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = valueTable[bucket]; entry != null;
entry = entry.getNextInValueBucket()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
ImmutableSet<Entry<V, K>> createEntrySet() {
return new InverseEntrySet();
}
final class InverseEntrySet extends ImmutableMapEntrySet<V, K> {
@Override
ImmutableMap<V, K> map() {
return Inverse.this;
}
@Override
boolean isHashCodeFast() {
return true;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public UnmodifiableIterator<Entry<V, K>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<V, K>> createAsList() {
return new ImmutableAsList<Entry<V, K>>() {
@Override
public Entry<V, K> get(int index) {
Entry<K, V> entry = entries[index];
return Maps.immutableEntry(entry.getValue(), entry.getKey());
}
@Override
ImmutableCollection<Entry<V, K>> delegateCollection() {
return InverseEntrySet.this;
}
};
}
}
@Override
boolean isPartialView() {
return false;
}
@Override
Object writeReplace() {
return new InverseSerializedForm<K, V>(RegularImmutableBiMap.this);
}
}
private static class InverseSerializedForm<K, V> implements Serializable {
private final ImmutableBiMap<K, V> forward;
InverseSerializedForm(ImmutableBiMap<K, V> forward) {
this.forward = forward;
}
Object readResolve() {
return forward.inverse();
}
private static final long serialVersionUID = 1;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/RegularImmutableBiMap.java | Java | asf20 | 10,780 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code entrySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
ImmutableMapEntrySet() {}
abstract ImmutableMap<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public boolean contains(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
V value = map().get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
return false;
}
@Override
boolean isPartialView() {
return map().isPartialView();
}
@GwtIncompatible("serialization")
@Override
Object writeReplace() {
return new EntrySetSerializedForm<K, V>(map());
}
@GwtIncompatible("serialization")
private static class EntrySetSerializedForm<K, V> implements Serializable {
final ImmutableMap<K, V> map;
EntrySetSerializedForm(ImmutableMap<K, V> map) {
this.map = map;
}
Object readResolve() {
return map.entrySet();
}
private static final long serialVersionUID = 0;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableMapEntrySet.java | Java | asf20 | 2,047 |
/*
* 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.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.Set;
/**
* A {@link Multiset} which maintains the ordering of its elements, according to
* either their natural order or an explicit {@link Comparator}. This order is
* reflected when iterating over the sorted multiset, either directly, or through
* its {@code elementSet} or {@code entrySet} views. 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 Collection} contract, which it 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
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public interface SortedMultiset<E> extends SortedMultisetBridge<E>, SortedIterable<E> {
/**
* Returns the comparator that orders this multiset, or
* {@link Ordering#natural()} if the natural ordering of the elements is used.
*/
Comparator<? super E> comparator();
/**
* Returns the entry of the first element in this multiset, or {@code null} if
* this multiset is empty.
*/
Entry<E> firstEntry();
/**
* Returns the entry of the last element in this multiset, or {@code null} if
* this multiset is empty.
*/
Entry<E> lastEntry();
/**
* Returns and removes the entry associated with the lowest element in this
* multiset, or returns {@code null} if this multiset is empty.
*/
Entry<E> pollFirstEntry();
/**
* Returns and removes the entry associated with the greatest element in this
* multiset, or returns {@code null} if this multiset is empty.
*/
Entry<E> pollLastEntry();
/**
* Returns a {@link NavigableSet} view of the distinct elements in this multiset.
*
* @since 14.0 (present with return type {@code SortedSet} since 11.0)
*/
@Override NavigableSet<E> elementSet();
/**
* {@inheritDoc}
*
* <p>The {@code entrySet}'s iterator returns entries in ascending element
* order according to the this multiset's comparator.
*/
@Override Set<Entry<E>> entrySet();
/**
* {@inheritDoc}
*
* <p>The iterator returns the elements in ascending order according to this
* multiset's comparator.
*/
@Override Iterator<E> iterator();
/**
* Returns a descending view of this multiset. Modifications made to either
* map will be reflected in the other.
*/
SortedMultiset<E> descendingMultiset();
/**
* Returns a view of this multiset restricted to the elements less than
* {@code upperBound}, optionally including {@code upperBound} itself. The
* returned multiset is a view of this multiset, so changes to one will be
* reflected in the other. The returned multiset supports all operations that
* this multiset supports.
*
* <p>The returned multiset will throw an {@link IllegalArgumentException} on
* attempts to add elements outside its range.
*/
SortedMultiset<E> headMultiset(E upperBound, BoundType boundType);
/**
* Returns a view of this multiset restricted to the range between
* {@code lowerBound} and {@code upperBound}. The returned multiset is a view
* of this multiset, so changes to one will be reflected in the other. The
* returned multiset supports all operations that this multiset supports.
*
* <p>The returned multiset will throw an {@link IllegalArgumentException} on
* attempts to add elements outside its range.
*
* <p>This method is equivalent to
* {@code tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound,
* upperBoundType)}.
*/
SortedMultiset<E> subMultiset(E lowerBound, BoundType lowerBoundType,
E upperBound, BoundType upperBoundType);
/**
* Returns a view of this multiset restricted to the elements greater than
* {@code lowerBound}, optionally including {@code lowerBound} itself. The
* returned multiset is a view of this multiset, so changes to one will be
* reflected in the other. The returned multiset supports all operations that
* this multiset supports.
*
* <p>The returned multiset will throw an {@link IllegalArgumentException} on
* attempts to add elements outside its range.
*/
SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType);
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SortedMultiset.java | Java | asf20 | 5,449 |
/*
* 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ReverseNaturalOrdering.java | Java | asf20 | 2,876 |
/*
* 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.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.
*
* @author Mike Bostock
* @author Jared Levy
*/
@GwtCompatible
final class Constraints {
private Constraints() {}
/**
* 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);
}
}
/*
* 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;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Constraints.java | Java | asf20 | 10,962 |
/*
* 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.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link List} instances. Also see this
* class's counterparts {@link Sets}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists">
* {@code Lists}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Lists {
private Lists() {}
// ArrayList
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableList#of()} instead.
*
* @return a new, empty {@code ArrayList}
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableList#of()} (for varargs) or
* {@link ImmutableList#copyOf(Object[])} (for an array) instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements); // for GWT
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@VisibleForTesting static int computeArrayListCapacity(int arraySize) {
checkNonnegative(arraySize, "arraySize");
// TODO(kevinb): Figure out the right behavior, and document it
return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
ArrayList<E> list = newArrayList();
Iterators.addAll(list, elements);
return list;
}
/**
* Creates an {@code ArrayList} instance backed by an array of the
* <i>exact</i> size specified; equivalent to
* {@link ArrayList#ArrayList(int)}.
*
* <p><b>Note:</b> if you know the exact size your list will be, consider
* using a fixed-size list ({@link Arrays#asList(Object[])}) or an {@link
* ImmutableList} instead of a growable {@link ArrayList}.
*
* <p><b>Note:</b> If you have only an <i>estimate</i> of the eventual size of
* the list, consider padding this estimate by a suitable amount, or simply
* use {@link #newArrayListWithExpectedSize(int)} instead.
*
* @param initialArraySize the exact size of the initial backing array for
* the returned array list ({@code ArrayList} documentation calls this
* value the "capacity")
* @return a new, empty {@code ArrayList} which is guaranteed not to resize
* itself unless its size reaches {@code initialArraySize + 1}
* @throws IllegalArgumentException if {@code initialArraySize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithCapacity(
int initialArraySize) {
checkNonnegative(initialArraySize, "initialArraySize"); // for GWT.
return new ArrayList<E>(initialArraySize);
}
/**
* Creates an {@code ArrayList} instance sized appropriately to hold an
* <i>estimated</i> number of elements without resizing. A small amount of
* padding is added in case the estimate is low.
*
* <p><b>Note:</b> If you know the <i>exact</i> number of elements the list
* will hold, or prefer to calculate your own amount of padding, refer to
* {@link #newArrayListWithCapacity(int)}.
*
* @param estimatedSize an estimate of the eventual {@link List#size()} of
* the new list
* @return a new, empty {@code ArrayList}, sized appropriately to hold the
* estimated number of elements
* @throws IllegalArgumentException if {@code estimatedSize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithExpectedSize(
int estimatedSize) {
return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
}
// LinkedList
/**
* Creates an empty {@code LinkedList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use
* {@link ImmutableList#of()} instead.
*
* @return a new, empty {@code LinkedList}
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList() {
return new LinkedList<E>();
}
/**
* Creates a {@code LinkedList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code LinkedList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList(
Iterable<? extends E> elements) {
LinkedList<E> list = newLinkedList();
Iterables.addAll(list, elements);
return list;
}
/**
* Creates an empty {@code CopyOnWriteArrayList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use
* {@link Collections#emptyList} instead.
*
* @return a new, empty {@code CopyOnWriteArrayList}
* @since 12.0
*/
@GwtIncompatible("CopyOnWriteArrayList")
public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
return new CopyOnWriteArrayList<E>();
}
/**
* Creates a {@code CopyOnWriteArrayList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code CopyOnWriteArrayList} containing those elements
* @since 12.0
*/
@GwtIncompatible("CopyOnWriteArrayList")
public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
Iterable<? extends E> elements) {
// We copy elements to an ArrayList first, rather than incurring the
// quadratic cost of adding them to the COWAL directly.
Collection<? extends E> elementsCollection = (elements instanceof Collection)
? Collections2.cast(elements)
: newArrayList(elements);
return new CopyOnWriteArrayList<E>(elementsCollection);
}
/**
* Returns an unmodifiable list containing the specified first element and
* backed by the specified array of additional elements. Changes to the {@code
* rest} array will be reflected in the returned list. Unlike {@link
* Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload
* ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(@Nullable E first, E[] rest) {
return new OnePlusArrayList<E>(first, rest);
}
/** @see Lists#asList(Object, Object[]) */
private static class OnePlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E[] rest;
OnePlusArrayList(@Nullable E first, E[] rest) {
this.first = first;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 1;
}
@Override public E get(int index) {
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return (index == 0) ? first : rest[index - 1];
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable list containing the specified first and second
* element, and backed by the specified array of additional elements. Changes
* to the {@code rest} array will be reflected in the returned list. Unlike
* {@link Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid
* overload ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param second the second element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(
@Nullable E first, @Nullable E second, E[] rest) {
return new TwoPlusArrayList<E>(first, second, rest);
}
/** @see Lists#asList(Object, Object, Object[]) */
private static class TwoPlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E second;
final E[] rest;
TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
this.first = first;
this.second = second;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 2;
}
@Override public E get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return rest[index - 2];
}
}
private static final long serialVersionUID = 0;
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given lists in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example: <pre> {@code
*
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))}</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be
* empty. If no lists at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size
* {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian product is constructed, the
* input lists are merely copied. Only as the resulting list is iterated are
* the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that
* the elements chosen from those lists should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable list containing immutable
* lists
* @throws IllegalArgumentException if the size of the cartesian product would
* be greater than {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the {@code lists},
* or any element of a provided list is null
*/ static <B> List<List<B>>
cartesianProduct(List<? extends List<? extends B>> lists) {
return CartesianList.create(lists);
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given lists in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example: <pre> {@code
*
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))}</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be
* empty. If no lists at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size
* {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian product is constructed, the
* input lists are merely copied. Only as the resulting list is iterated are
* the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that
* the elements chosen from those lists should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable list containing immutable
* lists
* @throws IllegalArgumentException if the size of the cartesian product would
* be greater than {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the
* {@code lists}, or any element of a provided list is null
*/ static <B> List<List<B>>
cartesianProduct(List<? extends B>... lists) {
return cartesianProduct(Arrays.asList(lists));
}
/**
* Returns a list that applies {@code function} to each element of {@code
* fromList}. The returned list is a transformed view of {@code fromList};
* changes to {@code fromList} will be reflected in the returned list and vice
* versa.
*
* <p>Since functions are not reversible, the transform is one-way and new
* items cannot be stored in the returned list. The {@code add},
* {@code addAll} and {@code set} methods are unsupported in the returned
* list.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned list to be a view, but it means that the function will be
* applied many times for bulk operations like {@link List#contains} and
* {@link List#hashCode}. For this to perform well, {@code function} should be
* fast. To avoid lazy evaluation when the returned list doesn't need to be a
* view, copy the returned list into a new list of your choosing.
*
* <p>If {@code fromList} implements {@link RandomAccess}, so will the
* returned list. The returned list is threadsafe if the supplied list and
* function are.
*
* <p>If only a {@code Collection} or {@code Iterable} input is available, use
* {@link Collections2#transform} or {@link Iterables#transform}.
*
* <p><b>Note:</b> serializing the returned list is implemented by serializing
* {@code fromList}, its contents, and {@code function} -- <i>not</i> by
* serializing the transformed values. This can lead to surprising behavior,
* so serializing the returned list is <b>not recommended</b>. Instead,
* copy the list using {@link ImmutableList#copyOf(Collection)} (for example),
* then serialize the copy. Other methods similar to this do not implement
* serialization at all for this reason.
*/
public static <F, T> List<T> transform(
List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<F, T>(fromList, function)
: new TransformingSequentialList<F, T>(fromList, function);
}
/**
* Implementation of a sequential transforming list.
*
* @see Lists#transform
*/
private static class TransformingSequentialList<F, T>
extends AbstractSequentialList<T> implements Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingSequentialList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
/**
* The default implementation inherited is based on iteration and removal of
* each element which can be overkill. That's why we forward this call
* directly to the backing list.
*/
@Override public void clear() {
fromList.clear();
}
@Override public int size() {
return fromList.size();
}
@Override public ListIterator<T> listIterator(final int index) {
return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
private static final long serialVersionUID = 0;
}
/**
* Implementation of a transforming random access list. We try to make as many
* of these methods pass-through to the source list as possible so that the
* performance characteristics of the source list and transformed list are
* similar.
*
* @see Lists#transform
*/
private static class TransformingRandomAccessList<F, T>
extends AbstractList<T> implements RandomAccess, Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingRandomAccessList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
@Override public void clear() {
fromList.clear();
}
@Override public T get(int index) {
return function.apply(fromList.get(index));
}
@Override public Iterator<T> iterator() {
return listIterator();
}
@Override public ListIterator<T> listIterator(int index) {
return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
@Override public boolean isEmpty() {
return fromList.isEmpty();
}
@Override public T remove(int index) {
return function.apply(fromList.remove(index));
}
@Override public int size() {
return fromList.size();
}
private static final long serialVersionUID = 0;
}
/**
* Returns consecutive {@linkplain List#subList(int, int) sublists} of a list,
* each of the same size (the final list may be smaller). For example,
* partitioning a list containing {@code [a, b, c, d, e]} with a partition
* size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
* two inner lists of three and two elements, all in the original order.
*
* <p>The outer list is unmodifiable, but reflects the latest state of the
* source list. The inner lists are sublist views of the original list,
* produced on demand using {@link List#subList(int, int)}, and are subject
* to all the usual caveats about modification as explained in that API.
*
* @param list the list to return consecutive sublists of
* @param size the desired size of each sublist (the last may be
* smaller)
* @return a list of consecutive sublists
* @throws IllegalArgumentException if {@code partitionSize} is nonpositive
*/
public static <T> List<List<T>> partition(List<T> list, int size) {
checkNotNull(list);
checkArgument(size > 0);
return (list instanceof RandomAccess)
? new RandomAccessPartition<T>(list, size)
: new Partition<T>(list, size);
}
private static class Partition<T> extends AbstractList<List<T>> {
final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
@Override public List<T> get(int index) {
checkElementIndex(index, size());
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override public int size() {
return IntMath.divide(list.size(), size, RoundingMode.CEILING);
}
@Override public boolean isEmpty() {
return list.isEmpty();
}
}
private static class RandomAccessPartition<T> extends Partition<T>
implements RandomAccess {
RandomAccessPartition(List<T> list, int size) {
super(list, size);
}
}
/**
* Returns a view of the specified string as an immutable list of {@code
* Character} values.
*
* @since 7.0
*/
@Beta public static ImmutableList<Character> charactersOf(String string) {
return new StringAsImmutableList(checkNotNull(string));
}
@SuppressWarnings("serial") // serialized using ImmutableList serialization
private static final class StringAsImmutableList
extends ImmutableList<Character> {
private final String string;
StringAsImmutableList(String string) {
this.string = string;
}
@Override public int indexOf(@Nullable Object object) {
return (object instanceof Character)
? string.indexOf((Character) object) : -1;
}
@Override public int lastIndexOf(@Nullable Object object) {
return (object instanceof Character)
? string.lastIndexOf((Character) object) : -1;
}
@Override public ImmutableList<Character> subList(
int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(string.substring(fromIndex, toIndex));
}
@Override boolean isPartialView() {
return false;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return string.charAt(index);
}
@Override public int size() {
return string.length();
}
}
/**
* Returns a view of the specified {@code CharSequence} as a {@code
* List<Character>}, viewing {@code sequence} as a sequence of Unicode code
* units. The view does not support any modification operations, but reflects
* any changes to the underlying character sequence.
*
* @param sequence the character sequence to view as a {@code List} of
* characters
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
@Beta public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
private static final class CharSequenceAsList
extends AbstractList<Character> {
private final CharSequence sequence;
CharSequenceAsList(CharSequence sequence) {
this.sequence = sequence;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return sequence.charAt(index);
}
@Override public int size() {
return sequence.length();
}
}
/**
* Returns a reversed view of the specified list. For example, {@code
* Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
* 2, 1}. The returned list is backed by this list, so changes in the returned
* list are reflected in this list, and vice-versa. The returned list supports
* all of the optional list operations supported by this list.
*
* <p>The returned list is random-access if the specified list is random
* access.
*
* @since 7.0
*/
public static <T> List<T> reverse(List<T> list) {
if (list instanceof ImmutableList) {
return ((ImmutableList<T>) list).reverse();
} else if (list instanceof ReverseList) {
return ((ReverseList<T>) list).getForwardList();
} else if (list instanceof RandomAccess) {
return new RandomAccessReverseList<T>(list);
} else {
return new ReverseList<T>(list);
}
}
private static class ReverseList<T> extends AbstractList<T> {
private final List<T> forwardList;
ReverseList(List<T> forwardList) {
this.forwardList = checkNotNull(forwardList);
}
List<T> getForwardList() {
return forwardList;
}
private int reverseIndex(int index) {
int size = size();
checkElementIndex(index, size);
return (size - 1) - index;
}
private int reversePosition(int index) {
int size = size();
checkPositionIndex(index, size);
return size - index;
}
@Override public void add(int index, @Nullable T element) {
forwardList.add(reversePosition(index), element);
}
@Override public void clear() {
forwardList.clear();
}
@Override public T remove(int index) {
return forwardList.remove(reverseIndex(index));
}
@Override protected void removeRange(int fromIndex, int toIndex) {
subList(fromIndex, toIndex).clear();
}
@Override public T set(int index, @Nullable T element) {
return forwardList.set(reverseIndex(index), element);
}
@Override public T get(int index) {
return forwardList.get(reverseIndex(index));
}
@Override public int size() {
return forwardList.size();
}
@Override public List<T> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
return reverse(forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)));
}
@Override public Iterator<T> iterator() {
return listIterator();
}
@Override public ListIterator<T> listIterator(int index) {
int start = reversePosition(index);
final ListIterator<T> forwardIterator = forwardList.listIterator(start);
return new ListIterator<T>() {
boolean canRemoveOrSet;
@Override public void add(T e) {
forwardIterator.add(e);
forwardIterator.previous();
canRemoveOrSet = false;
}
@Override public boolean hasNext() {
return forwardIterator.hasPrevious();
}
@Override public boolean hasPrevious() {
return forwardIterator.hasNext();
}
@Override public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.previous();
}
@Override public int nextIndex() {
return reversePosition(forwardIterator.nextIndex());
}
@Override public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.next();
}
@Override public int previousIndex() {
return nextIndex() - 1;
}
@Override public void remove() {
checkRemove(canRemoveOrSet);
forwardIterator.remove();
canRemoveOrSet = false;
}
@Override public void set(T e) {
checkState(canRemoveOrSet);
forwardIterator.set(e);
}
};
}
}
private static class RandomAccessReverseList<T> extends ReverseList<T>
implements RandomAccess {
RandomAccessReverseList(List<T> forwardList) {
super(forwardList);
}
}
/**
* An implementation of {@link List#hashCode()}.
*/
static int hashCodeImpl(List<?> list) {
// TODO(user): worth optimizing for RandomAccess?
int hashCode = 1;
for (Object o : list) {
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
hashCode = ~~hashCode;
// needed to deal with GWT integer overflow
}
return hashCode;
}
/**
* An implementation of {@link List#equals(Object)}.
*/
static boolean equalsImpl(List<?> list, @Nullable Object object) {
if (object == checkNotNull(list)) {
return true;
}
if (!(object instanceof List)) {
return false;
}
List<?> o = (List<?>) object;
return list.size() == o.size()
&& Iterators.elementsEqual(list.iterator(), o.iterator());
}
/**
* An implementation of {@link List#addAll(int, Collection)}.
*/
static <E> boolean addAllImpl(
List<E> list, int index, Iterable<? extends E> elements) {
boolean changed = false;
ListIterator<E> listIterator = list.listIterator(index);
for (E e : elements) {
listIterator.add(e);
changed = true;
}
return changed;
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element) {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
/**
* Returns an implementation of {@link List#listIterator(int)}.
*/
static <E> ListIterator<E> listIteratorImpl(List<E> list, int index) {
return new AbstractListWrapper<E>(list).listIterator(index);
}
/**
* An implementation of {@link List#subList(int, int)}.
*/
static <E> List<E> subListImpl(
final List<E> list, int fromIndex, int toIndex) {
List<E> wrapper;
if (list instanceof RandomAccess) {
wrapper = new RandomAccessListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
} else {
wrapper = new AbstractListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
}
private static class AbstractListWrapper<E> extends AbstractList<E> {
final List<E> backingList;
AbstractListWrapper(List<E> backingList) {
this.backingList = checkNotNull(backingList);
}
@Override public void add(int index, E element) {
backingList.add(index, element);
}
@Override public boolean addAll(int index, Collection<? extends E> c) {
return backingList.addAll(index, c);
}
@Override public E get(int index) {
return backingList.get(index);
}
@Override public E remove(int index) {
return backingList.remove(index);
}
@Override public E set(int index, E element) {
return backingList.set(index, element);
}
@Override public boolean contains(Object o) {
return backingList.contains(o);
}
@Override public int size() {
return backingList.size();
}
}
private static class RandomAccessListWrapper<E>
extends AbstractListWrapper<E> implements RandomAccess {
RandomAccessListWrapper(List<E> backingList) {
super(backingList);
}
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> List<T> cast(Iterable<T> iterable) {
return (List<T>) iterable;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Lists.java | Java | asf20 | 35,952 |
/*
* 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.concurrent.ConcurrentMap;
/**
* A concurrent map which forwards all its method calls to another concurrent
* map. Subclasses should override one or more methods to modify the behavior of
* the backing map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Charles Fry
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingConcurrentMap<K, V> extends ForwardingMap<K, V>
implements ConcurrentMap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingConcurrentMap() {}
@Override protected abstract ConcurrentMap<K, V> delegate();
@Override
public V putIfAbsent(K key, V value) {
return delegate().putIfAbsent(key, value);
}
@Override
public boolean remove(Object key, Object value) {
return delegate().remove(key, value);
}
@Override
public V replace(K key, V value) {
return delegate().replace(key, value);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
return delegate().replace(key, oldValue, newValue);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingConcurrentMap.java | Java | asf20 | 1,835 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting
* all optional operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null
* keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@Beta
@GwtIncompatible("NavigableMap")
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<K, V>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@Nullable
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@Nullable
public Entry<Range<K>, V> getEntry(K key) {
Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putAll(RangeMap<K, V> rangeMap) {
for (Map.Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
if (firstEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound,
lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(rangeToRemove.upperBound, rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(rangeMapEntry.getLowerBound(), rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(rangeToRemove.upperBound, rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
entriesByLowerBound.remove(rangeToRemove.lowerBound);
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges();
}
private final class AsMapOfRanges extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@Nullable Object key) {
return get(key) != null;
}
@Override
public V get(@Nullable Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new AbstractSet<Entry<Range<K>, V>>() {
@SuppressWarnings("unchecked") // it's safe to upcast iterators
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return (Iterator) entriesByLowerBound.values().iterator();
}
@Override
public int size() {
return entriesByLowerBound.size();
}
};
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return EMPTY_SUB_RANGE_MAP;
}
private static final RangeMap EMPTY_SUB_RANGE_MAP =
new RangeMap() {
@Override
@Nullable
public Object get(Comparable key) {
return null;
}
@Override
@Nullable
public Entry<Range, Object> getEntry(Comparable key) {
return null;
}
@Override
public Range span() {
throw new NoSuchElementException();
}
@Override
public void put(Range range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty " + "subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range range) {
checkNotNull(range);
}
@Override
public Map<Range, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap subRangeMap(Range range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@Nullable
public V get(K key) {
return subRange.contains(key)
? TreeRangeMap.this.get(key)
: null;
}
@Override
@Nullable
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null &&
lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(subRange.encloses(range),
"Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putAll(RangeMap<K, V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)", span, subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(Object key) {
return get(key) != null;
}
@Override
public V get(Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null && candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
public V remove(Object key) {
V value = get(key);
if (value != null) {
@SuppressWarnings("unchecked") // it's definitely in the map, so safe
Range<K> range = (Range<K>) key;
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@Nullable Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart = Objects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound),
subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
break;
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(
entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/TreeRangeMap.java | Java | asf20 | 18,182 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkElementIndex;
import com.google.common.annotations.GwtCompatible;
import com.google.common.math.IntMath;
import java.util.AbstractList;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* Implementation of {@link Lists#cartesianProduct(List)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class CartesianList<E> extends AbstractList<List<E>> implements RandomAccess {
private transient final ImmutableList<List<E>> axes;
private transient final int[] axesSizeProduct;
static <E> List<List<E>> create(List<? extends List<? extends E>> lists) {
ImmutableList.Builder<List<E>> axesBuilder =
new ImmutableList.Builder<List<E>>(lists.size());
for (List<? extends E> list : lists) {
List<E> copy = ImmutableList.copyOf(list);
if (copy.isEmpty()) {
return ImmutableList.of();
}
axesBuilder.add(copy);
}
return new CartesianList<E>(axesBuilder.build());
}
CartesianList(ImmutableList<List<E>> axes) {
this.axes = axes;
int[] axesSizeProduct = new int[axes.size() + 1];
axesSizeProduct[axes.size()] = 1;
try {
for (int i = axes.size() - 1; i >= 0; i--) {
axesSizeProduct[i] =
IntMath.checkedMultiply(axesSizeProduct[i + 1], axes.get(i).size());
}
} catch (ArithmeticException e) {
throw new IllegalArgumentException(
"Cartesian product too large; must have size at most Integer.MAX_VALUE");
}
this.axesSizeProduct = axesSizeProduct;
}
private int getAxisIndexForProductIndex(int index, int axis) {
return (index / axesSizeProduct[axis + 1]) % axes.get(axis).size();
}
@Override
public ImmutableList<E> get(final int index) {
checkElementIndex(index, size());
return new ImmutableList<E>() {
@Override
public int size() {
return axes.size();
}
@Override
public E get(int axis) {
checkElementIndex(axis, size());
int axisIndex = getAxisIndexForProductIndex(index, axis);
return axes.get(axis).get(axisIndex);
}
@Override
boolean isPartialView() {
return true;
}
};
}
@Override
public int size() {
return axesSizeProduct[0];
}
@Override
public boolean contains(@Nullable Object o) {
if (!(o instanceof List)) {
return false;
}
List<?> list = (List<?>) o;
if (list.size() != axes.size()) {
return false;
}
ListIterator<?> itr = list.listIterator();
while (itr.hasNext()) {
int index = itr.nextIndex();
if (!axes.get(index).contains(itr.next())) {
return false;
}
}
return true;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/CartesianList.java | Java | asf20 | 3,412 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.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>
*
* <p>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
*/
@Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
super.orderKeysBy(keyComparator);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@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.0
*/
@Override
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
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableList<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableListMultimap.java | Java | asf20 | 12,621 |
/*
* 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 3 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/EnumHashBiMap.java | Java | asf20 | 4,363 |
/*
* 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>
*
* <p>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;
T result = next;
next = null;
return result;
}
/**
* 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;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractIterator.java | Java | asf20 | 5,953 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* An immutable implementation of {@code RangeMap}, supporting all query operations efficiently.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@Beta
@GwtIncompatible("NavigableMap")
public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K, V> {
private static final ImmutableRangeMap<Comparable<?>, Object> EMPTY =
new ImmutableRangeMap<Comparable<?>, Object>(
ImmutableList.<Range<Comparable<?>>>of(), ImmutableList.of());
/**
* Returns an empty immutable range map.
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of() {
return (ImmutableRangeMap<K, V>) EMPTY;
}
/**
* Returns an immutable range map mapping a single range to a single value.
*/
public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of(
Range<K> range, V value) {
return new ImmutableRangeMap<K, V>(ImmutableList.of(range), ImmutableList.of(value));
}
@SuppressWarnings("unchecked")
public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> copyOf(
RangeMap<K, ? extends V> rangeMap) {
if (rangeMap instanceof ImmutableRangeMap) {
return (ImmutableRangeMap<K, V>) rangeMap;
}
Map<Range<K>, ? extends V> map = rangeMap.asMapOfRanges();
ImmutableList.Builder<Range<K>> rangesBuilder = new ImmutableList.Builder<Range<K>>(map.size());
ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<V>(map.size());
for (Entry<Range<K>, ? extends V> entry : map.entrySet()) {
rangesBuilder.add(entry.getKey());
valuesBuilder.add(entry.getValue());
}
return new ImmutableRangeMap<K, V>(rangesBuilder.build(), valuesBuilder.build());
}
/**
* Returns a new builder for an immutable range map.
*/
public static <K extends Comparable<?>, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* A builder for immutable range maps. Overlapping ranges are prohibited.
*/
public static final class Builder<K extends Comparable<?>, V> {
private final RangeSet<K> keyRanges;
private final RangeMap<K, V> rangeMap;
public Builder() {
this.keyRanges = TreeRangeSet.create();
this.rangeMap = TreeRangeMap.create();
}
/**
* Associates the specified range with the specified value.
*
* @throws IllegalArgumentException if {@code range} overlaps with any other ranges inserted
* into this builder, or if {@code range} is empty
*/
public Builder<K, V> put(Range<K> range, V value) {
checkNotNull(range);
checkNotNull(value);
checkArgument(!range.isEmpty(), "Range must not be empty, but was %s", range);
if (!keyRanges.complement().encloses(range)) {
// it's an error case; we can afford an expensive lookup
for (Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) {
Range<K> key = entry.getKey();
if (key.isConnected(range) && !key.intersection(range).isEmpty()) {
throw new IllegalArgumentException(
"Overlapping ranges: range " + range + " overlaps with entry " + entry);
}
}
}
keyRanges.add(range);
rangeMap.put(range, value);
return this;
}
/**
* Copies all associations from the specified range map into this builder.
*
* @throws IllegalArgumentException if any of the ranges in {@code rangeMap} overlap with ranges
* already in this builder
*/
public Builder<K, V> putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Returns an {@code ImmutableRangeMap} containing the associations previously added to this
* builder.
*/
public ImmutableRangeMap<K, V> build() {
Map<Range<K>, V> map = rangeMap.asMapOfRanges();
ImmutableList.Builder<Range<K>> rangesBuilder =
new ImmutableList.Builder<Range<K>>(map.size());
ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<V>(map.size());
for (Entry<Range<K>, V> entry : map.entrySet()) {
rangesBuilder.add(entry.getKey());
valuesBuilder.add(entry.getValue());
}
return new ImmutableRangeMap<K, V>(rangesBuilder.build(), valuesBuilder.build());
}
}
private final ImmutableList<Range<K>> ranges;
private final ImmutableList<V> values;
ImmutableRangeMap(ImmutableList<Range<K>> ranges, ImmutableList<V> values) {
this.ranges = ranges;
this.values = values;
}
@Override
@Nullable
public V get(K key) {
int index = SortedLists.binarySearch(ranges, Range.<K>lowerBoundFn(),
Cut.belowValue(key), KeyPresentBehavior.ANY_PRESENT, KeyAbsentBehavior.NEXT_LOWER);
if (index == -1) {
return null;
} else {
Range<K> range = ranges.get(index);
return range.contains(key) ? values.get(index) : null;
}
}
@Override
@Nullable
public Map.Entry<Range<K>, V> getEntry(K key) {
int index = SortedLists.binarySearch(ranges, Range.<K>lowerBoundFn(),
Cut.belowValue(key), KeyPresentBehavior.ANY_PRESENT, KeyAbsentBehavior.NEXT_LOWER);
if (index == -1) {
return null;
} else {
Range<K> range = ranges.get(index);
return range.contains(key) ? Maps.immutableEntry(range, values.get(index)) : null;
}
}
@Override
public Range<K> span() {
if (ranges.isEmpty()) {
throw new NoSuchElementException();
}
Range<K> firstRange = ranges.get(0);
Range<K> lastRange = ranges.get(ranges.size() - 1);
return Range.create(firstRange.lowerBound, lastRange.upperBound);
}
@Override
public void put(Range<K> range, V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(RangeMap<K, V> rangeMap) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public void remove(Range<K> range) {
throw new UnsupportedOperationException();
}
@Override
public ImmutableMap<Range<K>, V> asMapOfRanges() {
if (ranges.isEmpty()) {
return ImmutableMap.of();
}
RegularImmutableSortedSet<Range<K>> rangeSet =
new RegularImmutableSortedSet<Range<K>>(ranges, Range.RANGE_LEX_ORDERING);
return new RegularImmutableSortedMap<Range<K>, V>(rangeSet, values);
}
@Override
public ImmutableRangeMap<K, V> subRangeMap(final Range<K> range) {
if (checkNotNull(range).isEmpty()) {
return ImmutableRangeMap.of();
} else if (ranges.isEmpty() || range.encloses(span())) {
return this;
}
int lowerIndex = SortedLists.binarySearch(
ranges, Range.<K>upperBoundFn(), range.lowerBound,
KeyPresentBehavior.FIRST_AFTER, KeyAbsentBehavior.NEXT_HIGHER);
int upperIndex = SortedLists.binarySearch(ranges,
Range.<K>lowerBoundFn(), range.upperBound,
KeyPresentBehavior.ANY_PRESENT, KeyAbsentBehavior.NEXT_HIGHER);
if (lowerIndex >= upperIndex) {
return ImmutableRangeMap.of();
}
final int off = lowerIndex;
final int len = upperIndex - lowerIndex;
ImmutableList<Range<K>> subRanges = new ImmutableList<Range<K>>() {
@Override
public int size() {
return len;
}
@Override
public Range<K> get(int index) {
checkElementIndex(index, len);
if (index == 0 || index == len - 1) {
return ranges.get(index + off).intersection(range);
} else {
return ranges.get(index + off);
}
}
@Override
boolean isPartialView() {
return true;
}
};
final ImmutableRangeMap<K, V> outer = this;
return new ImmutableRangeMap<K, V>(
subRanges, values.subList(lowerIndex, upperIndex)) {
@Override
public ImmutableRangeMap<K, V> subRangeMap(Range<K> subRange) {
if (range.isConnected(subRange)) {
return outer.subRangeMap(subRange.intersection(range));
} else {
return ImmutableRangeMap.of();
}
}
};
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableRangeMap.java | Java | asf20 | 9,951 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.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
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
*/
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();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Table.java | Java | asf20 | 9,834 |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.NoSuchElementException;
/**
* A descriptor for a <i>discrete</i> {@code Comparable} domain such as all
* {@link Integer} instances. A discrete domain is one that supports the three basic
* operations: {@link #next}, {@link #previous} and {@link #distance}, according
* to their specifications. The methods {@link #minValue} and {@link #maxValue}
* should also be overridden for bounded types.
*
* <p>A discrete domain always represents the <i>entire</i> set of values of its
* type; it cannot represent partial domains such as "prime integers" or
* "strings of length 5."
*
* <p>See the Guava User Guide section on <a href=
* "http://code.google.com/p/guava-libraries/wiki/RangesExplained#Discrete_Domains">
* {@code DiscreteDomain}</a>.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@GwtCompatible
@Beta
public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code Integer}.
*
* @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()})
*/
public static DiscreteDomain<Integer> integers() {
return IntegerDomain.INSTANCE;
}
private static final class IntegerDomain extends DiscreteDomain<Integer>
implements Serializable {
private static final IntegerDomain INSTANCE = new IntegerDomain();
@Override public Integer next(Integer value) {
int i = value;
return (i == Integer.MAX_VALUE) ? null : i + 1;
}
@Override public Integer previous(Integer value) {
int i = value;
return (i == Integer.MIN_VALUE) ? null : i - 1;
}
@Override public long distance(Integer start, Integer end) {
return (long) end - start;
}
@Override public Integer minValue() {
return Integer.MIN_VALUE;
}
@Override public Integer maxValue() {
return Integer.MAX_VALUE;
}
private Object readResolve() {
return INSTANCE;
}
@Override
public String toString() {
return "DiscreteDomain.integers()";
}
private static final long serialVersionUID = 0;
}
/**
* Returns the discrete domain for values of type {@code Long}.
*
* @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()})
*/
public static DiscreteDomain<Long> longs() {
return LongDomain.INSTANCE;
}
private static final class LongDomain extends DiscreteDomain<Long>
implements Serializable {
private static final LongDomain INSTANCE = new LongDomain();
@Override public Long next(Long value) {
long l = value;
return (l == Long.MAX_VALUE) ? null : l + 1;
}
@Override public Long previous(Long value) {
long l = value;
return (l == Long.MIN_VALUE) ? null : l - 1;
}
@Override public long distance(Long start, Long end) {
long result = end - start;
if (end > start && result < 0) { // overflow
return Long.MAX_VALUE;
}
if (end < start && result > 0) { // underflow
return Long.MIN_VALUE;
}
return result;
}
@Override public Long minValue() {
return Long.MIN_VALUE;
}
@Override public Long maxValue() {
return Long.MAX_VALUE;
}
private Object readResolve() {
return INSTANCE;
}
@Override
public String toString() {
return "DiscreteDomain.longs()";
}
private static final long serialVersionUID = 0;
}
/**
* Returns the discrete domain for values of type {@code BigInteger}.
*
* @since 15.0
*/
public static DiscreteDomain<BigInteger> bigIntegers() {
return BigIntegerDomain.INSTANCE;
}
private static final class BigIntegerDomain extends DiscreteDomain<BigInteger>
implements Serializable {
private static final BigIntegerDomain INSTANCE = new BigIntegerDomain();
private static final BigInteger MIN_LONG =
BigInteger.valueOf(Long.MIN_VALUE);
private static final BigInteger MAX_LONG =
BigInteger.valueOf(Long.MAX_VALUE);
@Override public BigInteger next(BigInteger value) {
return value.add(BigInteger.ONE);
}
@Override public BigInteger previous(BigInteger value) {
return value.subtract(BigInteger.ONE);
}
@Override public long distance(BigInteger start, BigInteger end) {
return end.subtract(start).max(MIN_LONG).min(MAX_LONG).longValue();
}
private Object readResolve() {
return INSTANCE;
}
@Override
public String toString() {
return "DiscreteDomain.bigIntegers()";
}
private static final long serialVersionUID = 0;
}
/** Constructor for use by subclasses. */
protected DiscreteDomain() {}
/**
* Returns the unique least value of type {@code C} that is greater than
* {@code value}, or {@code null} if none exists. Inverse operation to {@link
* #previous}.
*
* @param value any value of type {@code C}
* @return the least value greater than {@code value}, or {@code null} if
* {@code value} is {@code maxValue()}
*/
public abstract C next(C value);
/**
* Returns the unique greatest value of type {@code C} that is less than
* {@code value}, or {@code null} if none exists. Inverse operation to {@link
* #next}.
*
* @param value any value of type {@code C}
* @return the greatest value less than {@code value}, or {@code null} if
* {@code value} is {@code minValue()}
*/
public abstract C previous(C value);
/**
* Returns a signed value indicating how many nested invocations of {@link
* #next} (if positive) or {@link #previous} (if negative) are needed to reach
* {@code end} starting from {@code start}. For example, if {@code end =
* next(next(next(start)))}, then {@code distance(start, end) == 3} and {@code
* distance(end, start) == -3}. As well, {@code distance(a, a)} is always
* zero.
*
* <p>Note that this function is necessarily well-defined for any discrete
* type.
*
* @return the distance as described above, or {@link Long#MIN_VALUE} or
* {@link Long#MAX_VALUE} if the distance is too small or too large,
* respectively.
*/
public abstract long distance(C start, C end);
/**
* Returns the minimum value of type {@code C}, if it has one. The minimum
* value is the unique value for which {@link Comparable#compareTo(Object)}
* never returns a positive value for any input of type {@code C}.
*
* <p>The default implementation throws {@code NoSuchElementException}.
*
* @return the minimum value of type {@code C}; never null
* @throws NoSuchElementException if the type has no (practical) minimum
* value; for example, {@link java.math.BigInteger}
*/
public C minValue() {
throw new NoSuchElementException();
}
/**
* Returns the maximum value of type {@code C}, if it has one. The maximum
* value is the unique value for which {@link Comparable#compareTo(Object)}
* never returns a negative value for any input of type {@code C}.
*
* <p>The default implementation throws {@code NoSuchElementException}.
*
* @return the maximum value of type {@code C}; never null
* @throws NoSuchElementException if the type has no (practical) maximum
* value; for example, {@link java.math.BigInteger}
*/
public C maxValue() {
throw new NoSuchElementException();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/DiscreteDomain.java | Java | asf20 | 8,132 |
/*
* 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.
*/
/**
* This package contains generic collection interfaces and implementations, and
* other utilities for working with collections. It is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* <h2>Collection Types</h2>
*
* <dl>
* <dt>{@link com.google.common.collect.BiMap}
* <dd>An extension of {@link java.util.Map} that guarantees the uniqueness of
* its values as well as that of its keys. This is sometimes called an
* "invertible map," since the restriction on values enables it to support
* an {@linkplain com.google.common.collect.BiMap#inverse inverse view} --
* which is another instance of {@code BiMap}.
*
* <dt>{@link com.google.common.collect.Multiset}
* <dd>An extension of {@link java.util.Collection} that may contain duplicate
* values like a {@link java.util.List}, yet has order-independent equality
* like a {@link java.util.Set}. One typical use for a multiset is to
* represent a histogram.
*
* <dt>{@link com.google.common.collect.Multimap}
* <dd>A new type, which is similar to {@link java.util.Map}, but may contain
* multiple entries with the same key. Some behaviors of
* {@link com.google.common.collect.Multimap} are left unspecified and are
* provided only by the subtypes mentioned below.
*
* <dt>{@link com.google.common.collect.ListMultimap}
* <dd>An extension of {@link com.google.common.collect.Multimap} which permits
* duplicate entries, supports random access of values for a particular key,
* and has <i>partially order-dependent equality</i> as defined by
* {@link com.google.common.collect.ListMultimap#equals(Object)}. {@code
* ListMultimap} takes its name from the fact that the {@linkplain
* com.google.common.collect.ListMultimap#get collection of values}
* associated with a given key fulfills the {@link java.util.List} contract.
*
* <dt>{@link com.google.common.collect.SetMultimap}
* <dd>An extension of {@link com.google.common.collect.Multimap} which has
* order-independent equality and does not allow duplicate entries; that is,
* while a key may appear twice in a {@code SetMultimap}, each must map to a
* different value. {@code SetMultimap} takes its name from the fact that
* the {@linkplain com.google.common.collect.SetMultimap#get collection of
* values} associated with a given key fulfills the {@link java.util.Set}
* contract.
*
* <dt>{@link com.google.common.collect.SortedSetMultimap}
* <dd>An extension of {@link com.google.common.collect.SetMultimap} for which
* the {@linkplain com.google.common.collect.SortedSetMultimap#get
* collection values} associated with a given key is a
* {@link java.util.SortedSet}.
*
* <dt>{@link com.google.common.collect.Table}
* <dd>A new type, which is similar to {@link java.util.Map}, but which indexes
* its values by an ordered pair of keys, a row key and column key.
*
* <dt>{@link com.google.common.collect.ClassToInstanceMap}
* <dd>An extension of {@link java.util.Map} that associates a raw type with an
* instance of that type.
* </dl>
*
* <h2>Collection Implementations</h2>
*
* <h3>of {@link java.util.List}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableList}
* </ul>
*
* <h3>of {@link java.util.Set}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableSet}
* <li>{@link com.google.common.collect.ImmutableSortedSet}
* <li>{@link com.google.common.collect.ContiguousSet} (see {@code Range})
* </ul>
*
* <h3>of {@link java.util.Map}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableMap}
* <li>{@link com.google.common.collect.ImmutableSortedMap}
* <li>{@link com.google.common.collect.MapMaker}
* </ul>
*
* <h3>of {@link com.google.common.collect.BiMap}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableBiMap}
* <li>{@link com.google.common.collect.HashBiMap}
* <li>{@link com.google.common.collect.EnumBiMap}
* <li>{@link com.google.common.collect.EnumHashBiMap}
* </ul>
*
* <h3>of {@link com.google.common.collect.Multiset}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableMultiset}
* <li>{@link com.google.common.collect.HashMultiset}
* <li>{@link com.google.common.collect.LinkedHashMultiset}
* <li>{@link com.google.common.collect.TreeMultiset}
* <li>{@link com.google.common.collect.EnumMultiset}
* <li>{@link com.google.common.collect.ConcurrentHashMultiset}
* </ul>
*
* <h3>of {@link com.google.common.collect.Multimap}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableMultimap}
* <li>{@link com.google.common.collect.ImmutableListMultimap}
* <li>{@link com.google.common.collect.ImmutableSetMultimap}
* <li>{@link com.google.common.collect.ArrayListMultimap}
* <li>{@link com.google.common.collect.HashMultimap}
* <li>{@link com.google.common.collect.TreeMultimap}
* <li>{@link com.google.common.collect.LinkedHashMultimap}
* <li>{@link com.google.common.collect.LinkedListMultimap}
* </ul>
*
* <h3>of {@link com.google.common.collect.Table}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableTable}
* <li>{@link com.google.common.collect.ArrayTable}
* <li>{@link com.google.common.collect.HashBasedTable}
* <li>{@link com.google.common.collect.TreeBasedTable}
* </ul>
*
* <h3>of {@link com.google.common.collect.ClassToInstanceMap}</h3>
* <ul>
* <li>{@link com.google.common.collect.ImmutableClassToInstanceMap}
* <li>{@link com.google.common.collect.MutableClassToInstanceMap}
* </ul>
*
* <h2>Classes of static utility methods</h2>
*
* <ul>
* <li>{@link com.google.common.collect.Collections2}
* <li>{@link com.google.common.collect.Iterators}
* <li>{@link com.google.common.collect.Iterables}
* <li>{@link com.google.common.collect.Lists}
* <li>{@link com.google.common.collect.Maps}
* <li>{@link com.google.common.collect.Queues}
* <li>{@link com.google.common.collect.Sets}
* <li>{@link com.google.common.collect.Multisets}
* <li>{@link com.google.common.collect.Multimaps}
* <li>{@link com.google.common.collect.Tables}
* <li>{@link com.google.common.collect.ObjectArrays}
* </ul>
*
* <h2>Comparison</h2>
*
* <ul>
* <li>{@link com.google.common.collect.Ordering}
* <li>{@link com.google.common.collect.ComparisonChain}
* </ul>
*
* <h2>Abstract implementations</h2>
*
* <ul>
* <li>{@link com.google.common.collect.AbstractIterator}
* <li>{@link com.google.common.collect.AbstractSequentialIterator}
* <li>{@link com.google.common.collect.ImmutableCollection}
* <li>{@link com.google.common.collect.UnmodifiableIterator}
* <li>{@link com.google.common.collect.UnmodifiableListIterator}
* </ul>
*
* <h2>Ranges</h2>
*
* <ul>
* <li>{@link com.google.common.collect.Range}
* <li>{@link com.google.common.collect.RangeMap}
* <li>{@link com.google.common.collect.DiscreteDomain}
* <li>{@link com.google.common.collect.ContiguousSet}
* </ul>
*
* <h2>Other</h2>
*
* <ul>
* <li>{@link com.google.common.collect.Interner},
* {@link com.google.common.collect.Interners}
* <li>{@link com.google.common.collect.Constraint},
* {@link com.google.common.collect.Constraints}
* <li>{@link com.google.common.collect.MapConstraint},
* {@link com.google.common.collect.MapConstraints}
* <li>{@link com.google.common.collect.MapDifference},
* {@link com.google.common.collect.SortedMapDifference}
* <li>{@link com.google.common.collect.MinMaxPriorityQueue}
* <li>{@link com.google.common.collect.PeekingIterator}
* </ul>
*
* <h2>Forwarding collections</h2>
*
* <ul>
* <li>{@link com.google.common.collect.ForwardingCollection}
* <li>{@link com.google.common.collect.ForwardingConcurrentMap}
* <li>{@link com.google.common.collect.ForwardingIterator}
* <li>{@link com.google.common.collect.ForwardingList}
* <li>{@link com.google.common.collect.ForwardingListIterator}
* <li>{@link com.google.common.collect.ForwardingListMultimap}
* <li>{@link com.google.common.collect.ForwardingMap}
* <li>{@link com.google.common.collect.ForwardingMapEntry}
* <li>{@link com.google.common.collect.ForwardingMultimap}
* <li>{@link com.google.common.collect.ForwardingMultiset}
* <li>{@link com.google.common.collect.ForwardingNavigableMap}
* <li>{@link com.google.common.collect.ForwardingNavigableSet}
* <li>{@link com.google.common.collect.ForwardingObject}
* <li>{@link com.google.common.collect.ForwardingQueue}
* <li>{@link com.google.common.collect.ForwardingSet}
* <li>{@link com.google.common.collect.ForwardingSetMultimap}
* <li>{@link com.google.common.collect.ForwardingSortedMap}
* <li>{@link com.google.common.collect.ForwardingSortedMultiset}
* <li>{@link com.google.common.collect.ForwardingSortedSet}
* <li>{@link com.google.common.collect.ForwardingSortedSetMultimap}
* <li>{@link com.google.common.collect.ForwardingTable}
* </ul>
*/
@javax.annotation.ParametersAreNonnullByDefault
package com.google.common.collect;
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/package-info.java | Java | asf20 | 9,579 |
/*
* 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;
/**
* Dummy class that makes the GWT serialization policy happy. It isn't used
* on the server-side.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
class ForwardingImmutableCollection {
private ForwardingImmutableCollection() {}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingImmutableCollection.java | Java | asf20 | 943 |
/*
* 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.Iterator;
import javax.annotation.Nullable;
/**
* An ordering which sorts iterables by comparing corresponding elements
* pairwise.
*/
@GwtCompatible(serializable = true)
final class LexicographicalOrdering<T>
extends Ordering<Iterable<T>> implements Serializable {
final Ordering<? super T> elementOrder;
LexicographicalOrdering(Ordering<? super T> elementOrder) {
this.elementOrder = elementOrder;
}
@Override public int compare(
Iterable<T> leftIterable, Iterable<T> rightIterable) {
Iterator<T> left = leftIterable.iterator();
Iterator<T> right = rightIterable.iterator();
while (left.hasNext()) {
if (!right.hasNext()) {
return LEFT_IS_GREATER; // because it's longer
}
int result = elementOrder.compare(left.next(), right.next());
if (result != 0) {
return result;
}
}
if (right.hasNext()) {
return RIGHT_IS_GREATER; // because it's longer
}
return 0;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof LexicographicalOrdering) {
LexicographicalOrdering<?> that = (LexicographicalOrdering<?>) object;
return this.elementOrder.equals(that.elementOrder);
}
return false;
}
@Override public int hashCode() {
return elementOrder.hashCode() ^ 2075626741; // meaningless
}
@Override public String toString() {
return elementOrder + ".lexicographical()";
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/LexicographicalOrdering.java | Java | asf20 | 2,287 |
/*
* 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.annotations.GwtIncompatible;
import com.google.common.collect.Multiset.Entry;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
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, emulated = 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> {
private static final ImmutableMultiset<Object> EMPTY =
new RegularImmutableMultiset<Object>(ImmutableMap.<Object, Integer>of(), 0);
/**
* Returns the empty immutable multiset.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static <E> ImmutableMultiset<E> of() {
return (ImmutableMultiset<E>) EMPTY;
}
/**
* 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) {
return new Builder<E>()
.add(e1)
.add(e2)
.add(e3)
.add(e4)
.add(e5)
.add(e6)
.add(others)
.build();
}
/**
* 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 = entrySet().iterator();
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
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
@GwtIncompatible("not present in emulated superclass")
@Override
int copyIntoArray(Object[] dst, int offset) {
for (Multiset.Entry<E> entry : entrySet()) {
Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement());
offset += entry.getCount();
}
return offset;
}
@Override public boolean equals(@Nullable Object object) {
return Multisets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override public String toString() {
return entrySet().toString();
}
private transient ImmutableSet<Entry<E>> entrySet;
@Override
public ImmutableSet<Entry<E>> entrySet() {
ImmutableSet<Entry<E>> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
private final ImmutableSet<Entry<E>> createEntrySet() {
return isEmpty() ? ImmutableSet.<Entry<E>>of() : new EntrySet();
}
abstract Entry<E> getEntry(int index);
private final class EntrySet extends ImmutableSet<Entry<E>> {
@Override
boolean isPartialView() {
return ImmutableMultiset.this.isPartialView();
}
@Override
public UnmodifiableIterator<Entry<E>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<E>> createAsList() {
return new ImmutableAsList<Entry<E>>() {
@Override
public Entry<E> get(int index) {
return getEntry(index);
}
@Override
ImmutableCollection<Entry<E>> delegateCollection() {
return EntrySet.this;
}
};
}
@Override
public int size() {
return elementSet().size();
}
@Override
public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = count(entry.getElement());
return count == entry.getCount();
}
return false;
}
@Override
public int hashCode() {
return ImmutableMultiset.this.hashCode();
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
// TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
Object writeReplace() {
return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
}
private static final long serialVersionUID = 0;
}
static class EntrySetSerializedForm<E> implements Serializable {
final ImmutableMultiset<E> multiset;
EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
this.multiset = multiset;
}
Object readResolve() {
return multiset.entrySet();
}
}
private static class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
SerializedForm(Multiset<?> multiset) {
int distinct = multiset.entrySet().size();
elements = new Object[distinct];
counts = new int[distinct];
int i = 0;
for (Entry<?> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
LinkedHashMultiset<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>
*
* <p>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);
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableMultiset.java | Java | asf20 | 18,639 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import com.google.common.annotations.GwtIncompatible;
import javax.annotation.Nullable;
/**
* Implementation of {@code Map.Entry} for {@link ImmutableMap} that adds extra methods to traverse
* hash buckets for the key and the value. This allows reuse in {@link RegularImmutableMap} and
* {@link RegularImmutableBiMap}, which don't have to recopy the entries created by their
* {@code Builder} implementations.
*
* @author Louis Wasserman
*/
@GwtIncompatible("unnecessary")
abstract class ImmutableMapEntry<K, V> extends ImmutableEntry<K, V> {
ImmutableMapEntry(K key, V value) {
super(key, value);
checkEntryNotNull(key, value);
}
ImmutableMapEntry(ImmutableMapEntry<K, V> contents) {
super(contents.getKey(), contents.getValue());
// null check would be redundant
}
@Nullable
abstract ImmutableMapEntry<K, V> getNextInKeyBucket();
@Nullable
abstract ImmutableMapEntry<K, V> getNextInValueBucket();
static final class TerminalEntry<K, V> extends ImmutableMapEntry<K, V> {
TerminalEntry(ImmutableMapEntry<K, V> contents) {
super(contents);
}
TerminalEntry(K key, V value) {
super(key, value);
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInKeyBucket() {
return null;
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInValueBucket() {
return null;
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableMapEntry.java | Java | asf20 | 2,107 |
/*
* 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(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);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Count.java | Java | asf20 | 1,678 |
/*
* 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.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* Static methods pertaining to sorted {@link List} instances.
*
* In this documentation, the terms <i>greatest</i>, <i>greater</i>, <i>least</i>, and
* <i>lesser</i> are considered to refer to the comparator on the elements, and the terms
* <i>first</i> and <i>last</i> are considered to refer to the elements' ordering in a
* list.
*
* @author Louis Wasserman
*/
@GwtCompatible
@Beta final class SortedLists {
private SortedLists() {}
/**
* A specification for which index to return if the list contains at least one element that
* compares as equal to the key.
*/
public enum KeyPresentBehavior {
/**
* Return the index of any list element that compares as equal to the key. No guarantees are
* made as to which index is returned, if more than one element compares as equal to the key.
*/
ANY_PRESENT {
@Override
<E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
return foundIndex;
}
},
/**
* Return the index of the last list element that compares as equal to the key.
*/
LAST_PRESENT {
@Override
<E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
// Of course, we have to use binary search to find the precise
// breakpoint...
int lower = foundIndex;
int upper = list.size() - 1;
// Everything between lower and upper inclusive compares at >= 0.
while (lower < upper) {
int middle = (lower + upper + 1) >>> 1;
int c = comparator.compare(list.get(middle), key);
if (c > 0) {
upper = middle - 1;
} else { // c == 0
lower = middle;
}
}
return lower;
}
},
/**
* Return the index of the first list element that compares as equal to the key.
*/
FIRST_PRESENT {
@Override
<E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
// Of course, we have to use binary search to find the precise
// breakpoint...
int lower = 0;
int upper = foundIndex;
// Of course, we have to use binary search to find the precise breakpoint...
// Everything between lower and upper inclusive compares at <= 0.
while (lower < upper) {
int middle = (lower + upper) >>> 1;
int c = comparator.compare(list.get(middle), key);
if (c < 0) {
lower = middle + 1;
} else { // c == 0
upper = middle;
}
}
return lower;
}
},
/**
* Return the index of the first list element that compares as greater than the key, or {@code
* list.size()} if there is no such element.
*/
FIRST_AFTER {
@Override
public <E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
return LAST_PRESENT.resultIndex(comparator, key, list, foundIndex) + 1;
}
},
/**
* Return the index of the last list element that compares as less than the key, or {@code -1}
* if there is no such element.
*/
LAST_BEFORE {
@Override
public <E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
return FIRST_PRESENT.resultIndex(comparator, key, list, foundIndex) - 1;
}
};
abstract <E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex);
}
/**
* A specification for which index to return if the list contains no elements that compare as
* equal to the key.
*/
public enum KeyAbsentBehavior {
/**
* Return the index of the next lower element in the list, or {@code -1} if there is no such
* element.
*/
NEXT_LOWER {
@Override
int resultIndex(int higherIndex) {
return higherIndex - 1;
}
},
/**
* Return the index of the next higher element in the list, or {@code list.size()} if there is
* no such element.
*/
NEXT_HIGHER {
@Override
public int resultIndex(int higherIndex) {
return higherIndex;
}
},
/**
* Return {@code ~insertionIndex}, where {@code insertionIndex} is defined as the point at
* which the key would be inserted into the list: the index of the next higher element in the
* list, or {@code list.size()} if there is no such element.
*
* <p>Note that the return value will be {@code >= 0} if and only if there is an element of the
* list that compares as equal to the key.
*
* <p>This is equivalent to the behavior of
* {@link java.util.Collections#binarySearch(List, Object)} when the key isn't present, since
* {@code ~insertionIndex} is equal to {@code -1 - insertionIndex}.
*/
INVERTED_INSERTION_INDEX {
@Override
public int resultIndex(int higherIndex) {
return ~higherIndex;
}
};
abstract int resultIndex(int higherIndex);
}
/**
* Searches the specified naturally ordered list for the specified object using the binary search
* algorithm.
*
* <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Ordering#natural}.
*/
public static <E extends Comparable> int binarySearch(List<? extends E> list, E e,
KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) {
checkNotNull(e);
return binarySearch(
list, checkNotNull(e), Ordering.natural(), presentBehavior, absentBehavior);
}
/**
* Binary searches the list for the specified key, using the specified key function.
*
* <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Ordering#natural}.
*/
public static <E, K extends Comparable> int binarySearch(List<E> list,
Function<? super E, K> keyFunction, @Nullable K key, KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
return binarySearch(
list,
keyFunction,
key,
Ordering.natural(),
presentBehavior,
absentBehavior);
}
/**
* Binary searches the list for the specified key, using the specified key function.
*
* <p>Equivalent to
* {@link #binarySearch(List, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} using
* {@link Lists#transform(List, Function) Lists.transform(list, keyFunction)}.
*/
public static <E, K> int binarySearch(
List<E> list,
Function<? super E, K> keyFunction,
@Nullable K key,
Comparator<? super K> keyComparator,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
return binarySearch(
Lists.transform(list, keyFunction), key, keyComparator, presentBehavior, absentBehavior);
}
/**
* Searches the specified list for the specified object using the binary search algorithm. The
* list must be sorted into ascending order according to the specified comparator (as by the
* {@link Collections#sort(List, Comparator) Collections.sort(List, Comparator)} method), prior
* to making this call. If it is not sorted, the results are undefined.
*
* <p>If there are elements in the list which compare as equal to the key, the choice of
* {@link KeyPresentBehavior} decides which index is returned. If no elements compare as equal to
* the key, the choice of {@link KeyAbsentBehavior} decides which index is returned.
*
* <p>This method runs in log(n) time on random-access lists, which offer near-constant-time
* access to each list element.
*
* @param list the list to be searched.
* @param key the value to be searched for.
* @param comparator the comparator by which the list is ordered.
* @param presentBehavior the specification for what to do if at least one element of the list
* compares as equal to the key.
* @param absentBehavior the specification for what to do if no elements of the list compare as
* equal to the key.
* @return the index determined by the {@code KeyPresentBehavior}, if the key is in the list;
* otherwise the index determined by the {@code KeyAbsentBehavior}.
*/
public static <E> int binarySearch(List<? extends E> list, @Nullable E key,
Comparator<? super E> comparator, KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
checkNotNull(comparator);
checkNotNull(list);
checkNotNull(presentBehavior);
checkNotNull(absentBehavior);
if (!(list instanceof RandomAccess)) {
list = Lists.newArrayList(list);
}
// TODO(user): benchmark when it's best to do a linear search
int lower = 0;
int upper = list.size() - 1;
while (lower <= upper) {
int middle = (lower + upper) >>> 1;
int c = comparator.compare(key, list.get(middle));
if (c < 0) {
upper = middle - 1;
} else if (c > 0) {
lower = middle + 1;
} else {
return lower + presentBehavior.resultIndex(
comparator, key, list.subList(lower, upper + 1), middle - lower);
}
}
return absentBehavior.resultIndex(lower);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SortedLists.java | Java | asf20 | 10,446 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.SortedSet;
/**
* A navigable set which forwards all its method calls to another navigable set. Subclasses should
* override one or more methods to modify the behavior of the backing 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 ForwardingNavigableSet} 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 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 Louis Wasserman
* @since 12.0
*/
public abstract class ForwardingNavigableSet<E>
extends ForwardingSortedSet<E> implements NavigableSet<E> {
/** Constructor for use by subclasses. */
protected ForwardingNavigableSet() {}
@Override
protected abstract NavigableSet<E> delegate();
@Override
public E lower(E e) {
return delegate().lower(e);
}
/**
* A sensible definition of {@link #lower} in terms of the {@code descendingIterator} method of
* {@link #headSet(Object, boolean)}. If you override {@link #headSet(Object, boolean)}, you may
* wish to override {@link #lower} to forward to this implementation.
*/
protected E standardLower(E e) {
return Iterators.getNext(headSet(e, false).descendingIterator(), null);
}
@Override
public E floor(E e) {
return delegate().floor(e);
}
/**
* A sensible definition of {@link #floor} in terms of the {@code descendingIterator} method of
* {@link #headSet(Object, boolean)}. If you override {@link #headSet(Object, boolean)}, you may
* wish to override {@link #floor} to forward to this implementation.
*/
protected E standardFloor(E e) {
return Iterators.getNext(headSet(e, true).descendingIterator(), null);
}
@Override
public E ceiling(E e) {
return delegate().ceiling(e);
}
/**
* A sensible definition of {@link #ceiling} in terms of the {@code iterator} method of
* {@link #tailSet(Object, boolean)}. If you override {@link #tailSet(Object, boolean)}, you may
* wish to override {@link #ceiling} to forward to this implementation.
*/
protected E standardCeiling(E e) {
return Iterators.getNext(tailSet(e, true).iterator(), null);
}
@Override
public E higher(E e) {
return delegate().higher(e);
}
/**
* A sensible definition of {@link #higher} in terms of the {@code iterator} method of
* {@link #tailSet(Object, boolean)}. If you override {@link #tailSet(Object, boolean)}, you may
* wish to override {@link #higher} to forward to this implementation.
*/
protected E standardHigher(E e) {
return Iterators.getNext(tailSet(e, false).iterator(), null);
}
@Override
public E pollFirst() {
return delegate().pollFirst();
}
/**
* A sensible definition of {@link #pollFirst} in terms of the {@code iterator} method. If you
* override {@link #iterator} you may wish to override {@link #pollFirst} to forward to this
* implementation.
*/
protected E standardPollFirst() {
return Iterators.pollNext(iterator());
}
@Override
public E pollLast() {
return delegate().pollLast();
}
/**
* A sensible definition of {@link #pollLast} in terms of the {@code descendingIterator} method.
* If you override {@link #descendingIterator} you may wish to override {@link #pollLast} to
* forward to this implementation.
*/
protected E standardPollLast() {
return Iterators.pollNext(descendingIterator());
}
protected E standardFirst() {
return iterator().next();
}
protected E standardLast() {
return descendingIterator().next();
}
@Override
public NavigableSet<E> descendingSet() {
return delegate().descendingSet();
}
/**
* A sensible implementation of {@link NavigableSet#descendingSet} in terms of the other methods
* of {@link NavigableSet}, notably including {@link NavigableSet#descendingIterator}.
*
* <p>In many cases, you may wish to override {@link ForwardingNavigableSet#descendingSet} to
* forward to this implementation or a subclass thereof.
*
* @since 12.0
*/
@Beta
protected class StandardDescendingSet extends Sets.DescendingSet<E> {
/** Constructor for use by subclasses. */
public StandardDescendingSet() {
super(ForwardingNavigableSet.this);
}
}
@Override
public Iterator<E> descendingIterator() {
return delegate().descendingIterator();
}
@Override
public NavigableSet<E> subSet(
E fromElement,
boolean fromInclusive,
E toElement,
boolean toInclusive) {
return delegate().subSet(fromElement, fromInclusive, toElement, toInclusive);
}
/**
* A sensible definition of {@link #subSet(Object, boolean, Object, boolean)} in terms of the
* {@code headSet} and {@code tailSet} methods. In many cases, you may wish to override
* {@link #subSet(Object, boolean, Object, boolean)} to forward to this implementation.
*/
@Beta
protected NavigableSet<E> standardSubSet(
E fromElement,
boolean fromInclusive,
E toElement,
boolean toInclusive) {
return tailSet(fromElement, fromInclusive).headSet(toElement, toInclusive);
}
/**
* A sensible definition of {@link #subSet(Object, Object)} in terms of the
* {@link #subSet(Object, boolean, Object, boolean)} method. If you override
* {@link #subSet(Object, boolean, Object, boolean)}, you may wish to override
* {@link #subSet(Object, Object)} to forward to this implementation.
*/
@Override
protected SortedSet<E> standardSubSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return delegate().headSet(toElement, inclusive);
}
/**
* A sensible definition of {@link #headSet(Object)} in terms of the
* {@link #headSet(Object, boolean)} method. If you override
* {@link #headSet(Object, boolean)}, you may wish to override
* {@link #headSet(Object)} to forward to this implementation.
*/
protected SortedSet<E> standardHeadSet(E toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return delegate().tailSet(fromElement, inclusive);
}
/**
* A sensible definition of {@link #tailSet(Object)} in terms of the
* {@link #tailSet(Object, boolean)} method. If you override
* {@link #tailSet(Object, boolean)}, you may wish to override
* {@link #tailSet(Object)} to forward to this implementation.
*/
protected SortedSet<E> standardTailSet(E fromElement) {
return tailSet(fromElement, true);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingNavigableSet.java | Java | asf20 | 8,143 |
/*
* 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 java.util.Comparator;
import java.util.SortedSet;
/**
* Utilities for dealing with sorted collections of all types.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class SortedIterables {
private SortedIterables() {}
/**
* Returns {@code true} if {@code elements} is a sorted collection using an ordering equivalent
* to {@code comparator}.
*/
public static boolean hasSameComparator(Comparator<?> comparator, Iterable<?> elements) {
checkNotNull(comparator);
checkNotNull(elements);
Comparator<?> comparator2;
if (elements instanceof SortedSet) {
comparator2 = comparator((SortedSet<?>) elements);
} else if (elements instanceof SortedIterable) {
comparator2 = ((SortedIterable<?>) elements).comparator();
} else {
return false;
}
return comparator.equals(comparator2);
}
@SuppressWarnings("unchecked")
// if sortedSet.comparator() is null, the set must be naturally ordered
public static <E> Comparator<? super E> comparator(SortedSet<E> sortedSet) {
Comparator<? super E> result = sortedSet.comparator();
if (result == null) {
result = (Comparator<? super E>) Ordering.natural();
}
return result;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SortedIterables.java | Java | asf20 | 1,970 |
/*
* 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.collect.Multisets.setCountImpl;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* This class provides a skeletal implementation of the {@link Multiset}
* interface. A new multiset implementation can be created easily by extending
* this class and implementing the {@link Multiset#entrySet()} method, plus
* optionally overriding {@link #add(Object, int)} and
* {@link #remove(Object, int)} to enable modifications to the multiset.
*
* <p>The {@link #count} and {@link #size} implementations all iterate across
* the set returned by {@link Multiset#entrySet()}, as do many methods acting on
* the set returned by {@link #elementSet()}. Override those methods for better
* performance.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
*/
@GwtCompatible
abstract class AbstractMultiset<E> extends AbstractCollection<E>
implements Multiset<E> {
// Query Operations
@Override public int size() {
return Multisets.sizeImpl(this);
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public boolean contains(@Nullable Object element) {
return count(element) > 0;
}
@Override public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@Override
public int count(@Nullable Object element) {
for (Entry<E> entry : entrySet()) {
if (Objects.equal(entry.getElement(), element)) {
return entry.getCount();
}
}
return 0;
}
// Modification Operations
@Override public boolean add(@Nullable E element) {
add(element, 1);
return true;
}
@Override
public int add(@Nullable E element, int occurrences) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(@Nullable Object element) {
return remove(element, 1) > 0;
}
@Override
public int remove(@Nullable Object element, int occurrences) {
throw new UnsupportedOperationException();
}
@Override
public int setCount(@Nullable E element, int count) {
return setCountImpl(this, element, count);
}
@Override
public boolean setCount(@Nullable E element, int oldCount, int newCount) {
return setCountImpl(this, element, oldCount, newCount);
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>This implementation is highly efficient when {@code elementsToAdd}
* is itself a {@link Multiset}.
*/
@Override public boolean addAll(Collection<? extends E> elementsToAdd) {
return Multisets.addAllImpl(this, elementsToAdd);
}
@Override public boolean removeAll(Collection<?> elementsToRemove) {
return Multisets.removeAllImpl(this, elementsToRemove);
}
@Override public boolean retainAll(Collection<?> elementsToRetain) {
return Multisets.retainAllImpl(this, elementsToRetain);
}
@Override public void clear() {
Iterators.clear(entryIterator());
}
// Views
private transient Set<E> elementSet;
@Override
public Set<E> elementSet() {
Set<E> result = elementSet;
if (result == null) {
elementSet = result = createElementSet();
}
return result;
}
/**
* Creates a new instance of this multiset's element set, which will be
* returned by {@link #elementSet()}.
*/
Set<E> createElementSet() {
return new ElementSet();
}
class ElementSet extends Multisets.ElementSet<E> {
@Override
Multiset<E> multiset() {
return AbstractMultiset.this;
}
}
abstract Iterator<Entry<E>> entryIterator();
abstract int distinctElements();
private transient Set<Entry<E>> entrySet;
@Override public Set<Entry<E>> entrySet() {
Set<Entry<E>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
class EntrySet extends Multisets.EntrySet<E> {
@Override Multiset<E> multiset() {
return AbstractMultiset.this;
}
@Override public Iterator<Entry<E>> iterator() {
return entryIterator();
}
@Override public int size() {
return distinctElements();
}
}
Set<Entry<E>> createEntrySet() {
return new EntrySet();
}
// Object methods
/**
* {@inheritDoc}
*
* <p>This implementation returns {@code true} if {@code object} is a multiset
* of the same size and if, for each element, the two multisets have the same
* count.
*/
@Override public boolean equals(@Nullable Object object) {
return Multisets.equalsImpl(this, object);
}
/**
* {@inheritDoc}
*
* <p>This implementation returns the hash code of {@link
* Multiset#entrySet()}.
*/
@Override public int hashCode() {
return entrySet().hashCode();
}
/**
* {@inheritDoc}
*
* <p>This implementation returns the result of invoking {@code toString} on
* {@link Multiset#entrySet()}.
*/
@Override public String toString() {
return entrySet().toString();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractMultiset.java | Java | asf20 | 5,709 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Predicate;
import java.util.List;
import javax.annotation.Nullable;
/**
* Implementation of {@link Multimaps#filterKeys(ListMultimap, Predicate)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class FilteredKeyListMultimap<K, V> extends FilteredKeyMultimap<K, V>
implements ListMultimap<K, V> {
FilteredKeyListMultimap(ListMultimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
super(unfiltered, keyPredicate);
}
@Override
public ListMultimap<K, V> unfiltered() {
return (ListMultimap<K, V>) super.unfiltered();
}
@Override
public List<V> get(K key) {
return (List<V>) super.get(key);
}
@Override
public List<V> removeAll(@Nullable 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);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/FilteredKeyListMultimap.java | Java | asf20 | 1,620 |
/*
* 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 javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMultiset} with zero 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
Entry<E> getEntry(int index) {
Map.Entry<E, Integer> mapEntry = map.entrySet().asList().get(index);
return Multisets.immutableEntry(mapEntry.getKey(), mapEntry.getValue());
}
@Override
public int hashCode() {
return map.hashCode();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/RegularImmutableMultiset.java | Java | asf20 | 2,008 |
/*
* 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ExplicitOrdering.java | Java | asf20 | 2,244 |
/*
* 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.Set;
import javax.annotation.Nullable;
/**
* A {@code Multimap} that cannot hold duplicate key-value pairs. Adding a
* key-value pair that's already in the multimap has no effect. See the {@link
* Multimap} documentation for information common to all multimaps.
*
* <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods
* each return a {@link Set} of values, while {@link #entries} returns a {@code
* Set} of map entries. Though the method signature doesn't say so explicitly,
* the map returned by {@link #asMap} has {@code Set} values.
*
* <p>If the values corresponding to a single key should be ordered according to
* a {@link java.util.Comparator} (or the natural order), see the
* {@link SortedSetMultimap} subinterface.
*
* <p>Since the value collections are sets, the behavior of a {@code SetMultimap}
* is not specified if key <em>or value</em> objects already present in the
* multimap change in a manner that affects {@code equals} comparisons.
* Use caution if mutable objects are used as keys or values in a
* {@code SetMultimap}.
*
* <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 SetMultimap<K, V> extends Multimap<K, V> {
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link java.util.Collection}
* specified in the {@link Multimap} interface.
*/
@Override
Set<V> get(@Nullable K key);
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link java.util.Collection}
* specified in the {@link Multimap} interface.
*/
@Override
Set<V> removeAll(@Nullable Object key);
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link java.util.Collection}
* specified in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override
Set<V> replaceValues(K key, Iterable<? extends V> values);
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link java.util.Collection}
* specified in the {@link Multimap} interface.
*/
@Override
Set<Map.Entry<K, V>> entries();
/**
* {@inheritDoc}
*
* <p><b>Note:</b> The returned map's values are guaranteed to be of type
* {@link Set}. To obtain this map with the more specific generic type
* {@code Map<K, Set<V>>}, call {@link Multimaps#asMap(SetMultimap)} instead.
*/
@Override
Map<K, Collection<V>> asMap();
/**
* Compares the specified object to this multimap for equality.
*
* <p>Two {@code SetMultimap} instances are equal if, for each key, they
* contain the same values. Equality does not depend on the ordering of keys
* or values.
*
* <p>An empty {@code SetMultimap} is equal to any other empty {@code
* Multimap}, including an empty {@code ListMultimap}.
*/
@Override
boolean equals(@Nullable Object obj);
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SetMultimap.java | Java | asf20 | 4,206 |
/*
* 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.SortedMap;
/**
* An object representing the differences between two sorted maps.
*
* @author Louis Wasserman
* @since 8.0
*/
@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();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SortedMapDifference.java | Java | asf20 | 1,152 |
/*
* 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;
/** 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);
return left.compareTo(right);
}
@Override public <S extends Comparable> Ordering<S> reverse() {
return (Ordering<S>) ReverseNaturalOrdering.INSTANCE;
}
// 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/NaturalOrdering.java | Java | asf20 | 1,700 |
/*
* 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.Predicates.compose;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
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.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.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() {}
private enum EntryFunction implements Function<Entry<?, ?>, Object> {
KEY {
@Override
@Nullable
public Object apply(Entry<?, ?> entry) {
return entry.getKey();
}
},
VALUE {
@Override
@Nullable
public Object apply(Entry<?, ?> entry) {
return entry.getValue();
}
};
}
@SuppressWarnings("unchecked")
static <K> Function<Entry<K, ?>, K> keyFunction() {
return (Function) EntryFunction.KEY;
}
@SuppressWarnings("unchecked")
static <V> Function<Entry<?, V>, V> valueFunction() {
return (Function) EntryFunction.VALUE;
}
static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) {
return Iterators.transform(entryIterator, Maps.<K>keyFunction());
}
static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) {
return Iterators.transform(entryIterator, Maps.<V>valueFunction());
}
static <K, V> UnmodifiableIterator<V> valueIterator(
final UnmodifiableIterator<Entry<K, V>> entryIterator) {
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
/**
* Returns an immutable map instance containing the given entries.
* Internally, the returned map will be backed by an {@link EnumMap}.
*
* <p>The iteration order of the returned map follows the enum's iteration
* order, not the order in which the elements appear in the given map.
*
* @param map the map to make an immutable copy of
* @return an immutable map containing those entries
* @since 14.0
*/
@GwtCompatible(serializable = true)
@Beta
public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
Map<K, ? extends V> map) {
if (map instanceof ImmutableEnumMap) {
@SuppressWarnings("unchecked") // safe covariant cast
ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map;
return result;
} else if (map.isEmpty()) {
return ImmutableMap.of();
} else {
for (Map.Entry<K, ? extends V> entry : map.entrySet()) {
checkNotNull(entry.getKey());
checkNotNull(entry.getValue());
}
return ImmutableEnumMap.asImmutable(new EnumMap<K, V>(map));
}
}
/**
* 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) {
checkNonnegative(expectedSize, "expectedSize");
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, Equivalence.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();
doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
return new MapDifferenceImpl<K, V>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> void doDifference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence,
Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, MapDifference.ValueDifference<V>> differences) {
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 {
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
onlyOnLeft.put(leftKey, leftValue);
}
}
}
private static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
if (map instanceof SortedMap) {
return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
} else {
return Collections.unmodifiableMap(map);
}
}
static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.onlyOnLeft = unmodifiableMap(onlyOnLeft);
this.onlyOnRight = unmodifiableMap(onlyOnRight);
this.onBoth = unmodifiableMap(onBoth);
this.differences = unmodifiableMap(differences);
}
@Override
public boolean areEqual() {
return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty();
}
@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
*/
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);
doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<K, V>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(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 a live {@link Map} view whose keys are the contents of {@code set}
* and whose values are computed on demand using {@code function}. To get an
* immutable <i>copy</i> instead, use {@link #toMap(Iterable, Function)}.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map
* does not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also
* of type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
public static <K, V> Map<K, V> asMap(
Set<K> set, Function<? super K, V> function) {
if (set instanceof SortedSet) {
return asMap((SortedSet<K>) set, function);
} else {
return new AsMapView<K, V>(set, function);
}
}
/**
* Returns a view of the sorted set as a map, mapping keys from the set
* according to the specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map does
* not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
public static <K, V> SortedMap<K, V> asMap(
SortedSet<K> set, Function<? super K, V> function) {
return Platform.mapsAsMapSortedSet(set, function);
}
static <K, V> SortedMap<K, V> asMapSortedIgnoreNavigable(SortedSet<K> set,
Function<? super K, V> function) {
return new SortedAsMapView<K, V>(set, function);
}
/**
* Returns a view of the navigable set as a map, mapping keys from the set
* according to the specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map
* does not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also
* of type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> asMap(
NavigableSet<K> set, Function<? super K, V> function) {
return new NavigableAsMapView<K, V>(set, function);
}
private static class AsMapView<K, V> extends ImprovedAbstractMap<K, V> {
private final Set<K> set;
final Function<? super K, V> function;
Set<K> backingSet() {
return set;
}
AsMapView(Set<K> set, Function<? super K, V> function) {
this.set = checkNotNull(set);
this.function = checkNotNull(function);
}
@Override
public Set<K> createKeySet() {
return removeOnlySet(backingSet());
}
@Override
Collection<V> createValues() {
return Collections2.transform(set, function);
}
@Override
public int size() {
return backingSet().size();
}
@Override
public boolean containsKey(@Nullable Object key) {
return backingSet().contains(key);
}
@Override
public V get(@Nullable Object key) {
if (Collections2.safeContains(backingSet(), key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public V remove(@Nullable Object key) {
if (backingSet().remove(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
backingSet().clear();
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet<K, V>() {
@Override
Map<K, V> map() {
return AsMapView.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return asMapEntryIterator(backingSet(), function);
}
};
}
}
static <K, V> Iterator<Entry<K, V>> asMapEntryIterator(
Set<K> set, final Function<? super K, V> function) {
return new TransformedIterator<K, Entry<K,V>>(set.iterator()) {
@Override
Entry<K, V> transform(final K key) {
return immutableEntry(key, function.apply(key));
}
};
}
private static class SortedAsMapView<K, V> extends AsMapView<K, V>
implements SortedMap<K, V> {
SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) {
super(set, function);
}
@Override
SortedSet<K> backingSet() {
return (SortedSet<K>) super.backingSet();
}
@Override
public Comparator<? super K> comparator() {
return backingSet().comparator();
}
@Override
public Set<K> keySet() {
return removeOnlySortedSet(backingSet());
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return asMap(backingSet().subSet(fromKey, toKey), function);
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return asMap(backingSet().headSet(toKey), function);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return asMap(backingSet().tailSet(fromKey), function);
}
@Override
public K firstKey() {
return backingSet().first();
}
@Override
public K lastKey() {
return backingSet().last();
}
}
@GwtIncompatible("NavigableMap")
private static final class NavigableAsMapView<K, V>
extends AbstractNavigableMap<K, V> {
/*
* Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the
* NavigableMap methods.
*/
private final NavigableSet<K> set;
private final Function<? super K, V> function;
NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) {
this.set = checkNotNull(ks);
this.function = checkNotNull(vFunction);
}
@Override
public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return asMap(set.headSet(toKey, inclusive), function);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return asMap(set.tailSet(fromKey, inclusive), function);
}
@Override
public Comparator<? super K> comparator() {
return set.comparator();
}
@Override
@Nullable
public V get(@Nullable Object key) {
if (Collections2.safeContains(set, key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
set.clear();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return asMapEntryIterator(set, function);
}
@Override
Iterator<Entry<K, V>> descendingEntryIterator() {
return descendingMap().entrySet().iterator();
}
@Override
public NavigableSet<K> navigableKeySet() {
return removeOnlyNavigableSet(set);
}
@Override
public int size() {
return set.size();
}
@Override
public NavigableMap<K, V> descendingMap() {
return asMap(set.descendingSet(), function);
}
}
private static <E> Set<E> removeOnlySet(final Set<E> set) {
return new ForwardingSet<E>() {
@Override
protected Set<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
};
}
private static <E> SortedSet<E> removeOnlySortedSet(final SortedSet<E> set) {
return new ForwardingSortedSet<E>() {
@Override
protected SortedSet<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
};
}
@GwtIncompatible("NavigableSet")
private static <E> NavigableSet<E> removeOnlyNavigableSet(final NavigableSet<E> set) {
return new ForwardingNavigableSet<E>() {
@Override
protected NavigableSet<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return removeOnlySortedSet(
super.subSet(fromElement, toElement));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return removeOnlyNavigableSet(super.headSet(toElement, inclusive));
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive));
}
@Override
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
E toElement, boolean toInclusive) {
return removeOnlyNavigableSet(super.subSet(
fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<E> descendingSet() {
return removeOnlyNavigableSet(super.descendingSet());
}
};
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code
* keys} and whose value for each key was computed by {@code valueFunction}.
* The map's iteration order is the order of the first appearance of each key
* in {@code keys}.
*
* <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of
* a copy using {@link Maps#asMap(Set, Function)}.
*
* @throws NullPointerException if any element of {@code keys} is
* {@code null}, or if {@code valueFunction} produces {@code null}
* for any key
* @since 14.0
*/
@Beta
public static <K, V> ImmutableMap<K, V> toMap(Iterable<K> keys,
Function<? super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code
* keys} and whose value for each key was computed by {@code valueFunction}.
* The map's iteration order is the order of the first appearance of each key
* in {@code keys}.
*
* @throws NullPointerException if any element of {@code keys} is
* {@code null}, or if {@code valueFunction} produces {@code null}
* for any key
* @since 14.0
*/
@Beta
public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys,
Function<? super K, V> valueFunction) {
checkNotNull(valueFunction);
// Using LHM instead of a builder so as not to fail on duplicate keys
Map<K, V> builder = newLinkedHashMap();
while (keys.hasNext()) {
K key = keys.next();
builder.put(key, valueFunction.apply(key));
}
return ImmutableMap.copyOf(builder);
}
/**
* 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);
}
/**
* 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<? extends K, ? extends 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 UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override public Entry<K, V> next() {
return unmodifiableEntry(delegate.next());
}
};
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@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 {@link Converter} that converts values using {@link BiMap#get bimap.get()},
* and whose inverse view converts values using
* {@link BiMap#inverse bimap.inverse()}{@code .get()}.
*
* <p>To use a plain {@link Map} as a {@link Function}, see
* {@link com.google.common.base.Functions#forMap(Map)} or
* {@link com.google.common.base.Functions#forMap(Map, Object)}.
*
* @since 16.0
*/
@Beta
public static <A, B> Converter<A, B> asConverter(final BiMap<A, B> bimap) {
return new BiMapConverter<A, B>(bimap);
}
private static final class BiMapConverter<A, B> extends Converter<A, B> implements Serializable {
private final BiMap<A, B> bimap;
BiMapConverter(BiMap<A, B> bimap) {
this.bimap = checkNotNull(bimap);
}
@Override
protected B doForward(A a) {
return convert(bimap, a);
}
@Override
protected A doBackward(B b) {
return convert(bimap.inverse(), b);
}
private static <X, Y> Y convert(BiMap<X, Y> bimap, X input) {
Y output = bimap.get(input);
checkArgument(output != null, "No non-null mapping present for input: %s", input);
return output;
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof BiMapConverter) {
BiMapConverter<?, ?> that = (BiMapConverter<?, ?>) object;
return this.bimap.equals(that.bimap);
}
return false;
}
@Override
public int hashCode() {
return bimap.hashCode();
}
// There's really no good way to implement toString() without printing the entire BiMap, right?
@Override
public String toString() {
return "Maps.asConverter(" + bimap + ")";
}
private static final long serialVersionUID = 0L;
}
/**
* 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>
*
* <p>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;
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, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* 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.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.
*
* @since 11.0
*/
public static <K, V1, V2> SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a navigable 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
*
* NavigableMap<String, Integer> map = Maps.newTreeMap();
* map.put("a", 4);
* map.put("b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* NavigableMap<String, Double> transformed =
* Maps.transformNavigableValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* 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 13.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(
NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* 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 =
* Maps.transformEntries(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
*/
public static <K, V1, V2> SortedMap<K, V2> transformEntries(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return Platform.mapsTransformEntriesSortedMap(fromMap, transformer);
}
/**
* Returns a view of a navigable map whose values are derived from the
* original navigable 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
*
* NavigableMap<String, Boolean> options = Maps.newTreeMap();
* options.put("verbose", false);
* options.put("sort", true);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : ("yes" + key);
* }
* };
* NavigableMap<String, String> transformed =
* LabsMaps.transformNavigableEntries(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 13.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformEntries(
final NavigableMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesNavigableMap<K, V1, V2>(fromMap, transformer);
}
static <K, V1, V2> SortedMap<K, V2> transformEntriesIgnoreNavigable(
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);
}
/**
* Views a function as an entry transformer that ignores the entry key.
*/
static <K, V1, V2> EntryTransformer<K, V1, V2>
asEntryTransformer(final Function<? super V1, V2> function) {
checkNotNull(function);
return new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
}
static <K, V1, V2> Function<V1, V2> asValueToValueFunction(
final EntryTransformer<? super K, V1, V2> transformer, final K key) {
checkNotNull(transformer);
return new Function<V1, V2>() {
@Override
public V2 apply(@Nullable V1 v1) {
return transformer.transformEntry(key, v1);
}
};
}
/**
* Views an entry transformer as a function from {@code Entry} to values.
*/
static <K, V1, V2> Function<Entry<K, V1>, V2> asEntryToValueFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, V2>() {
@Override
public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/**
* Returns a view of an entry transformed by the specified transformer.
*/
static <V2, K, V1> Entry<K, V2> transformEntry(
final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
checkNotNull(transformer);
checkNotNull(entry);
return new AbstractMapEntry<K, V2>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V2 getValue() {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/**
* Views an entry transformer as a function from entries to entries.
*/
static <K, V1, V2> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override
public Entry<K, V2> apply(final Entry<K, V1> entry) {
return transformEntry(transformer, entry);
}
};
}
static class TransformedEntriesMap<K, V1, V2>
extends ImprovedAbstractMap<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();
}
@Override
protected Set<Entry<K, V2>> createEntrySet() {
return new EntrySet<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
@Override public Iterator<Entry<K, V2>> iterator() {
return Iterators.transform(fromMap.entrySet().iterator(),
Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
};
}
}
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);
}
}
@GwtIncompatible("NavigableMap")
private static class TransformedEntriesNavigableMap<K, V1, V2>
extends TransformedEntriesSortedMap<K, V1, V2>
implements NavigableMap<K, V2> {
TransformedEntriesNavigableMap(NavigableMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override public Entry<K, V2> ceilingEntry(K key) {
return transformEntry(fromMap().ceilingEntry(key));
}
@Override public K ceilingKey(K key) {
return fromMap().ceilingKey(key);
}
@Override public NavigableSet<K> descendingKeySet() {
return fromMap().descendingKeySet();
}
@Override public NavigableMap<K, V2> descendingMap() {
return transformEntries(fromMap().descendingMap(), transformer);
}
@Override public Entry<K, V2> firstEntry() {
return transformEntry(fromMap().firstEntry());
}
@Override public Entry<K, V2> floorEntry(K key) {
return transformEntry(fromMap().floorEntry(key));
}
@Override public K floorKey(K key) {
return fromMap().floorKey(key);
}
@Override public NavigableMap<K, V2> headMap(K toKey) {
return headMap(toKey, false);
}
@Override public NavigableMap<K, V2> headMap(K toKey, boolean inclusive) {
return transformEntries(
fromMap().headMap(toKey, inclusive), transformer);
}
@Override public Entry<K, V2> higherEntry(K key) {
return transformEntry(fromMap().higherEntry(key));
}
@Override public K higherKey(K key) {
return fromMap().higherKey(key);
}
@Override public Entry<K, V2> lastEntry() {
return transformEntry(fromMap().lastEntry());
}
@Override public Entry<K, V2> lowerEntry(K key) {
return transformEntry(fromMap().lowerEntry(key));
}
@Override public K lowerKey(K key) {
return fromMap().lowerKey(key);
}
@Override public NavigableSet<K> navigableKeySet() {
return fromMap().navigableKeySet();
}
@Override public Entry<K, V2> pollFirstEntry() {
return transformEntry(fromMap().pollFirstEntry());
}
@Override public Entry<K, V2> pollLastEntry() {
return transformEntry(fromMap().pollLastEntry());
}
@Override public NavigableMap<K, V2> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return transformEntries(
fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive),
transformer);
}
@Override public NavigableMap<K, V2> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override public NavigableMap<K, V2> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override public NavigableMap<K, V2> tailMap(K fromKey, boolean inclusive) {
return transformEntries(
fromMap().tailMap(fromKey, inclusive), transformer);
}
@Nullable
private Entry<K, V2> transformEntry(@Nullable Entry<K, V1> entry) {
return (entry == null) ? null : Maps.transformEntry(transformer, entry);
}
@Override protected NavigableMap<K, V1> fromMap() {
return (NavigableMap<K, V1>) super.fromMap();
}
}
static <K> Predicate<Entry<K, ?>> keyPredicateOnEntries(Predicate<? super K> keyPredicate) {
return compose(keyPredicate, Maps.<K>keyFunction());
}
static <V> Predicate<Entry<?, V>> valuePredicateOnEntries(Predicate<? super V> valuePredicate) {
return compose(valuePredicate, Maps.<V>valueFunction());
}
/**
* 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);
} else if (unfiltered instanceof BiMap) {
return filterKeys((BiMap<K, V>) unfiltered, keyPredicate);
}
checkNotNull(keyPredicate);
Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate);
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
*/
public static <K, V> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a navigable 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 14.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> filterKeys(
NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate.
* The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap'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
* bimap and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code
* put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as
* documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterKeys(
BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* 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);
} else if (unfiltered instanceof BiMap) {
return filterValues((BiMap<K, V>) unfiltered, valuePredicate);
}
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* 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
*/
public static <K, V> SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a navigable 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 14.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> filterValues(
NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a
* predicate. The returned bimap is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting bimap'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
* bimap and its views. When given a value that doesn't satisfy the predicate, the bimap's
* {@code put()}, {@code forcePut()} 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 provided value doesn't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as
* documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterValues(
BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* 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);
} else if (unfiltered instanceof BiMap) {
return filterEntries((BiMap<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
*/
public static <K, V> SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
return Platform.mapsFilterSortedMap(unfiltered, entryPredicate);
}
static <K, V> SortedMap<K, V> filterSortedIgnoreNavigable(
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);
}
/**
* 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 14.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> filterEntries(
NavigableMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryNavigableMap)
? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
* returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap'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 bimap
* and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's
* {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an
* {@link IllegalArgumentException}. Similarly, the map's entries have an {@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
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every
* key/value mapping in the underlying bimap and determine which satisfy the filter. When a live
* view is <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as
* documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterEntries(
BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(unfiltered);
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryBiMap)
? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryBiMap<K, V>(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) {
return new FilteredEntryMap<K, V>(map.unfiltered,
Predicates.<Entry<K, V>>and(map.predicate, entryPredicate));
}
private abstract static class AbstractFilteredMap<K, V>
extends ImprovedAbstractMap<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(@Nullable Object key, @Nullable 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;
}
@Override
Collection<V> createValues() {
return new FilteredMapValues<K, V>(this, unfiltered, predicate);
}
}
private static final class FilteredMapValues<K, V> extends Maps.Values<K, V> {
Map<K, V> unfiltered;
Predicate<? super Entry<K, V>> predicate;
FilteredMapValues(Map<K, V> filteredMap, Map<K, V> unfiltered,
Predicate<? super Entry<K, V>> predicate) {
super(filteredMap);
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override public boolean remove(Object o) {
return Iterables.removeFirstMatching(unfiltered.entrySet(),
Predicates.<Entry<K, V>>and(predicate, Maps.<V>valuePredicateOnEntries(equalTo(o))))
!= null;
}
private boolean removeIf(Predicate<? super V> valuePredicate) {
return Iterables.removeIf(unfiltered.entrySet(), Predicates.<Entry<K, V>>and(
predicate, Maps.<V>valuePredicateOnEntries(valuePredicate)));
}
@Override public boolean removeAll(Collection<?> collection) {
return removeIf(in(collection));
}
@Override public boolean retainAll(Collection<?> collection) {
return removeIf(not(in(collection)));
}
@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);
}
}
private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> {
Predicate<? super K> keyPredicate;
FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
Set<K> createKeySet() {
return Sets.filter(unfiltered.keySet(), keyPredicate);
}
// 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);
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
@Override protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override public Iterator<Entry<K, V>> iterator() {
return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) {
@Override
Entry<K, V> transform(final Entry<K, V> entry) {
return new ForwardingMapEntry<K, V>() {
@Override
protected Entry<K, V> delegate() {
return entry;
}
@Override
public V setValue(V newValue) {
checkArgument(apply(getKey(), newValue));
return super.setValue(newValue);
}
};
}
};
}
}
@Override
Set<K> createKeySet() {
return new KeySet();
}
class KeySet extends Maps.KeySet<K, V> {
KeySet() {
super(FilteredEntryMap.this);
}
@Override public boolean remove(Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
private boolean removeIf(Predicate<? super K> keyPredicate) {
return Iterables.removeIf(unfiltered.entrySet(), Predicates.<Entry<K, V>>and(
predicate, Maps.<K>keyPredicateOnEntries(keyPredicate)));
}
@Override
public boolean removeAll(Collection<?> c) {
return removeIf(in(c));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeIf(not(in(c)));
}
@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 SortedSet<K> keySet() {
return (SortedSet<K>) super.keySet();
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet();
}
class SortedKeySet extends KeySet implements SortedSet<K> {
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return (SortedSet<K>) subMap(fromElement, toElement).keySet();
}
@Override
public SortedSet<K> headSet(K toElement) {
return (SortedSet<K>) headMap(toElement).keySet();
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return (SortedSet<K>) tailMap(fromElement).keySet();
}
@Override
public K first() {
return firstKey();
}
@Override
public K last() {
return lastKey();
}
}
@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);
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered navigable map.
*/
@GwtIncompatible("NavigableMap")
private static <K, V> NavigableMap<K, V> filterFiltered(
FilteredEntryNavigableMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.entryPredicate, entryPredicate);
return new FilteredEntryNavigableMap<K, V>(map.unfiltered, predicate);
}
@GwtIncompatible("NavigableMap")
private static class FilteredEntryNavigableMap<K, V> extends AbstractNavigableMap<K, V> {
/*
* It's less code to extend AbstractNavigableMap and forward the filtering logic to
* FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap
* methods.
*/
private final NavigableMap<K, V> unfiltered;
private final Predicate<? super Entry<K, V>> entryPredicate;
private final Map<K, V> filteredDelegate;
FilteredEntryNavigableMap(
NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
this.unfiltered = checkNotNull(unfiltered);
this.entryPredicate = entryPredicate;
this.filteredDelegate = new FilteredEntryMap<K, V>(unfiltered, entryPredicate);
}
@Override
public Comparator<? super K> comparator() {
return unfiltered.comparator();
}
@Override
public NavigableSet<K> navigableKeySet() {
return new Maps.NavigableKeySet<K, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return Iterators.removeIf(unfiltered.entrySet().iterator(),
Predicates.<Entry<K, V>>and(entryPredicate, Maps.<K>keyPredicateOnEntries(in(c))));
}
@Override
public boolean retainAll(Collection<?> c) {
return Iterators.removeIf(unfiltered.entrySet().iterator(), Predicates.<Entry<K, V>>and(
entryPredicate, Maps.<K>keyPredicateOnEntries(not(in(c)))));
}
};
}
@Override
public Collection<V> values() {
return new FilteredMapValues<K, V>(this, unfiltered, entryPredicate);
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate);
}
@Override
Iterator<Entry<K, V>> descendingEntryIterator() {
return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate);
}
@Override
public int size() {
return filteredDelegate.size();
}
@Override
@Nullable
public V get(@Nullable Object key) {
return filteredDelegate.get(key);
}
@Override
public boolean containsKey(@Nullable Object key) {
return filteredDelegate.containsKey(key);
}
@Override
public V put(K key, V value) {
return filteredDelegate.put(key, value);
}
@Override
public V remove(@Nullable Object key) {
return filteredDelegate.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
filteredDelegate.putAll(m);
}
@Override
public void clear() {
filteredDelegate.clear();
}
@Override
public Set<Entry<K, V>> entrySet() {
return filteredDelegate.entrySet();
}
@Override
public Entry<K, V> pollFirstEntry() {
return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate);
}
@Override
public Entry<K, V> pollLastEntry() {
return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate);
}
@Override
public NavigableMap<K, V> descendingMap() {
return filterEntries(unfiltered.descendingMap(), entryPredicate);
}
@Override
public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return filterEntries(
unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate);
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered map.
*/
private static <K, V> BiMap<K, V> filterFiltered(
FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate);
return new FilteredEntryBiMap<K, V>(map.unfiltered(), predicate);
}
static final class FilteredEntryBiMap<K, V> extends FilteredEntryMap<K, V>
implements BiMap<K, V> {
private final BiMap<V, K> inverse;
private static <K, V> Predicate<Entry<V, K>> inversePredicate(
final Predicate<? super Entry<K, V>> forwardPredicate) {
return new Predicate<Entry<V, K>>() {
@Override
public boolean apply(Entry<V, K> input) {
return forwardPredicate.apply(
Maps.immutableEntry(input.getValue(), input.getKey()));
}
};
}
FilteredEntryBiMap(BiMap<K, V> delegate,
Predicate<? super Entry<K, V>> predicate) {
super(delegate, predicate);
this.inverse = new FilteredEntryBiMap<V, K>(
delegate.inverse(), inversePredicate(predicate), this);
}
private FilteredEntryBiMap(
BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate,
BiMap<V, K> inverse) {
super(delegate, predicate);
this.inverse = inverse;
}
BiMap<K, V> unfiltered() {
return (BiMap<K, V>) unfiltered;
}
@Override
public V forcePut(@Nullable K key, @Nullable V value) {
checkArgument(apply(key, value));
return unfiltered().forcePut(key, value);
}
@Override
public BiMap<V, K> inverse() {
return inverse;
}
@Override
public Set<V> values() {
return inverse.keySet();
}
}
/**
* 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;
}
UnmodifiableNavigableMap(
NavigableMap<K, V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) {
this.delegate = delegate;
this.descendingMap = descendingMap;
}
@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;
return (result == null)
? descendingMap = new UnmodifiableNavigableMap<K, V>(delegate.descendingMap(), this)
: 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 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
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));
}
}
/**
* Returns a synchronized (thread-safe) navigable map backed by the specified
* navigable map. In order to guarantee serial access, it is critical that
* <b>all</b> access to the backing navigable map is accomplished
* through the returned navigable map (or its views).
*
* <p>It is imperative that the user manually synchronize on the returned
* navigable map when iterating over any of its collection views, or the
* collections views of any of its {@code descendingMap}, {@code subMap},
* {@code headMap} or {@code tailMap} views. <pre> {@code
*
* NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
*
* // Needn't be in synchronized block
* NavigableSet<K> set = map.navigableKeySet();
*
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<K> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* <p>or: <pre> {@code
*
* NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
* NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true);
*
* // Needn't be in synchronized block
* NavigableSet<K> set2 = map2.descendingKeySet();
*
* synchronized (map) { // Synchronizing on map, not map2 or set2!
* Iterator<K> it = set2.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned navigable map will be serializable if the specified
* navigable map is serializable.
*
* @param navigableMap the navigable map to be "wrapped" in a synchronized
* navigable map.
* @return a synchronized view of the specified navigable map.
* @since 13.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> synchronizedNavigableMap(
NavigableMap<K, V> navigableMap) {
return Synchronized.navigableMap(navigableMap);
}
/**
* {@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
abstract static 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.
*/
abstract Set<Entry<K, V>> createEntrySet();
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;
}
private transient Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
Set<K> createKeySet() {
return new KeySet<K, V>(this);
}
private transient Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = createValues() : result;
}
Collection<V> createValues() {
return new Values<K, V>(this);
}
}
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code
* ClassCastException} and {@code NullPointerException}.
*/
static <V> V safeGet(Map<?, V> map, @Nullable Object key) {
checkNotNull(map);
try {
return map.get(key);
} catch (ClassCastException e) {
return null;
} catch (NullPointerException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code
* ClassCastException} and {@code NullPointerException}.
*/
static boolean safeContainsKey(Map<?, ?> map, Object key) {
checkNotNull(map);
try {
return map.containsKey(key);
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
/**
* Delegates to {@link Map#remove}. Returns {@code null} on {@code
* ClassCastException} and {@code NullPointerException}.
*/
static <V> V safeRemove(Map<?, V> map, Object key) {
checkNotNull(map);
try {
return map.remove(key);
} catch (ClassCastException e) {
return null;
} catch (NullPointerException e) {
return null;
}
}
/**
* An admittedly inefficient implementation of {@link Map#containsKey}.
*/
static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) {
return Iterators.contains(keyIterator(map.entrySet().iterator()), key);
}
/**
* An implementation of {@link Map#containsValue}.
*/
static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) {
return Iterators.contains(valueIterator(map.entrySet().iterator()), value);
}
/**
* 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;
} else if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
static final MapJoiner STANDARD_JOINER =
Collections2.STANDARD_JOINER.withKeyValueSeparator("=");
/**
* 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());
}
}
static class KeySet<K, V> extends Sets.ImprovedAbstractSet<K> {
final Map<K, V> map;
KeySet(Map<K, V> map) {
this.map = checkNotNull(map);
}
Map<K, V> map() {
return map;
}
@Override public Iterator<K> iterator() {
return keyIterator(map().entrySet().iterator());
}
@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 void clear() {
map().clear();
}
}
@Nullable
static <K> K keyOrNull(@Nullable Entry<K, ?> entry) {
return (entry == null) ? null : entry.getKey();
}
@Nullable
static <V> V valueOrNull(@Nullable Entry<?, V> entry) {
return (entry == null) ? null : entry.getValue();
}
static class SortedKeySet<K, V> extends KeySet<K, V> implements SortedSet<K> {
SortedKeySet(SortedMap<K, V> map) {
super(map);
}
@Override
SortedMap<K, V> map() {
return (SortedMap<K, V>) super.map();
}
@Override
public Comparator<? super K> comparator() {
return map().comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet<K, V>(map().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet<K, V>(map().headMap(toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet<K, V>(map().tailMap(fromElement));
}
@Override
public K first() {
return map().firstKey();
}
@Override
public K last() {
return map().lastKey();
}
}
@GwtIncompatible("NavigableMap")
static class NavigableKeySet<K, V> extends SortedKeySet<K, V> implements NavigableSet<K> {
NavigableKeySet(NavigableMap<K, V> map) {
super(map);
}
@Override
NavigableMap<K, V> map() {
return (NavigableMap<K, V>) map;
}
@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);
}
}
static class Values<K, V> extends AbstractCollection<V> {
final Map<K, V> map;
Values(Map<K, V> map) {
this.map = checkNotNull(map);
}
final Map<K, V> map() {
return map;
}
@Override public Iterator<V> iterator() {
return valueIterator(map().entrySet().iterator());
}
@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 Sets.ImprovedAbstractSet<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 = Maps.safeGet(map(), 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
return Sets.removeAllImpl(this, c.iterator());
}
}
@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")
abstract static 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;
return (result == null) ? navigableKeySet = new NavigableKeySet<K, V>(this) : 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>(this);
}
@Override
public String toString() {
return standardToString();
}
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Maps.java | Java | asf20 | 136,681 |
/*
* 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 java.util.Set;
import javax.annotation.Nullable;
/**
* A collection that maps keys to values, similar to {@link Map}, but in which
* each key may be associated with <i>multiple</i> values. You can visualize the
* contents of a multimap either as a map from keys to <i>nonempty</i>
* collections of values:
*
* <ul>
* <li>a → 1, 2
* <li>b → 3
* </ul>
*
* ... or as a single "flattened" collection of key-value pairs:
*
* <ul>
* <li>a → 1
* <li>a → 2
* <li>b → 3
* </ul>
*
* <p><b>Important:</b> although the first interpretation resembles how most
* multimaps are <i>implemented</i>, the design of the {@code Multimap} API is
* based on the <i>second</i> form. So, using the multimap shown above as an
* example, the {@link #size} is {@code 3}, not {@code 2}, and the {@link
* #values} collection is {@code [1, 2, 3]}, not {@code [[1, 2], [3]]}. For
* those times when the first style is more useful, use the multimap's {@link
* #asMap} view (or create a {@code Map<K, Collection<V>>} in the first place).
*
* <h3>Example</h3>
*
* <p>The following code: <pre> {@code
*
* ListMultimap<String, String> multimap = ArrayListMultimap.create();
* for (President pres : US_PRESIDENTS_IN_ORDER) {
* multimap.put(pres.firstName(), pres.lastName());
* }
* for (String firstName : multimap.keySet()) {
* List<String> lastNames = multimap.get(firstName);
* out.println(firstName + ": " + lastNames);
* }}</pre>
*
* ... produces output such as: <pre> {@code
*
* Zachary: [Taylor]
* John: [Adams, Adams, Tyler, Kennedy] // Remember, Quincy!
* George: [Washington, Bush, Bush]
* Grover: [Cleveland, Cleveland] // Two, non-consecutive terms, rep'ing NJ!
* ...}</pre>
*
* <h3>Views</h3>
*
* <p>Much of the power of the multimap API comes from the <i>view
* collections</i> it provides. These always reflect the latest state of the
* multimap itself. When they support modification, the changes are
* <i>write-through</i> (they automatically update the backing multimap). These
* view collections are:
*
* <ul>
* <li>{@link #asMap}, mentioned above</li>
* <li>{@link #keys}, {@link #keySet}, {@link #values}, {@link #entries}, which
* are similar to the corresponding view collections of {@link Map}
* <li>and, notably, even the collection returned by {@link #get get(key)} is an
* active view of the values corresponding to {@code key}
* </ul>
*
* <p>The collections returned by the {@link #replaceValues replaceValues} and
* {@link #removeAll removeAll} methods, which contain values that have just
* been removed from the multimap, are naturally <i>not</i> views.
*
* <h3>Subinterfaces</h3>
*
* <p>Instead of using the {@code Multimap} interface directly, prefer the
* subinterfaces {@link ListMultimap} and {@link SetMultimap}. These take their
* names from the fact that the collections they return from {@code get} behave
* like (and, of course, implement) {@link List} and {@link Set}, respectively.
*
* <p>For example, the "presidents" code snippet above used a {@code
* ListMultimap}; if it had used a {@code SetMultimap} instead, two presidents
* would have vanished, and last names might or might not appear in
* chronological order.
*
* <p><b>Warning:</b> instances of type {@code Multimap} may not implement
* {@link Object#equals} in the way you expect (multimaps containing the same
* key-value pairs, even in the same order, may or may not be equal). The
* recommended subinterfaces provide a much stronger guarantee.
*
* <h3>Comparison to a map of collections</h3>
*
* <p>Multimaps are commonly used in places where a {@code Map<K,
* Collection<V>>} would otherwise have appeared. The differences include:
*
* <ul>
* <li>There is no need to populate an empty collection before adding an entry
* with {@link #put put}.
* <li>{@code get} never returns {@code null}, only an empty collection.
* <li>A key is contained in the multimap if and only if it maps to at least
* one value. Any operation that causes a key to have zero associated
* values has the effect of <i>removing</i> that key from the multimap.
* <li>The total entry count is available as {@link #size}.
* <li>Many complex operations become easier; for example, {@code
* Collections.min(multimap.values())} finds the smallest value across all
* keys.
* </ul>
*
* <h3>Implementations</h3>
*
* <p>As always, prefer the immutable implementations, {@link
* ImmutableListMultimap} and {@link ImmutableSetMultimap}. General-purpose
* mutable implementations are listed above under "All Known Implementing
* Classes". You can also create a <i>custom</i> multimap, backed by any {@code
* Map} and {@link Collection} types, using the {@link Multimaps#newMultimap
* Multimaps.newMultimap} family of methods. Finally, another popular way to
* obtain a multimap is using {@link Multimaps#index Multimaps.index}. See
* the {@link Multimaps} class for these and other static utilities related
* to multimaps.
*
* <h3>Other Notes</h3>
*
* <p>As with {@code Map}, the behavior of a {@code Multimap} is not specified
* if key objects already present in the multimap change in a manner that
* affects {@code equals} comparisons. Use caution if mutable objects are used
* as keys in a {@code Multimap}.
*
* <p>All methods that modify the multimap are optional. The view collections
* returned by the multimap may or may not be modifiable. Any modification
* method that is not supported will throw {@link
* UnsupportedOperationException}.
*
* <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 Multimap<K, V> {
// Query Operations
/**
* Returns the number of key-value pairs in this multimap.
*
* <p><b>Note:</b> this method does not return the number of <i>distinct
* keys</i> in the multimap, which is given by {@code keySet().size()} or
* {@code asMap().size()}. See the opening section of the {@link Multimap}
* class documentation for clarification.
*/
int size();
/**
* Returns {@code true} if this multimap contains no key-value pairs.
* Equivalent to {@code size() == 0}, but can in some cases be more efficient.
*/
boolean isEmpty();
/**
* Returns {@code true} if this multimap contains at least one key-value pair
* with the key {@code key}.
*/
boolean containsKey(@Nullable Object key);
/**
* Returns {@code true} if this multimap contains at least one key-value pair
* with the value {@code value}.
*/
boolean containsValue(@Nullable Object value);
/**
* Returns {@code true} if this multimap contains at least one key-value pair
* with the key {@code key} and the value {@code value}.
*/
boolean containsEntry(@Nullable Object key, @Nullable Object value);
// Modification Operations
/**
* Stores a key-value pair in this multimap.
*
* <p>Some multimap implementations allow duplicate key-value pairs, in which
* case {@code put} always adds a new key-value pair and increases the
* multimap size by 1. Other implementations prohibit duplicates, and storing
* a key-value pair that's already in the multimap has no effect.
*
* @return {@code true} if the method increased the size of the multimap, or
* {@code false} if the multimap already contained the key-value pair and
* doesn't allow duplicates
*/
boolean put(@Nullable K key, @Nullable V value);
/**
* Removes a single key-value pair with the key {@code key} and the value
* {@code value} from this multimap, if such exists. If multiple key-value
* pairs in the multimap fit this description, which one is removed is
* unspecified.
*
* @return {@code true} if the multimap changed
*/
boolean remove(@Nullable Object key, @Nullable Object value);
// Bulk Operations
/**
* Stores a key-value pair in this multimap for each of {@code values}, all
* using the same key, {@code key}. Equivalent to (but expected to be more
* efficient than): <pre> {@code
*
* for (V value : values) {
* put(key, value);
* }}</pre>
*
* <p>In particular, this is a no-op if {@code values} is empty.
*
* @return {@code true} if the multimap changed
*/
boolean putAll(@Nullable K key, Iterable<? extends V> values);
/**
* Stores all key-value pairs of {@code multimap} in this multimap, in the
* order returned by {@code multimap.entries()}.
*
* @return {@code true} if the multimap changed
*/
boolean putAll(Multimap<? extends K, ? extends V> multimap);
/**
* Stores a collection of values with the same key, replacing any existing
* values for that key.
*
* <p>If {@code values} is empty, this is equivalent to
* {@link #removeAll(Object) removeAll(key)}.
*
* @return the collection of replaced values, or an empty collection if no
* values were previously associated with the key. The collection
* <i>may</i> be modifiable, but updating it will have no effect on the
* multimap.
*/
Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values);
/**
* Removes all values associated with the key {@code key}.
*
* <p>Once this method returns, {@code key} will not be mapped to any values,
* so it will not appear in {@link #keySet()}, {@link #asMap()}, or any other
* views.
*
* @return the values that were removed (possibly empty). The returned
* collection <i>may</i> be modifiable, but updating it will have no
* effect on the multimap.
*/
Collection<V> removeAll(@Nullable Object key);
/**
* Removes all key-value pairs from the multimap, leaving it {@linkplain
* #isEmpty empty}.
*/
void clear();
// Views
/**
* Returns a view collection of the values associated with {@code key} in this
* multimap, if any. Note that when {@code containsKey(key)} is false, this
* returns an empty collection, not {@code null}.
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa.
*/
Collection<V> get(@Nullable K key);
/**
* Returns a view collection of all <i>distinct</i> keys contained in this
* multimap. Note that the key set contains a key if and only if this multimap
* maps that key to at least one value.
*
* <p>Changes to the returned set will update the underlying multimap, and
* vice versa. However, <i>adding</i> to the returned set is not possible.
*/
Set<K> keySet();
/**
* Returns a view collection containing the key from each key-value pair in
* this multimap, <i>without</i> collapsing duplicates. This collection has
* the same size as this multimap, and {@code keys().count(k) ==
* get(k).size()} for all {@code k}.
*
* <p>Changes to the returned multiset will update the underlying multimap,
* and vice versa. However, <i>adding</i> to the returned collection is not
* possible.
*/
Multiset<K> keys();
/**
* Returns a view collection containing the <i>value</i> from each key-value
* pair contained in this multimap, without collapsing duplicates (so {@code
* values().size() == size()}).
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa. However, <i>adding</i> to the returned collection is not
* possible.
*/
Collection<V> values();
/**
* Returns a view collection of all key-value pairs contained in this
* multimap, as {@link Map.Entry} instances.
*
* <p>Changes to the returned collection or the entries it contains will
* update the underlying multimap, and vice versa. However, <i>adding</i> to
* the returned collection is not possible.
*/
Collection<Map.Entry<K, V>> entries();
/**
* Returns a view of this multimap as a {@code Map} from each distinct key
* to the nonempty collection of that key's associated values. Note that
* {@code this.asMap().get(k)} is equivalent to {@code this.get(k)} only when
* {@code k} is a key contained in the multimap; otherwise it returns {@code
* null} as opposed to an empty collection.
*
* <p>Changes to the returned map or the collections that serve as its values
* will update the underlying multimap, and vice versa. The map does not
* support {@code put} or {@code putAll}, nor do its entries support {@link
* Map.Entry#setValue setValue}.
*/
Map<K, Collection<V>> asMap();
// Comparison and hashing
/**
* Compares the specified object with this multimap for equality. Two
* multimaps are equal when their map views, as returned by {@link #asMap},
* are also equal.
*
* <p>In general, two multimaps with identical key-value mappings may or may
* not be equal, depending on the implementation. For example, two
* {@link SetMultimap} instances with the same key-value mappings are equal,
* but equality of two {@link ListMultimap} instances depends on the ordering
* of the values for each key.
*
* <p>A non-empty {@link SetMultimap} cannot be equal to a non-empty
* {@link ListMultimap}, since their {@link #asMap} views contain unequal
* collections as values. However, any two empty multimaps are equal, because
* they both have empty {@link #asMap} views.
*/
@Override
boolean equals(@Nullable Object obj);
/**
* Returns the hash code for this multimap.
*
* <p>The hash code of a multimap is defined as the hash code of the map view,
* as returned by {@link Multimap#asMap}.
*/
@Override
int hashCode();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Multimap.java | Java | asf20 | 14,584 |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* A table which forwards all its method calls to another table. Subclasses
* should override one or more methods to modify the behavior of the backing
* map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Gregory Kick
* @since 7.0
*/
@GwtCompatible
public abstract class ForwardingTable<R, C, V> extends ForwardingObject
implements Table<R, C, V> {
/** Constructor for use by subclasses. */
protected ForwardingTable() {}
@Override protected abstract Table<R, C, V> delegate();
@Override
public Set<Cell<R, C, V>> cellSet() {
return delegate().cellSet();
}
@Override
public void clear() {
delegate().clear();
}
@Override
public Map<R, V> column(C columnKey) {
return delegate().column(columnKey);
}
@Override
public Set<C> columnKeySet() {
return delegate().columnKeySet();
}
@Override
public Map<C, Map<R, V>> columnMap() {
return delegate().columnMap();
}
@Override
public boolean contains(Object rowKey, Object columnKey) {
return delegate().contains(rowKey, columnKey);
}
@Override
public boolean containsColumn(Object columnKey) {
return delegate().containsColumn(columnKey);
}
@Override
public boolean containsRow(Object rowKey) {
return delegate().containsRow(rowKey);
}
@Override
public boolean containsValue(Object value) {
return delegate().containsValue(value);
}
@Override
public V get(Object rowKey, Object columnKey) {
return delegate().get(rowKey, columnKey);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public V put(R rowKey, C columnKey, V value) {
return delegate().put(rowKey, columnKey, value);
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
delegate().putAll(table);
}
@Override
public V remove(Object rowKey, Object columnKey) {
return delegate().remove(rowKey, columnKey);
}
@Override
public Map<C, V> row(R rowKey) {
return delegate().row(rowKey);
}
@Override
public Set<R> rowKeySet() {
return delegate().rowKeySet();
}
@Override
public Map<R, Map<C, V>> rowMap() {
return delegate().rowMap();
}
@Override
public int size() {
return delegate().size();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override public boolean equals(Object obj) {
return (obj == this) || delegate().equals(obj);
}
@Override public int hashCode() {
return delegate().hashCode();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingTable.java | Java | asf20 | 3,369 |
/*
* 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);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingSetMultimap.java | Java | asf20 | 1,720 |
/*
* 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.collect.MapConstraints.ConstrainedMap;
import com.google.common.primitives.Primitives;
import java.util.HashMap;
import java.util.Map;
/**
* A mutable class-to-instance map backed by an arbitrary user-provided map.
* See also {@link ImmutableClassToInstanceMap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#ClassToInstanceMap">
* {@code ClassToInstanceMap}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
public final class MutableClassToInstanceMap<B>
extends ConstrainedMap<Class<? extends B>, B>
implements ClassToInstanceMap<B> {
/**
* Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link
* HashMap} using the default initial capacity and load factor.
*/
public static <B> MutableClassToInstanceMap<B> create() {
return new MutableClassToInstanceMap<B>(
new HashMap<Class<? extends B>, B>());
}
/**
* Returns a new {@code MutableClassToInstanceMap} instance backed by a given
* empty {@code backingMap}. The caller surrenders control of the backing map,
* and thus should not allow any direct references to it to remain accessible.
*/
public static <B> MutableClassToInstanceMap<B> create(
Map<Class<? extends B>, B> backingMap) {
return new MutableClassToInstanceMap<B>(backingMap);
}
private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) {
super(delegate, VALUE_CAN_BE_CAST_TO_KEY);
}
private static final MapConstraint<Class<?>, Object> VALUE_CAN_BE_CAST_TO_KEY
= new MapConstraint<Class<?>, Object>() {
@Override
public void checkKeyValue(Class<?> key, Object value) {
cast(key, value);
}
};
@Override
public <T extends B> T putInstance(Class<T> type, T value) {
return cast(type, put(type, value));
}
@Override
public <T extends B> T getInstance(Class<T> type) {
return cast(type, get(type));
}
private static <B, T extends B> T cast(Class<T> type, B value) {
return Primitives.wrap(type).cast(value);
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/MutableClassToInstanceMap.java | Java | asf20 | 2,847 |
/*
* 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
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final void add(E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final void set(E e) {
throw new UnsupportedOperationException();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/UnmodifiableListIterator.java | Java | asf20 | 1,669 |
/*
* 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.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Multiset.Entry;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Provides static utility methods for creating and working with {@link
* Multiset} instances.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multisets">
* {@code Multisets}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Multisets {
private Multisets() {}
/**
* Returns an unmodifiable view of the specified multiset. Query operations on
* the returned multiset "read through" to the specified multiset, and
* attempts to modify the returned multiset result in an
* {@link UnsupportedOperationException}.
*
* <p>The returned multiset will be serializable if the specified multiset is
* serializable.
*
* @param multiset the multiset for which an unmodifiable view is to be
* generated
* @return an unmodifiable view of the multiset
*/
public static <E> Multiset<E> unmodifiableMultiset(
Multiset<? extends E> multiset) {
if (multiset instanceof UnmodifiableMultiset ||
multiset instanceof ImmutableMultiset) {
// Since it's unmodifiable, the covariant cast is safe
@SuppressWarnings("unchecked")
Multiset<E> result = (Multiset<E>) multiset;
return result;
}
return new UnmodifiableMultiset<E>(checkNotNull(multiset));
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <E> Multiset<E> unmodifiableMultiset(
ImmutableMultiset<E> multiset) {
return checkNotNull(multiset);
}
static class UnmodifiableMultiset<E>
extends ForwardingMultiset<E> implements Serializable {
final Multiset<? extends E> delegate;
UnmodifiableMultiset(Multiset<? extends E> delegate) {
this.delegate = delegate;
}
@SuppressWarnings("unchecked")
@Override protected Multiset<E> delegate() {
// This is safe because all non-covariant methods are overriden
return (Multiset<E>) delegate;
}
transient Set<E> elementSet;
Set<E> createElementSet() {
return Collections.<E>unmodifiableSet(delegate.elementSet());
}
@Override
public Set<E> elementSet() {
Set<E> es = elementSet;
return (es == null) ? elementSet = createElementSet() : es;
}
transient Set<Multiset.Entry<E>> entrySet;
@SuppressWarnings("unchecked")
@Override public Set<Multiset.Entry<E>> entrySet() {
Set<Multiset.Entry<E>> es = entrySet;
return (es == null)
// Safe because the returned set is made unmodifiable and Entry
// itself is readonly
? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet())
: es;
}
@SuppressWarnings("unchecked")
@Override public Iterator<E> iterator() {
// Safe because the returned Iterator is made unmodifiable
return (Iterator<E>) Iterators.unmodifiableIterator(delegate.iterator());
}
@Override public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override public int add(E element, int occurences) {
throw new UnsupportedOperationException();
}
@Override public boolean addAll(Collection<? extends E> elementsToAdd) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object element) {
throw new UnsupportedOperationException();
}
@Override public int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
@Override public boolean removeAll(Collection<?> elementsToRemove) {
throw new UnsupportedOperationException();
}
@Override public boolean retainAll(Collection<?> elementsToRetain) {
throw new UnsupportedOperationException();
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
@Override public boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable view of the specified sorted multiset. Query
* operations on the returned multiset "read through" to the specified
* multiset, and attempts to modify the returned multiset result in an {@link
* UnsupportedOperationException}.
*
* <p>The returned multiset will be serializable if the specified multiset is
* serializable.
*
* @param sortedMultiset the sorted multiset for which an unmodifiable view is
* to be generated
* @return an unmodifiable view of the multiset
* @since 11.0
*/
@Beta
public static <E> SortedMultiset<E> unmodifiableSortedMultiset(
SortedMultiset<E> sortedMultiset) {
// it's in its own file so it can be emulated for GWT
return new UnmodifiableSortedMultiset<E>(checkNotNull(sortedMultiset));
}
/**
* Returns an immutable multiset entry with the specified element and count.
* The entry will be serializable if {@code e} is.
*
* @param e the element to be associated with the returned entry
* @param n the count to be associated with the returned entry
* @throws IllegalArgumentException if {@code n} is negative
*/
public static <E> Multiset.Entry<E> immutableEntry(@Nullable E e, int n) {
return new ImmutableEntry<E>(e, n);
}
static final class ImmutableEntry<E> extends AbstractEntry<E> implements
Serializable {
@Nullable final E element;
final int count;
ImmutableEntry(@Nullable E element, int count) {
this.element = element;
this.count = count;
checkNonnegative(count, "count");
}
@Override
@Nullable public E getElement() {
return element;
}
@Override
public int getCount() {
return count;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a view of the elements of {@code unfiltered} that satisfy a predicate. The returned
* multiset is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multiset's iterators, and those of its {@code entrySet()} and
* {@code elementSet()}, do not support {@code remove()}. However, all other multiset methods
* supported by {@code unfiltered} are supported by the returned multiset. When given an element
* that doesn't satisfy the predicate, the multiset'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 multiset, only elements that satisfy the filter
* will be removed from the underlying multiset.
*
* <p>The returned multiset isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered multiset's methods, such as {@code size()}, iterate across every
* element in the underlying multiset and determine which elements satisfy the filter. When a
* live view is <i>not</i> needed, it may be faster to copy the returned multiset 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.)
*
* @since 14.0
*/
@Beta
public static <E> Multiset<E> filter(Multiset<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredMultiset) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredMultiset<E> filtered = (FilteredMultiset<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredMultiset<E>(filtered.unfiltered, combinedPredicate);
}
return new FilteredMultiset<E>(unfiltered, predicate);
}
private static final class FilteredMultiset<E> extends AbstractMultiset<E> {
final Multiset<E> unfiltered;
final Predicate<? super E> predicate;
FilteredMultiset(Multiset<E> unfiltered, Predicate<? super E> predicate) {
this.unfiltered = checkNotNull(unfiltered);
this.predicate = checkNotNull(predicate);
}
@Override
public UnmodifiableIterator<E> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
@Override
Set<E> createElementSet() {
return Sets.filter(unfiltered.elementSet(), predicate);
}
@Override
Set<Entry<E>> createEntrySet() {
return Sets.filter(unfiltered.entrySet(), new Predicate<Entry<E>>() {
@Override
public boolean apply(Entry<E> entry) {
return predicate.apply(entry.getElement());
}
});
}
@Override
Iterator<Entry<E>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
int distinctElements() {
return elementSet().size();
}
@Override
public int count(@Nullable Object element) {
int count = unfiltered.count(element);
if (count > 0) {
@SuppressWarnings("unchecked") // element is equal to an E
E e = (E) element;
return predicate.apply(e) ? count : 0;
}
return 0;
}
@Override
public int add(@Nullable E element, int occurrences) {
checkArgument(predicate.apply(element),
"Element %s does not match predicate %s", element, predicate);
return unfiltered.add(element, occurrences);
}
@Override
public int remove(@Nullable Object element, int occurrences) {
checkNonnegative(occurrences, "occurrences");
if (occurrences == 0) {
return count(element);
} else {
return contains(element) ? unfiltered.remove(element, occurrences) : 0;
}
}
@Override
public void clear() {
elementSet().clear();
}
}
/**
* Returns the expected number of distinct elements given the specified
* elements. The number of distinct elements is only computed if {@code
* elements} is an instance of {@code Multiset}; otherwise the default value
* of 11 is returned.
*/
static int inferDistinctElements(Iterable<?> elements) {
if (elements instanceof Multiset) {
return ((Multiset<?>) elements).elementSet().size();
}
return 11; // initial capacity will be rounded up to 16
}
/**
* Returns an unmodifiable view of the union of two multisets.
* In the returned multiset, the count of each element is the <i>maximum</i>
* of its counts in the two backing multisets. The iteration order of the
* returned multiset matches that of the element set of {@code multiset1}
* followed by the members of the element set of {@code multiset2} that are
* not contained in {@code multiset1}, with repeated occurrences of the same
* element appearing consecutively.
*
* <p>Results are undefined if {@code multiset1} and {@code multiset2} are
* based on different equivalence relations (as {@code HashMultiset} and
* {@code TreeMultiset} are).
*
* @since 14.0
*/
@Beta
public static <E> Multiset<E> union(
final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
checkNotNull(multiset1);
checkNotNull(multiset2);
return new AbstractMultiset<E>() {
@Override
public boolean contains(@Nullable Object element) {
return multiset1.contains(element) || multiset2.contains(element);
}
@Override
public boolean isEmpty() {
return multiset1.isEmpty() && multiset2.isEmpty();
}
@Override
public int count(Object element) {
return Math.max(multiset1.count(element), multiset2.count(element));
}
@Override
Set<E> createElementSet() {
return Sets.union(multiset1.elementSet(), multiset2.elementSet());
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<? extends Entry<? extends E>> iterator1
= multiset1.entrySet().iterator();
final Iterator<? extends Entry<? extends E>> iterator2
= multiset2.entrySet().iterator();
// TODO(user): consider making the entries live views
return new AbstractIterator<Entry<E>>() {
@Override
protected Entry<E> computeNext() {
if (iterator1.hasNext()) {
Entry<? extends E> entry1 = iterator1.next();
E element = entry1.getElement();
int count = Math.max(entry1.getCount(), multiset2.count(element));
return immutableEntry(element, count);
}
while (iterator2.hasNext()) {
Entry<? extends E> entry2 = iterator2.next();
E element = entry2.getElement();
if (!multiset1.contains(element)) {
return immutableEntry(element, entry2.getCount());
}
}
return endOfData();
}
};
}
@Override
int distinctElements() {
return elementSet().size();
}
};
}
/**
* Returns an unmodifiable view of the intersection of two multisets.
* In the returned multiset, the count of each element is the <i>minimum</i>
* of its counts in the two backing multisets, with elements that would have
* a count of 0 not included. The iteration order of the returned multiset
* matches that of the element set of {@code multiset1}, with repeated
* occurrences of the same element appearing consecutively.
*
* <p>Results are undefined if {@code multiset1} and {@code multiset2} are
* based on different equivalence relations (as {@code HashMultiset} and
* {@code TreeMultiset} are).
*
* @since 2.0
*/
public static <E> Multiset<E> intersection(
final Multiset<E> multiset1, final Multiset<?> multiset2) {
checkNotNull(multiset1);
checkNotNull(multiset2);
return new AbstractMultiset<E>() {
@Override
public int count(Object element) {
int count1 = multiset1.count(element);
return (count1 == 0) ? 0 : Math.min(count1, multiset2.count(element));
}
@Override
Set<E> createElementSet() {
return Sets.intersection(
multiset1.elementSet(), multiset2.elementSet());
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
// TODO(user): consider making the entries live views
return new AbstractIterator<Entry<E>>() {
@Override
protected Entry<E> computeNext() {
while (iterator1.hasNext()) {
Entry<E> entry1 = iterator1.next();
E element = entry1.getElement();
int count = Math.min(entry1.getCount(), multiset2.count(element));
if (count > 0) {
return immutableEntry(element, count);
}
}
return endOfData();
}
};
}
@Override
int distinctElements() {
return elementSet().size();
}
};
}
/**
* Returns an unmodifiable view of the sum of two multisets.
* In the returned multiset, the count of each element is the <i>sum</i> of
* its counts in the two backing multisets. The iteration order of the
* returned multiset matches that of the element set of {@code multiset1}
* followed by the members of the element set of {@code multiset2} that
* are not contained in {@code multiset1}, with repeated occurrences of the
* same element appearing consecutively.
*
* <p>Results are undefined if {@code multiset1} and {@code multiset2} are
* based on different equivalence relations (as {@code HashMultiset} and
* {@code TreeMultiset} are).
*
* @since 14.0
*/
@Beta
public static <E> Multiset<E> sum(
final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
checkNotNull(multiset1);
checkNotNull(multiset2);
// TODO(user): consider making the entries live views
return new AbstractMultiset<E>() {
@Override
public boolean contains(@Nullable Object element) {
return multiset1.contains(element) || multiset2.contains(element);
}
@Override
public boolean isEmpty() {
return multiset1.isEmpty() && multiset2.isEmpty();
}
@Override
public int size() {
return multiset1.size() + multiset2.size();
}
@Override
public int count(Object element) {
return multiset1.count(element) + multiset2.count(element);
}
@Override
Set<E> createElementSet() {
return Sets.union(multiset1.elementSet(), multiset2.elementSet());
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<? extends Entry<? extends E>> iterator1
= multiset1.entrySet().iterator();
final Iterator<? extends Entry<? extends E>> iterator2
= multiset2.entrySet().iterator();
return new AbstractIterator<Entry<E>>() {
@Override
protected Entry<E> computeNext() {
if (iterator1.hasNext()) {
Entry<? extends E> entry1 = iterator1.next();
E element = entry1.getElement();
int count = entry1.getCount() + multiset2.count(element);
return immutableEntry(element, count);
}
while (iterator2.hasNext()) {
Entry<? extends E> entry2 = iterator2.next();
E element = entry2.getElement();
if (!multiset1.contains(element)) {
return immutableEntry(element, entry2.getCount());
}
}
return endOfData();
}
};
}
@Override
int distinctElements() {
return elementSet().size();
}
};
}
/**
* Returns an unmodifiable view of the difference of two multisets.
* In the returned multiset, the count of each element is the result of the
* <i>zero-truncated subtraction</i> of its count in the second multiset from
* its count in the first multiset, with elements that would have a count of
* 0 not included. The iteration order of the returned multiset matches that
* of the element set of {@code multiset1}, with repeated occurrences of the
* same element appearing consecutively.
*
* <p>Results are undefined if {@code multiset1} and {@code multiset2} are
* based on different equivalence relations (as {@code HashMultiset} and
* {@code TreeMultiset} are).
*
* @since 14.0
*/
@Beta
public static <E> Multiset<E> difference(
final Multiset<E> multiset1, final Multiset<?> multiset2) {
checkNotNull(multiset1);
checkNotNull(multiset2);
// TODO(user): consider making the entries live views
return new AbstractMultiset<E>() {
@Override
public int count(@Nullable Object element) {
int count1 = multiset1.count(element);
return (count1 == 0) ? 0 :
Math.max(0, count1 - multiset2.count(element));
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
return new AbstractIterator<Entry<E>>() {
@Override
protected Entry<E> computeNext() {
while (iterator1.hasNext()) {
Entry<E> entry1 = iterator1.next();
E element = entry1.getElement();
int count = entry1.getCount() - multiset2.count(element);
if (count > 0) {
return immutableEntry(element, count);
}
}
return endOfData();
}
};
}
@Override
int distinctElements() {
return Iterators.size(entryIterator());
}
};
}
/**
* Returns {@code true} if {@code subMultiset.count(o) <=
* superMultiset.count(o)} for all {@code o}.
*
* @since 10.0
*/
public static boolean containsOccurrences(
Multiset<?> superMultiset, Multiset<?> subMultiset) {
checkNotNull(superMultiset);
checkNotNull(subMultiset);
for (Entry<?> entry : subMultiset.entrySet()) {
int superCount = superMultiset.count(entry.getElement());
if (superCount < entry.getCount()) {
return false;
}
}
return true;
}
/**
* Modifies {@code multisetToModify} so that its count for an element
* {@code e} is at most {@code multisetToRetain.count(e)}.
*
* <p>To be precise, {@code multisetToModify.count(e)} is set to
* {@code Math.min(multisetToModify.count(e),
* multisetToRetain.count(e))}. This is similar to
* {@link #intersection(Multiset, Multiset) intersection}
* {@code (multisetToModify, multisetToRetain)}, but mutates
* {@code multisetToModify} instead of returning a view.
*
* <p>In contrast, {@code multisetToModify.retainAll(multisetToRetain)} keeps
* all occurrences of elements that appear at all in {@code
* multisetToRetain}, and deletes all occurrences of all other elements.
*
* @return {@code true} if {@code multisetToModify} was changed as a result
* of this operation
* @since 10.0
*/
public static boolean retainOccurrences(Multiset<?> multisetToModify,
Multiset<?> multisetToRetain) {
return retainOccurrencesImpl(multisetToModify, multisetToRetain);
}
/**
* Delegate implementation which cares about the element type.
*/
private static <E> boolean retainOccurrencesImpl(
Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) {
checkNotNull(multisetToModify);
checkNotNull(occurrencesToRetain);
// Avoiding ConcurrentModificationExceptions is tricky.
Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator();
boolean changed = false;
while (entryIterator.hasNext()) {
Entry<E> entry = entryIterator.next();
int retainCount = occurrencesToRetain.count(entry.getElement());
if (retainCount == 0) {
entryIterator.remove();
changed = true;
} else if (retainCount < entry.getCount()) {
multisetToModify.setCount(entry.getElement(), retainCount);
changed = true;
}
}
return changed;
}
/**
* For each occurrence of an element {@code e} in {@code occurrencesToRemove},
* removes one occurrence of {@code e} in {@code multisetToModify}.
*
* <p>Equivalently, this method modifies {@code multisetToModify} so that
* {@code multisetToModify.count(e)} is set to
* {@code Math.max(0, multisetToModify.count(e) -
* occurrencesToRemove.count(e))}.
*
* <p>This is <i>not</i> the same as {@code multisetToModify.}
* {@link Multiset#removeAll removeAll}{@code (occurrencesToRemove)}, which
* removes all occurrences of elements that appear in
* {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent
* to, albeit more efficient than, the following: <pre> {@code
*
* for (E e : occurrencesToRemove) {
* multisetToModify.remove(e);
* }}</pre>
*
* @return {@code true} if {@code multisetToModify} was changed as a result of
* this operation
* @since 10.0
*/
public static boolean removeOccurrences(
Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) {
return removeOccurrencesImpl(multisetToModify, occurrencesToRemove);
}
/**
* Delegate that cares about the element types in occurrencesToRemove.
*/
private static <E> boolean removeOccurrencesImpl(
Multiset<E> multisetToModify, Multiset<?> occurrencesToRemove) {
// TODO(user): generalize to removing an Iterable, perhaps
checkNotNull(multisetToModify);
checkNotNull(occurrencesToRemove);
boolean changed = false;
Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator();
while (entryIterator.hasNext()) {
Entry<E> entry = entryIterator.next();
int removeCount = occurrencesToRemove.count(entry.getElement());
if (removeCount >= entry.getCount()) {
entryIterator.remove();
changed = true;
} else if (removeCount > 0) {
multisetToModify.remove(entry.getElement(), removeCount);
changed = true;
}
}
return changed;
}
/**
* Implementation of the {@code equals}, {@code hashCode}, and
* {@code toString} methods of {@link Multiset.Entry}.
*/
abstract static class AbstractEntry<E> implements Multiset.Entry<E> {
/**
* Indicates whether an object equals this entry, following the behavior
* specified in {@link Multiset.Entry#equals}.
*/
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Multiset.Entry) {
Multiset.Entry<?> that = (Multiset.Entry<?>) object;
return this.getCount() == that.getCount()
&& Objects.equal(this.getElement(), that.getElement());
}
return false;
}
/**
* Return this entry's hash code, following the behavior specified in
* {@link Multiset.Entry#hashCode}.
*/
@Override public int hashCode() {
E e = getElement();
return ((e == null) ? 0 : e.hashCode()) ^ getCount();
}
/**
* Returns a string representation of this multiset entry. The string
* representation consists of the associated element if the associated count
* is one, and otherwise the associated element followed by the characters
* " x " (space, x and space) followed by the count. Elements and counts are
* converted to strings as by {@code String.valueOf}.
*/
@Override public String toString() {
String text = String.valueOf(getElement());
int n = getCount();
return (n == 1) ? text : (text + " x " + n);
}
}
/**
* An implementation of {@link Multiset#equals}.
*/
static boolean equalsImpl(Multiset<?> multiset, @Nullable Object object) {
if (object == multiset) {
return true;
}
if (object instanceof Multiset) {
Multiset<?> that = (Multiset<?>) object;
/*
* We can't simply check whether the entry sets are equal, since that
* approach fails when a TreeMultiset has a comparator that returns 0
* when passed unequal elements.
*/
if (multiset.size() != that.size()
|| multiset.entrySet().size() != that.entrySet().size()) {
return false;
}
for (Entry<?> entry : that.entrySet()) {
if (multiset.count(entry.getElement()) != entry.getCount()) {
return false;
}
}
return true;
}
return false;
}
/**
* An implementation of {@link Multiset#addAll}.
*/
static <E> boolean addAllImpl(
Multiset<E> self, Collection<? extends E> elements) {
if (elements.isEmpty()) {
return false;
}
if (elements instanceof Multiset) {
Multiset<? extends E> that = cast(elements);
for (Entry<? extends E> entry : that.entrySet()) {
self.add(entry.getElement(), entry.getCount());
}
} else {
Iterators.addAll(self, elements.iterator());
}
return true;
}
/**
* An implementation of {@link Multiset#removeAll}.
*/
static boolean removeAllImpl(
Multiset<?> self, Collection<?> elementsToRemove) {
Collection<?> collection = (elementsToRemove instanceof Multiset)
? ((Multiset<?>) elementsToRemove).elementSet() : elementsToRemove;
return self.elementSet().removeAll(collection);
}
/**
* An implementation of {@link Multiset#retainAll}.
*/
static boolean retainAllImpl(
Multiset<?> self, Collection<?> elementsToRetain) {
checkNotNull(elementsToRetain);
Collection<?> collection = (elementsToRetain instanceof Multiset)
? ((Multiset<?>) elementsToRetain).elementSet() : elementsToRetain;
return self.elementSet().retainAll(collection);
}
/**
* An implementation of {@link Multiset#setCount(Object, int)}.
*/
static <E> int setCountImpl(Multiset<E> self, E element, int count) {
checkNonnegative(count, "count");
int oldCount = self.count(element);
int delta = count - oldCount;
if (delta > 0) {
self.add(element, delta);
} else if (delta < 0) {
self.remove(element, -delta);
}
return oldCount;
}
/**
* An implementation of {@link Multiset#setCount(Object, int, int)}.
*/
static <E> boolean setCountImpl(
Multiset<E> self, E element, int oldCount, int newCount) {
checkNonnegative(oldCount, "oldCount");
checkNonnegative(newCount, "newCount");
if (self.count(element) == oldCount) {
self.setCount(element, newCount);
return true;
} else {
return false;
}
}
abstract static class ElementSet<E> extends Sets.ImprovedAbstractSet<E> {
abstract Multiset<E> multiset();
@Override public void clear() {
multiset().clear();
}
@Override public boolean contains(Object o) {
return multiset().contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return multiset().containsAll(c);
}
@Override public boolean isEmpty() {
return multiset().isEmpty();
}
@Override public Iterator<E> iterator() {
return new TransformedIterator<Entry<E>, E>(multiset().entrySet().iterator()) {
@Override
E transform(Entry<E> entry) {
return entry.getElement();
}
};
}
@Override
public boolean remove(Object o) {
int count = multiset().count(o);
if (count > 0) {
multiset().remove(o, count);
return true;
}
return false;
}
@Override public int size() {
return multiset().entrySet().size();
}
}
abstract static class EntrySet<E> extends Sets.ImprovedAbstractSet<Entry<E>> {
abstract Multiset<E> multiset();
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Entry) {
/*
* The GWT compiler wrongly issues a warning here.
*/
@SuppressWarnings("cast")
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = multiset().count(entry.getElement());
return count == entry.getCount();
}
return false;
}
// GWT compiler warning; see contains().
@SuppressWarnings("cast")
@Override public boolean remove(Object object) {
if (object instanceof Multiset.Entry) {
Entry<?> entry = (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;
}
@Override public void clear() {
multiset().clear();
}
}
/**
* An implementation of {@link Multiset#iterator}.
*/
static <E> Iterator<E> iteratorImpl(Multiset<E> multiset) {
return new MultisetIteratorImpl<E>(
multiset, multiset.entrySet().iterator());
}
static final class MultisetIteratorImpl<E> implements Iterator<E> {
private final Multiset<E> multiset;
private final Iterator<Entry<E>> entryIterator;
private Entry<E> currentEntry;
/** Count of subsequent elements equal to current element */
private int laterCount;
/** Count of all elements equal to current element */
private int totalCount;
private boolean canRemove;
MultisetIteratorImpl(
Multiset<E> multiset, Iterator<Entry<E>> entryIterator) {
this.multiset = multiset;
this.entryIterator = entryIterator;
}
@Override
public boolean hasNext() {
return laterCount > 0 || entryIterator.hasNext();
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (laterCount == 0) {
currentEntry = entryIterator.next();
totalCount = laterCount = currentEntry.getCount();
}
laterCount--;
canRemove = true;
return currentEntry.getElement();
}
@Override
public void remove() {
checkRemove(canRemove);
if (totalCount == 1) {
entryIterator.remove();
} else {
multiset.remove(currentEntry.getElement());
}
totalCount--;
canRemove = false;
}
}
/**
* An implementation of {@link Multiset#size}.
*/
static int sizeImpl(Multiset<?> multiset) {
long size = 0;
for (Entry<?> entry : multiset.entrySet()) {
size += entry.getCount();
}
return Ints.saturatedCast(size);
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> Multiset<T> cast(Iterable<T> iterable) {
return (Multiset<T>) iterable;
}
private static final Ordering<Entry<?>> DECREASING_COUNT_ORDERING = new Ordering<Entry<?>>() {
@Override
public int compare(Entry<?> entry1, Entry<?> entry2) {
return Ints.compare(entry2.getCount(), entry1.getCount());
}
};
/**
* Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is
* highest count first, with ties broken by the iteration order of the original multiset.
*
* @since 11.0
*/
@Beta
public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
List<Entry<E>> sortedEntries =
Multisets.DECREASING_COUNT_ORDERING.immutableSortedCopy(multiset.entrySet());
return ImmutableMultiset.copyFromEntries(sortedEntries);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Multisets.java | Java | asf20 | 35,612 |
/*
* 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.Maps.keyOrNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* An immutable {@link SortedMap}. Does not permit null keys or values.
*
* <p>Unlike {@link Collections#unmodifiableSortedMap}, which is a <i>view</i>
* of a separate map which can still change, an instance of {@code
* ImmutableSortedMap} contains its own data and will <i>never</i> change.
* {@code ImmutableSortedMap} 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><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
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library; implements {@code
* NavigableMap} since 12.0)
*/
@GwtCompatible(serializable = true, emulated = true)
public abstract class ImmutableSortedMap<K, V>
extends ImmutableSortedMapFauxverideShim<K, V> implements NavigableMap<K, V> {
/*
* TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and
* uses less memory than TreeMap; then say so in the class Javadoc.
*/
private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural();
private static final ImmutableSortedMap<Comparable, Object> NATURAL_EMPTY_MAP =
new EmptyImmutableSortedMap<Comparable, Object>(NATURAL_ORDER);
static <K, V> ImmutableSortedMap<K, V> emptyMap(Comparator<? super K> comparator) {
if (Ordering.natural().equals(comparator)) {
return of();
} else {
return new EmptyImmutableSortedMap<K, V>(comparator);
}
}
static <K, V> ImmutableSortedMap<K, V> fromSortedEntries(
Comparator<? super K> comparator,
int size,
Entry<K, V>[] entries) {
if (size == 0) {
return emptyMap(comparator);
}
ImmutableList.Builder<K> keyBuilder = ImmutableList.builder();
ImmutableList.Builder<V> valueBuilder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
Entry<K, V> entry = entries[i];
keyBuilder.add(entry.getKey());
valueBuilder.add(entry.getValue());
}
return new RegularImmutableSortedMap<K, V>(
new RegularImmutableSortedSet<K>(keyBuilder.build(), comparator),
valueBuilder.build());
}
static <K, V> ImmutableSortedMap<K, V> from(
ImmutableSortedSet<K> keySet, ImmutableList<V> valueList) {
if (keySet.isEmpty()) {
return emptyMap(keySet.comparator());
} else {
return new RegularImmutableSortedMap<K, V>(
(RegularImmutableSortedSet<K>) keySet,
valueList);
}
}
/**
* Returns the empty sorted map.
*/
@SuppressWarnings("unchecked")
// unsafe, comparator() returns a comparator on the specified type
// TODO(kevinb): evaluate whether or not of().comparator() should return null
public static <K, V> ImmutableSortedMap<K, V> of() {
return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP;
}
/**
* Returns an immutable map containing a single entry.
*/
public static <K extends Comparable<? super K>, V>
ImmutableSortedMap<K, V> of(K k1, V v1) {
return from(ImmutableSortedSet.of(k1), ImmutableList.of(v1));
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if the two keys are equal according to
* their natural ordering
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2) {
return fromEntries(Ordering.natural(), false, 2, entryOf(k1, v1), entryOf(k2, v2));
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3) {
return fromEntries(Ordering.natural(), false, 3, entryOf(k1, v1), entryOf(k2, v2),
entryOf(k3, v3));
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return fromEntries(Ordering.natural(), false, 4, entryOf(k1, v1), entryOf(k2, v2),
entryOf(k3, v3), entryOf(k4, v4));
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
@SuppressWarnings("unchecked")
public static <K extends Comparable<? super 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) {
return fromEntries(Ordering.natural(), false, 5, entryOf(k1, v1), entryOf(k2, v2),
entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
}
/**
* Returns an immutable map containing the same entries as {@code map}, sorted
* by the natural ordering of the keys.
*
* <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 a map with keys
* that are not mutually comparable.
*
* @throws ClassCastException if the keys in {@code map} are not mutually
* comparable
* @throws NullPointerException if any key or value in {@code map} is null
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Map<? extends K, ? extends V> map) {
// Hack around K not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<K> naturalOrder = (Ordering<K>) Ordering.<Comparable>natural();
return copyOfInternal(map, naturalOrder);
}
/**
* Returns an immutable map containing the same entries as {@code map}, with
* keys sorted by the provided comparator.
*
* <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
* @throws IllegalArgumentException if any two keys are equal according to the
* comparator
*/
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
return copyOfInternal(map, checkNotNull(comparator));
}
/**
* Returns an immutable map containing the same entries as the provided sorted
* map, with the same ordering.
*
* <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
*/
@SuppressWarnings("unchecked")
public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(
SortedMap<K, ? extends V> map) {
Comparator<? super K> comparator = map.comparator();
if (comparator == null) {
// If map has a null comparator, the keys should have a natural ordering,
// even though K doesn't explicitly implement Comparable.
comparator = (Comparator<? super K>) NATURAL_ORDER;
}
return copyOfInternal(map, comparator);
}
private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
boolean sameComparator = false;
if (map instanceof SortedMap) {
SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) map;
Comparator<?> comparator2 = sortedMap.comparator();
sameComparator = (comparator2 == null)
? comparator == NATURAL_ORDER
: comparator.equals(comparator2);
}
if (sameComparator && (map instanceof ImmutableSortedMap)) {
// TODO(kevinb): Prove that this cast is safe, even though
// Collections.unmodifiableSortedMap requires the same key type.
@SuppressWarnings("unchecked")
ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
if (!kvMap.isPartialView()) {
return kvMap;
}
}
// "adding" type params to an array of a raw type should be safe as
// long as no one can ever cast that same array instance back to a
// raw type.
@SuppressWarnings("unchecked")
Entry<K, V>[] entries = map.entrySet().toArray(new Entry[0]);
return fromEntries(comparator, sameComparator, entries.length, entries);
}
static <K, V> ImmutableSortedMap<K, V> fromEntries(
Comparator<? super K> comparator, boolean sameComparator, int size, Entry<K, V>... entries) {
for (int i = 0; i < size; i++) {
Entry<K, V> entry = entries[i];
entries[i] = entryOf(entry.getKey(), entry.getValue());
}
if (!sameComparator) {
sortEntries(comparator, size, entries);
validateEntries(size, entries, comparator);
}
return fromSortedEntries(comparator, size, entries);
}
private static <K, V> void sortEntries(
final Comparator<? super K> comparator, int size, Entry<K, V>[] entries) {
Arrays.sort(entries, 0, size, Ordering.from(comparator).<K>onKeys());
}
private static <K, V> void validateEntries(int size, Entry<K, V>[] entries,
Comparator<? super K> comparator) {
for (int i = 1; i < size; i++) {
checkNoConflict(comparator.compare(entries[i - 1].getKey(), entries[i].getKey()) != 0, "key",
entries[i - 1], entries[i]);
}
}
/**
* Returns a builder that creates immutable sorted maps whose keys are
* ordered by their natural ordering. The sorted maps use {@link
* Ordering#natural()} as the comparator.
*/
public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() {
return new Builder<K, V>(Ordering.natural());
}
/**
* Returns a builder that creates immutable sorted maps with an explicit
* comparator. If the comparator has a more general type than the map's keys,
* such as creating a {@code SortedMap<Integer, String>} with a {@code
* Comparator<Number>}, use the {@link Builder} constructor instead.
*
* @throws NullPointerException if {@code comparator} is null
*/
public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) {
return new Builder<K, V>(comparator);
}
/**
* Returns a builder that creates immutable sorted maps whose keys are
* ordered by the reverse of their natural ordering.
*/
public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
return new Builder<K, V>(Ordering.natural().reverse());
}
/**
* A builder for creating immutable sorted map instances, especially {@code
* public static final} maps ("constant maps"). Example: <pre> {@code
*
* static final ImmutableSortedMap<Integer, String> INT_TO_WORD =
* new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural())
* .put(1, "one")
* .put(2, "two")
* .put(3, "three")
* .build();}</pre>
*
* <p>For <i>small</i> immutable sorted maps, the {@code ImmutableSortedMap.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> extends ImmutableMap.Builder<K, V> {
private final Comparator<? super K> comparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSortedMap#orderedBy}.
*/
@SuppressWarnings("unchecked")
public Builder(Comparator<? super K> comparator) {
this.comparator = checkNotNull(comparator);
}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys, according to the comparator (which might be the keys' natural
* order), 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;
}
/**
* Adds the given {@code entry} to the map, making it immutable if
* necessary. Duplicate keys, according to the comparator (which might be
* the keys' natural order), are not allowed, and will cause {@link #build}
* to fail.
*
* @since 11.0
*/
@Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
/**
* Associates all of the given map's keys and values in the built map.
* Duplicate keys, according to the comparator (which might be the keys'
* natural order), 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 sorted map.
*
* @throws IllegalArgumentException if any two keys are equal according to
* the comparator (which might be the keys' natural order)
*/
@Override public ImmutableSortedMap<K, V> build() {
return fromEntries(comparator, false, size, entries);
}
}
ImmutableSortedMap() {
}
ImmutableSortedMap(ImmutableSortedMap<K, V> descendingMap) {
this.descendingMap = descendingMap;
}
@Override
public int size() {
return values().size();
}
@Override public boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
@Override boolean isPartialView() {
return keySet().isPartialView() || values().isPartialView();
}
/**
* Returns an immutable set of the mappings in this map, sorted by the key
* ordering.
*/
@Override public ImmutableSet<Entry<K, V>> entrySet() {
return super.entrySet();
}
/**
* Returns an immutable sorted set of the keys in this map.
*/
@Override public abstract ImmutableSortedSet<K> keySet();
/**
* Returns an immutable collection of the values in this map, sorted by the
* ordering of the corresponding keys.
*/
@Override public abstract ImmutableCollection<V> values();
/**
* Returns the comparator that orders the keys, which is
* {@link Ordering#natural()} when the natural ordering of the keys is used.
* Note that its behavior is not consistent with {@link TreeMap#comparator()},
* which returns {@code null} to indicate natural ordering.
*/
@Override
public Comparator<? super K> comparator() {
return keySet().comparator();
}
@Override
public K firstKey() {
return keySet().first();
}
@Override
public K lastKey() {
return keySet().last();
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys are less than {@code toKey}.
*
* <p>The {@link SortedMap#headMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code toKey}
* greater than an earlier {@code toKey}. However, this method doesn't throw
* an exception in that situation, but instead keeps the original {@code
* toKey}.
*/
@Override
public ImmutableSortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys are less than (or equal to, if {@code inclusive}) {@code toKey}.
*
* <p>The {@link SortedMap#headMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code toKey}
* greater than an earlier {@code toKey}. However, this method doesn't throw
* an exception in that situation, but instead keeps the original {@code
* toKey}.
*
* @since 12.0
*/
@Override
public abstract ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive);
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys ranges from {@code fromKey}, inclusive, to {@code toKey},
* exclusive.
*
* <p>The {@link SortedMap#subMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code
* fromKey} less than an earlier {@code fromKey}. However, this method doesn't
* throw an exception in that situation, but instead keeps the original {@code
* fromKey}. Similarly, this method keeps the original {@code toKey}, instead
* of throwing an exception, if passed a {@code toKey} greater than an earlier
* {@code toKey}.
*/
@Override
public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys ranges from {@code fromKey} to {@code toKey}, inclusive or
* exclusive as indicated by the boolean flags.
*
* <p>The {@link SortedMap#subMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code
* fromKey} less than an earlier {@code fromKey}. However, this method doesn't
* throw an exception in that situation, but instead keeps the original {@code
* fromKey}. Similarly, this method keeps the original {@code toKey}, instead
* of throwing an exception, if passed a {@code toKey} greater than an earlier
* {@code toKey}.
*
* @since 12.0
*/
@Override
public ImmutableSortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive) {
checkNotNull(fromKey);
checkNotNull(toKey);
checkArgument(comparator().compare(fromKey, toKey) <= 0,
"expected fromKey <= toKey but %s > %s", fromKey, toKey);
return headMap(toKey, toInclusive).tailMap(fromKey, fromInclusive);
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys are greater than or equals to {@code fromKey}.
*
* <p>The {@link SortedMap#tailMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code
* fromKey} less than an earlier {@code fromKey}. However, this method doesn't
* throw an exception in that situation, but instead keeps the original {@code
* fromKey}.
*/
@Override
public ImmutableSortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys are greater than (or equal to, if {@code inclusive})
* {@code fromKey}.
*
* <p>The {@link SortedMap#tailMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code
* fromKey} less than an earlier {@code fromKey}. However, this method doesn't
* throw an exception in that situation, but instead keeps the original {@code
* fromKey}.
*
* @since 12.0
*/
@Override
public abstract ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive);
@Override
public Entry<K, V> lowerEntry(K key) {
return headMap(key, false).lastEntry();
}
@Override
public K lowerKey(K key) {
return keyOrNull(lowerEntry(key));
}
@Override
public Entry<K, V> floorEntry(K key) {
return headMap(key, true).lastEntry();
}
@Override
public K floorKey(K key) {
return keyOrNull(floorEntry(key));
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return tailMap(key, true).firstEntry();
}
@Override
public K ceilingKey(K key) {
return keyOrNull(ceilingEntry(key));
}
@Override
public Entry<K, V> higherEntry(K key) {
return tailMap(key, false).firstEntry();
}
@Override
public K higherKey(K key) {
return keyOrNull(higherEntry(key));
}
@Override
public Entry<K, V> firstEntry() {
return isEmpty() ? null : entrySet().asList().get(0);
}
@Override
public Entry<K, V> lastEntry() {
return isEmpty() ? null : entrySet().asList().get(size() - 1);
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
private transient ImmutableSortedMap<K, V> descendingMap;
@Override
public ImmutableSortedMap<K, V> descendingMap() {
ImmutableSortedMap<K, V> result = descendingMap;
if (result == null) {
result = descendingMap = createDescendingMap();
}
return result;
}
abstract ImmutableSortedMap<K, V> createDescendingMap();
@Override
public ImmutableSortedSet<K> navigableKeySet() {
return keySet();
}
@Override
public ImmutableSortedSet<K> descendingKeySet() {
return keySet().descendingSet();
}
/**
* Serialized type for all ImmutableSortedMap instances. It captures the
* logical contents and they are reconstructed using public factory methods.
* This ensures that the implementation types remain as implementation
* details.
*/
private static class SerializedForm extends ImmutableMap.SerializedForm {
private final Comparator<Object> comparator;
@SuppressWarnings("unchecked")
SerializedForm(ImmutableSortedMap<?, ?> sortedMap) {
super(sortedMap);
comparator = (Comparator<Object>) sortedMap.comparator();
}
@Override Object readResolve() {
Builder<Object, Object> builder = new Builder<Object, Object>(comparator);
return createMap(builder);
}
private static final long serialVersionUID = 0;
}
@Override Object writeReplace() {
return new SerializedForm(this);
}
// 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSortedMap.java | Java | asf20 | 24,682 |
/*
* 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;
/**
* "Overrides" the {@link ImmutableMap} static methods that lack
* {@link ImmutableSortedMap} equivalents with deprecated, exception-throwing
* versions. See {@link ImmutableSortedSetFauxverideShim} for details.
*
* @author Chris Povirk
*/
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.
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableSortedMapFauxverideShim.java | Java | asf20 | 4,640 |
/*
* 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 javax.annotation.Nullable;
/**
* A constraint on the keys and values that may be added to a {@code Map} or
* {@code Multimap}. For example, {@link MapConstraints#notNull()}, which
* prevents a map from including any null keys or values, could be implemented
* like this: <pre> {@code
*
* public void checkKeyValue(Object key, Object value) {
* if (key == null || value == null) {
* throw new NullPointerException();
* }
* }}</pre>
*
* <p>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 key
* and value. 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.
*
* @author Mike Bostock
* @see MapConstraints
* @see Constraint
* @since 3.0
*/
@GwtCompatible
@Beta
public interface MapConstraint<K, V> {
/**
* Throws a suitable {@code RuntimeException} if the specified key or value 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.
*/
void checkKeyValue(@Nullable K key, @Nullable V value);
/**
* Returns a brief human readable description of this constraint, such as
* "Not null".
*/
@Override
String toString();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/MapConstraint.java | Java | asf20 | 2,307 |
/*
* 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 java.util.Map;
/**
* An implementation of {@link ImmutableTable} that holds a single cell.
*
* @author Gregory Kick
*/
@GwtCompatible
class SingletonImmutableTable<R, C, V> extends ImmutableTable<R, C, V> {
final R singleRowKey;
final C singleColumnKey;
final V singleValue;
SingletonImmutableTable(R rowKey, C columnKey, V value) {
this.singleRowKey = checkNotNull(rowKey);
this.singleColumnKey = checkNotNull(columnKey);
this.singleValue = checkNotNull(value);
}
SingletonImmutableTable(Cell<R, C, V> cell) {
this(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
return containsColumn(columnKey)
? ImmutableMap.of(singleRowKey, singleValue)
: ImmutableMap.<R, V>of();
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
return ImmutableMap.of(singleColumnKey,
(Map<R, V>) ImmutableMap.of(singleRowKey, singleValue));
}
@Override public ImmutableMap<R, Map<C, V>> rowMap() {
return ImmutableMap.of(singleRowKey,
(Map<C, V>) ImmutableMap.of(singleColumnKey, singleValue));
}
@Override public int size() {
return 1;
}
@Override
ImmutableSet<Cell<R, C, V>> createCellSet() {
return ImmutableSet.of(
cellOf(singleRowKey, singleColumnKey, singleValue));
}
@Override ImmutableCollection<V> createValues() {
return ImmutableSet.of(singleValue);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SingletonImmutableTable.java | Java | asf20 | 2,245 |
/*
* 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 static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
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.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
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.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} backed by {@code map}, whose internal value
* collections are generated by {@code factory}.
*
* <b>Warning: do not use</b> this method when the collections returned by
* {@code factory} implement either {@link List} or {@code Set}! Use the more
* specific method {@link #newListMultimap}, {@link #newSetMultimap} or {@link
* #newSortedSetMultimap} instead, to avoid very surprising behavior from
* {@link Multimap#equals}.
*
* <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 AbstractMapBasedMultimap<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> multimap = Multimaps.synchronizedMultimap(
* HashMultimap.<K, V>create());
* ...
* Collection<V> values = multimap.get(key); // Needn't be in synchronized block
* ...
* synchronized (multimap) { // Synchronizing on multimap, not values!
* Iterator<V> i = values.iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }}</pre>
*
* <p>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) {
result = map = Collections.unmodifiableMap(
Maps.transformValues(delegate.asMap(), new Function<Collection<V>, Collection<V>>() {
@Override
public Collection<V> apply(Collection<V> collection) {
return unmodifiableValueCollection(collection);
}
}));
}
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 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 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 {@link ListMultimap#asMap multimap.asMap()}, with its type
* corrected from {@code Map<K, Collection<V>>} to {@code Map<K, List<V>>}.
*
* @since 15.0
*/
@Beta
@SuppressWarnings("unchecked")
// safe by specification of ListMultimap.asMap()
public static <K, V> Map<K, List<V>> asMap(ListMultimap<K, V> multimap) {
return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap();
}
/**
* Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected
* from {@code Map<K, Collection<V>>} to {@code Map<K, Set<V>>}.
*
* @since 15.0
*/
@Beta
@SuppressWarnings("unchecked")
// safe by specification of SetMultimap.asMap()
public static <K, V> Map<K, Set<V>> asMap(SetMultimap<K, V> multimap) {
return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap();
}
/**
* Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type
* corrected from {@code Map<K, Collection<V>>} to
* {@code Map<K, SortedSet<V>>}.
*
* @since 15.0
*/
@Beta
@SuppressWarnings("unchecked")
// safe by specification of SortedSetMultimap.asMap()
public static <K, V> Map<K, SortedSet<V>> asMap(
SortedSetMultimap<K, V> multimap) {
return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap();
}
/**
* Returns {@link Multimap#asMap multimap.asMap()}. This is provided for
* parity with the other more strongly-typed {@code asMap()} implementations.
*
* @since 15.0
*/
@Beta
public static <K, V> Map<K, Collection<V>> asMap(Multimap<K, V> multimap) {
return multimap.asMap();
}
/**
* 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>
extends AbstractMultimap<K, V> implements SetMultimap<K, V>, Serializable {
final Map<K, V> map;
MapMultimap(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public int size() {
return map.size();
}
@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 Sets.ImprovedAbstractSet<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() {
checkRemove(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 Collection<V> values() {
return map.values();
}
@Override
public Set<Entry<K, V>> entries() {
return map.entrySet();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return map.entrySet().iterator();
}
@Override
Map<K, Collection<V>> createAsMap() {
return new AsMap<K, V>(this);
}
@Override public int hashCode() {
return map.hashCode();
}
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=[36]}}.
*
* <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
*/
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 = Maps.asEntryTransformer(function);
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
*/
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>
extends AbstractMultimap<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(K key, Collection<V1> values) {
Function<? super V1, V2> function =
Maps.asValueToValueFunction(transformer, key);
if (values instanceof List) {
return Lists.transform((List<V1>) values, function);
} else {
return Collections2.transform(values, function);
}
}
@Override
Map<K, Collection<V2>> createAsMap() {
return 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);
}
});
}
@Override public void clear() {
fromMultimap.clear();
}
@Override public boolean containsKey(Object key) {
return fromMultimap.containsKey(key);
}
@Override
Iterator<Entry<K, V2>> entryIterator() {
return Iterators.transform(fromMultimap.entries().iterator(),
Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
@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();
}
@Override
Collection<V2> createValues() {
return Collections2.transform(
fromMultimap.entries(), Maps.<K, V1, V2>asEntryToValueFunction(transformer));
}
}
/**
* 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
*/
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 = Maps.asEntryTransformer(function);
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
*/
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(K key, Collection<V1> values) {
return Lists.transform((List<V1>) values, Maps.asValueToValueFunction(transformer, key));
}
@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>
*
* <p>prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* <p>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);
}
/**
* 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>
*
* <p>prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* <p>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 class Keys<K, V> extends AbstractMultiset<K> {
final Multimap<K, V> multimap;
Keys(Multimap<K, V> multimap) {
this.multimap = multimap;
}
@Override Iterator<Multiset.Entry<K>> entryIterator() {
return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>(
multimap.asMap().entrySet().iterator()) {
@Override
Multiset.Entry<K> transform(
final Map.Entry<K, Collection<V>> backingEntry) {
return new Multisets.AbstractEntry<K>() {
@Override
public K getElement() {
return backingEntry.getKey();
}
@Override
public int getCount() {
return backingEntry.getValue().size();
}
};
}
};
}
@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 Maps.keyIterator(multimap.entries().iterator());
}
@Override public int count(@Nullable Object element) {
Collection<V> values = Maps.safeGet(multimap.asMap(), element);
return (values == null) ? 0 : values.size();
}
@Override public int remove(@Nullable Object element, int occurrences) {
checkNonnegative(occurrences, "occurrences");
if (occurrences == 0) {
return count(element);
}
Collection<V> values = Maps.safeGet(multimap.asMap(), element);
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();
}
}
/**
* A skeleton implementation of {@link Multimap#entries()}.
*/
abstract static 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 Multimap#asMap()}.
*/
static final class AsMap<K, V> extends
Maps.ImprovedAbstractMap<K, Collection<V>> {
private final Multimap<K, V> multimap;
AsMap(Multimap<K, V> multimap) {
this.multimap = checkNotNull(multimap);
}
@Override public int size() {
return multimap.keySet().size();
}
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new EntrySet();
}
void removeValuesForKey(Object key) {
multimap.keySet().remove(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 Maps.asMapEntryIterator(multimap.keySet(), new Function<K, Collection<V>>() {
@Override
public Collection<V> apply(K key) {
return multimap.get(key);
}
});
}
@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 {@code 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
*/
public static <K, V> Multimap<K, V> filterKeys(
Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof SetMultimap) {
return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate);
} else if (unfiltered instanceof ListMultimap) {
return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate);
} else if (unfiltered instanceof FilteredKeyMultimap) {
FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered;
return new FilteredKeyMultimap<K, V>(prev.unfiltered,
Predicates.and(prev.keyPredicate, keyPredicate));
} else if (unfiltered instanceof FilteredMultimap) {
FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered;
return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
} else {
return new FilteredKeyMultimap<K, V>(unfiltered, keyPredicate);
}
}
/**
* 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 {@code 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 14.0
*/
public static <K, V> SetMultimap<K, V> filterKeys(
SetMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof FilteredKeySetMultimap) {
FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered;
return new FilteredKeySetMultimap<K, V>(prev.unfiltered(),
Predicates.and(prev.keyPredicate, keyPredicate));
} else if (unfiltered instanceof FilteredSetMultimap) {
FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered;
return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
} else {
return new FilteredKeySetMultimap<K, V>(unfiltered, keyPredicate);
}
}
/**
* 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 {@code 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 14.0
*/
public static <K, V> ListMultimap<K, V> filterKeys(
ListMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof FilteredKeyListMultimap) {
FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered;
return new FilteredKeyListMultimap<K, V>(prev.unfiltered(),
Predicates.and(prev.keyPredicate, keyPredicate));
} else {
return new FilteredKeyListMultimap<K, V>(unfiltered, keyPredicate);
}
}
/**
* 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 {@code 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
*/
public static <K, V> Multimap<K, V> filterValues(
Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* 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 {@code 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 14.0
*/
public static <K, V> SetMultimap<K, V> filterValues(
SetMultimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* 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 {@code 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
*/
public static <K, V> Multimap<K, V> filterEntries(
Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
if (unfiltered instanceof SetMultimap) {
return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate);
}
return (unfiltered instanceof FilteredMultimap)
? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMultimap<K, V>(checkNotNull(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 {@code 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 14.0
*/
public static <K, V> SetMultimap<K, V> filterEntries(
SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredSetMultimap)
? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySetMultimap<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 FilteredEntryMultimap 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> multimap,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(multimap.entryPredicate(), entryPredicate);
return new FilteredEntryMultimap<K, V>(multimap.unfiltered(), predicate);
}
/**
* Support removal operations when filtering a filtered multimap. Since a filtered multimap has
* iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would
* lead to a multimap whose removal operations would fail. This method combines the predicates to
* avoid that problem.
*/
private static <K, V> SetMultimap<K, V> filterFiltered(
FilteredSetMultimap<K, V> multimap,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(multimap.entryPredicate(), entryPredicate);
return new FilteredEntrySetMultimap<K, V>(multimap.unfiltered(), predicate);
}
static boolean equalsImpl(Multimap<?, ?> multimap, @Nullable Object object) {
if (object == multimap) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return multimap.asMap().equals(that.asMap());
}
return false;
}
// TODO(jlevy): Create methods that filter a SortedSetMultimap.
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Multimaps.java | Java | asf20 | 78,583 |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
/**
* A {@code RegularImmutableTable} optimized for sparse data.
*/
@GwtCompatible
@Immutable
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;
private final int[] iterationOrderRow;
private final int[] iterationOrderColumn;
SparseImmutableTable(ImmutableList<Cell<R, C, V>> cellList,
ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) {
Map<R, Integer> rowIndex = Maps.newHashMap();
Map<R, Map<C, V>> rows = Maps.newLinkedHashMap();
for (R row : rowSpace) {
rowIndex.put(row, rows.size());
rows.put(row, new LinkedHashMap<C, V>());
}
Map<C, Map<R, V>> columns = Maps.newLinkedHashMap();
for (C col : columnSpace) {
columns.put(col, new LinkedHashMap<R, V>());
}
int[] iterationOrderRow = new int[cellList.size()];
int[] iterationOrderColumn = new int[cellList.size()];
for (int i = 0; i < cellList.size(); i++) {
Cell<R, C, V> cell = cellList.get(i);
R rowKey = cell.getRowKey();
C columnKey = cell.getColumnKey();
V value = cell.getValue();
iterationOrderRow[i] = rowIndex.get(rowKey);
Map<C, V> thisRow = rows.get(rowKey);
iterationOrderColumn[i] = thisRow.size();
V oldValue = thisRow.put(columnKey, value);
if (oldValue != null) {
throw new IllegalArgumentException("Duplicate value for row=" + rowKey + ", column="
+ columnKey + ": " + value + ", " + oldValue);
}
columns.get(columnKey).put(rowKey, value);
}
this.iterationOrderRow = iterationOrderRow;
this.iterationOrderColumn = iterationOrderColumn;
ImmutableMap.Builder<R, Map<C, V>> rowBuilder = ImmutableMap.builder();
for (Map.Entry<R, Map<C, V>> row : rows.entrySet()) {
rowBuilder.put(row.getKey(), ImmutableMap.copyOf(row.getValue()));
}
this.rowMap = rowBuilder.build();
ImmutableMap.Builder<C, Map<R, V>> columnBuilder = ImmutableMap.builder();
for (Map.Entry<C, Map<R, V>> col : columns.entrySet()) {
columnBuilder.put(col.getKey(), ImmutableMap.copyOf(col.getValue()));
}
this.columnMap = columnBuilder.build();
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
return columnMap;
}
@Override public ImmutableMap<R, Map<C, V>> rowMap() {
return rowMap;
}
@Override
public int size() {
return iterationOrderRow.length;
}
@Override
Cell<R, C, V> getCell(int index) {
int rowIndex = iterationOrderRow[index];
Map.Entry<R, Map<C, V>> rowEntry = rowMap.entrySet().asList().get(rowIndex);
ImmutableMap<C, V> row = (ImmutableMap<C, V>) rowEntry.getValue();
int columnIndex = iterationOrderColumn[index];
Map.Entry<C, V> colEntry = row.entrySet().asList().get(columnIndex);
return cellOf(rowEntry.getKey(), colEntry.getKey(), colEntry.getValue());
}
@Override
V getValue(int index) {
int rowIndex = iterationOrderRow[index];
ImmutableMap<C, V> row = (ImmutableMap<C, V>) rowMap.values().asList().get(rowIndex);
int columnIndex = iterationOrderColumn[index];
return row.values().asList().get(columnIndex);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SparseImmutableTable.java | Java | asf20 | 4,028 |
/*
* 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;
import javax.annotation.Nullable;
/** An ordering that uses the reverse of a given order. */
@GwtCompatible(serializable = true)
final class ReverseOrdering<T> extends Ordering<T> implements Serializable {
final Ordering<? super T> forwardOrder;
ReverseOrdering(Ordering<? super T> forwardOrder) {
this.forwardOrder = checkNotNull(forwardOrder);
}
@Override public int compare(T a, T b) {
return forwardOrder.compare(b, a);
}
@SuppressWarnings("unchecked") // how to explain?
@Override public <S extends T> Ordering<S> reverse() {
return (Ordering<S>) forwardOrder;
}
// Override the min/max methods to "hoist" delegation outside loops
@Override public <E extends T> E min(E a, E b) {
return forwardOrder.max(a, b);
}
@Override public <E extends T> E min(E a, E b, E c, E... rest) {
return forwardOrder.max(a, b, c, rest);
}
@Override public <E extends T> E min(Iterator<E> iterator) {
return forwardOrder.max(iterator);
}
@Override public <E extends T> E min(Iterable<E> iterable) {
return forwardOrder.max(iterable);
}
@Override public <E extends T> E max(E a, E b) {
return forwardOrder.min(a, b);
}
@Override public <E extends T> E max(E a, E b, E c, E... rest) {
return forwardOrder.min(a, b, c, rest);
}
@Override public <E extends T> E max(Iterator<E> iterator) {
return forwardOrder.min(iterator);
}
@Override public <E extends T> E max(Iterable<E> iterable) {
return forwardOrder.min(iterable);
}
@Override public int hashCode() {
return -forwardOrder.hashCode();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof ReverseOrdering) {
ReverseOrdering<?> that = (ReverseOrdering<?>) object;
return this.forwardOrder.equals(that.forwardOrder);
}
return false;
}
@Override public String toString() {
return forwardOrder + ".reverse()";
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ReverseOrdering.java | Java | asf20 | 2,847 |
/*
* 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.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.lang.reflect.Array;
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 {
static final Object[] EMPTY_ARRAY = new Object[0];
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)")
@SuppressWarnings("unchecked")
public static <T> T[] newArray(Class<T> type, int length) {
return (T[]) Array.newInstance(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);
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(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;
System.arraycopy(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);
System.arraycopy(
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;
}
/**
* Implementation of {@link Collection#toArray(Object[])} for collections backed by an object
* array. 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.
*/
static <T> T[] toArrayImpl(Object[] src, int offset, int len, T[] dst) {
checkPositionIndexes(offset, offset + len, src.length);
if (dst.length < len) {
dst = newArray(dst, len);
} else if (dst.length > len) {
dst[len] = null;
}
System.arraycopy(src, offset, dst, 0, len);
return dst;
}
/**
* 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()]);
}
/**
* Returns a copy of the specified subrange of the specified array that is literally an Object[],
* and not e.g. a {@code String[]}.
*/
static Object[] copyAsObjectArray(Object[] elements, int offset, int length) {
checkPositionIndexes(offset, offset + length, elements.length);
if (length == 0) {
return EMPTY_ARRAY;
}
Object[] result = new Object[length];
System.arraycopy(elements, offset, result, 0, length);
return result;
}
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;
}
static Object[] checkElementsNotNull(Object... array) {
return checkElementsNotNull(array, array.length);
}
static Object[] checkElementsNotNull(Object[] array, int length) {
for (int i = 0; i < length; i++) {
checkElementNotNull(array[i], i);
}
return array;
}
// We do this instead of Preconditions.checkNotNull to save boxing and array
// creation cost.
static Object checkElementNotNull(Object element, int index) {
if (element == null) {
throw new NullPointerException("at index " + index);
}
return element;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ObjectArrays.java | Java | asf20 | 8,805 |
/*
* 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
* @deprecated This class existed only to support the generic paramterization necessary for the
* caching functionality in {@code MapMaker}. That functionality has been moved to {@link
* com.google.common.cache.CacheBuilder}, which is a properly generified class and thus needs no
* "Generic" equivalent; simple use {@code CacheBuilder} naturally. For general migration
* instructions, see the <a
* href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker Migration
* Guide</a>.
*/
@Beta
@Deprecated
@GwtCompatible(emulated = true)
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#initialCapacity}.
*/
public abstract GenericMapMaker<K0, V0> initialCapacity(int initialCapacity);
/**
* See {@link MapMaker#maximumSize}.
*/
abstract GenericMapMaker<K0, V0> maximumSize(int maximumSize);
/**
* 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#weakValues}.
*/
@GwtIncompatible("java.lang.ref.WeakReference")
public abstract GenericMapMaker<K0, V0> weakValues();
/**
* See {@link MapMaker#softValues}.
*
* @deprecated Caching functionality in {@code MapMaker} has been moved to {@link
* com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link
* com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply
* an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This
* method is scheduled for deletion in August 2014.</b>
*/
@Deprecated
@GwtIncompatible("java.lang.ref.SoftReference")
public abstract GenericMapMaker<K0, V0> softValues();
/**
* 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
abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction);
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/GenericMapMaker.java | Java | asf20 | 5,338 |
/*
* 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
int copyIntoArray(Object[] dst, int offset) {
dst[offset] = element;
return offset + 1;
}
@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();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SingletonImmutableSet.java | Java | asf20 | 3,163 |
/*
* 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;
/**
* Indicates whether an endpoint of some range is contained in the range itself ("closed") or not
* ("open"). If a range is unbounded on a side, it is neither open nor closed on that side; the
* bound simply does not exist.
*
* @since 10.0
*/
@GwtCompatible
public enum BoundType {
/**
* The endpoint value <i>is not</i> considered part of the set ("exclusive").
*/
OPEN {
@Override
BoundType flip() {
return CLOSED;
}
},
/**
* The endpoint value <i>is</i> considered part of the set ("inclusive").
*/
CLOSED {
@Override
BoundType flip() {
return OPEN;
}
};
/**
* Returns the bound type corresponding to a boolean value for inclusivity.
*/
static BoundType forBoolean(boolean inclusive) {
return inclusive ? CLOSED : OPEN;
}
abstract BoundType flip();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/BoundType.java | Java | asf20 | 1,528 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
import javax.annotation.Nullable;
/**
* Skeletal implementation of {@link ImmutableSortedSet#descendingSet()}.
*
* @author Louis Wasserman
*/
class DescendingImmutableSortedSet<E> extends ImmutableSortedSet<E> {
private final ImmutableSortedSet<E> forward;
DescendingImmutableSortedSet(ImmutableSortedSet<E> forward) {
super(Ordering.from(forward.comparator()).reverse());
this.forward = forward;
}
@Override
public int size() {
return forward.size();
}
@Override
public UnmodifiableIterator<E> iterator() {
return forward.descendingIterator();
}
@Override
ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) {
return forward.tailSet(toElement, inclusive).descendingSet();
}
@Override
ImmutableSortedSet<E> subSetImpl(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
}
@Override
ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) {
return forward.headSet(fromElement, inclusive).descendingSet();
}
@Override
@GwtIncompatible("NavigableSet")
public ImmutableSortedSet<E> descendingSet() {
return forward;
}
@Override
@GwtIncompatible("NavigableSet")
public UnmodifiableIterator<E> descendingIterator() {
return forward.iterator();
}
@Override
@GwtIncompatible("NavigableSet")
ImmutableSortedSet<E> createDescendingSet() {
throw new AssertionError("should never be called");
}
@Override
public E lower(E element) {
return forward.higher(element);
}
@Override
public E floor(E element) {
return forward.ceiling(element);
}
@Override
public E ceiling(E element) {
return forward.floor(element);
}
@Override
public E higher(E element) {
return forward.lower(element);
}
@Override
int indexOf(@Nullable Object target) {
int index = forward.indexOf(target);
if (index == -1) {
return index;
} else {
return size() - 1 - index;
}
}
@Override
boolean isPartialView() {
return forward.isPartialView();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/DescendingImmutableSortedSet.java | Java | asf20 | 2,847 |
/*
* 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;
/**
* A map, each entry of which maps a Java
* <a href="http://tinyurl.com/2cmwkz">raw type</a> to an instance of that type.
* In addition to implementing {@code Map}, the additional type-safe operations
* {@link #putInstance} and {@link #getInstance} are available.
*
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries
* for primitive types, and a primitive type and its corresponding wrapper type
* may map to different values.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#ClassToInstanceMap">
* {@code ClassToInstanceMap}</a>.
*
* <p>To map a generic type to an instance of that type, use {@link
* com.google.common.reflect.TypeToInstanceMap} instead.
*
* @param <B> the common supertype that all entries must share; often this is
* simply {@link Object}
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no
* entry for this class is present. This will only return a value that was
* bound to this specific class, not a value that may have been bound to a
* subtype.
*/
<T extends B> T getInstance(Class<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate
* this value with any of the class's supertypes.
*
* @return the value previously associated with this class (possibly {@code
* null}), or {@code null} if there was no previous entry.
*/
<T extends B> T putInstance(Class<T> type, @Nullable T value);
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ClassToInstanceMap.java | Java | asf20 | 2,489 |
/*
* 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.util.Collection;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A set which forwards all its method calls to another set. Subclasses should
* override one or more methods to modify the behavior of the backing set as
* desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingSet} 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 ForwardingSet<E> extends ForwardingCollection<E>
implements Set<E> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingSet() {}
@Override protected abstract Set<E> delegate();
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
/**
* A sensible definition of {@link #removeAll} in terms of {@link #iterator}
* and {@link #remove}. If you override {@code iterator} or {@code remove},
* you may wish to override {@link #removeAll} to forward to this
* implementation.
*
* @since 7.0 (this version overrides the {@code ForwardingCollection} version as of 12.0)
*/
@Override
protected boolean standardRemoveAll(Collection<?> collection) {
return Sets.removeAllImpl(this, checkNotNull(collection)); // for GWT
}
/**
* A sensible definition of {@link #equals} in terms of {@link #size} and
* {@link #containsAll}. If you override either of those methods, you may wish
* to override {@link #equals} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardEquals(@Nullable Object object) {
return Sets.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 #equals}
* to forward to this implementation.
*
* @since 7.0
*/
protected int standardHashCode() {
return Sets.hashCodeImpl(this);
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ForwardingSet.java | Java | asf20 | 3,509 |
/*
* 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 java.util.Set;
import javax.annotation.Nullable;
/**
* A bimap (or "bidirectional map") is a map that preserves the uniqueness of
* its values as well as that of its keys. This constraint enables bimaps to
* support an "inverse view", which is another bimap containing the same entries
* as this bimap but with reversed keys and values.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface BiMap<K, V> extends Map<K, V> {
// Modification Operations
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the given value is already bound to a
* different key in this bimap. The bimap will remain unmodified in this
* event. To avoid this exception, call {@link #forcePut} instead.
*/
@Override
V put(@Nullable K key, @Nullable V value);
/**
* An alternate form of {@code put} that silently removes any existing entry
* with the value {@code value} before proceeding with the {@link #put}
* operation. If the bimap previously contained the provided key-value
* mapping, this method has no effect.
*
* <p>Note that a successful call to this method could cause the size of the
* bimap to increase by one, stay the same, or even decrease by one.
*
* <p><b>Warning:</b> If an existing entry with this value is removed, the key
* for that entry is discarded and not returned.
*
* @param key the key with which the specified value is to be associated
* @param value the value to be associated with the specified key
* @return the value which was previously associated with the key, which may
* be {@code null}, or {@code null} if there was no previous entry
*/
V forcePut(@Nullable K key, @Nullable V value);
// Bulk Operations
/**
* {@inheritDoc}
*
* <p><b>Warning:</b> the results of calling this method may vary depending on
* the iteration order of {@code map}.
*
* @throws IllegalArgumentException if an attempt to {@code put} any
* entry fails. Note that some map entries may have been added to the
* bimap before the exception was thrown.
*/
@Override
void putAll(Map<? extends K, ? extends V> map);
// Views
/**
* {@inheritDoc}
*
* <p>Because a bimap has unique values, this method returns a {@link Set},
* instead of the {@link java.util.Collection} specified in the {@link Map}
* interface.
*/
@Override
Set<V> values();
/**
* Returns the inverse view of this bimap, which maps each of this bimap's
* values to its associated key. The two bimaps are backed by the same data;
* any changes to one will appear in the other.
*
* <p><b>Note:</b>There is no guaranteed correspondence between the iteration
* order of a bimap and that of its inverse.
*
* @return the inverse view of this bimap
*/
BiMap<V, K> inverse();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/BiMap.java | Java | asf20 | 3,781 |
/*
* 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.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Interface that extends {@code Table} and whose rows are sorted.
*
* <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.
*
* @author Warren Dukes
* @since 8.0
*/
@GwtCompatible
@Beta
public interface RowSortedTable<R, C, V> extends Table<R, C, V> {
/**
* {@inheritDoc}
*
* <p>This method returns a {@link SortedSet}, instead of the {@code Set}
* specified in the {@link Table} interface.
*/
@Override SortedSet<R> rowKeySet();
/**
* {@inheritDoc}
*
* <p>This method returns a {@link SortedMap}, instead of the {@code Map}
* specified in the {@link Table} interface.
*/
@Override SortedMap<R, Map<C, V>> rowMap();
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/RowSortedTable.java | Java | asf20 | 1,661 |
/*
* 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.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
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.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, Count>}.
*
* <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();
}
/** 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() {
Count count = mapEntry.getValue();
if (count == null || count.get() == 0) {
Count frequency = backingMap.get(getElement());
if (frequency != null) {
return frequency.get();
}
}
return (count == null) ? 0 : count.get();
}
};
}
@Override
public void remove() {
checkRemove(toRemove != null);
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, Count> 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() {
checkRemove(canRemove);
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) {
Count frequency = Maps.safeGet(backingMap, element);
return (frequency == null) ? 0 : frequency.get();
}
// 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(@Nullable 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);
}
// 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractMapBasedMultiset.java | Java | asf20 | 8,664 |
/*
* 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;
/**
* Basic implementation of the {@link ListMultimap} interface. It's a wrapper
* around {@link AbstractMapBasedMultimap} that converts the returned collections into
* {@code Lists}. The {@link #createCollection} method must return a {@code
* List}.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
abstract class AbstractListMultimap<K, V>
extends AbstractMapBasedMultimap<K, V> implements ListMultimap<K, V> {
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
*/
protected AbstractListMultimap(Map<K, Collection<V>> map) {
super(map);
}
@Override abstract List<V> createCollection();
@Override
List<V> createUnmodifiableEmptyCollection() {
return ImmutableList.of();
}
// Following Javadoc copied from ListMultimap.
/**
* {@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 Collection} specified in the {@link Multimap} interface.
*/
@Override public List<V> get(@Nullable K key) {
return (List<V>) super.get(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 Collection} specified in the {@link Multimap} interface.
*/
@Override public List<V> removeAll(@Nullable Object key) {
return (List<V>) super.removeAll(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 Collection} specified in the {@link Multimap} interface.
*/
@Override public List<V> replaceValues(
@Nullable K key, Iterable<? extends V> values) {
return (List<V>) super.replaceValues(key, values);
}
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} always
*/
@Override public boolean put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
/**
* {@inheritDoc}
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link List} values.
*/
@Override public Map<K, Collection<V>> asMap() {
return super.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.
*/
@Override public boolean equals(@Nullable Object object) {
return super.equals(object);
}
private static final long serialVersionUID = 6588350623831699109L;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractListMultimap.java | Java | asf20 | 3,840 |
/*
* 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.Collection;
import java.util.Comparator;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.annotation.Nullable;
/**
* Implementation of {@code Multimap} whose keys and values are ordered by
* their natural ordering or by supplied comparators. 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 comparators or comparables used must be <i>consistent
* with equals</i> as explained by the {@link Comparable} class specification.
* Otherwise, the resulting multiset will violate the general contract of {@link
* SetMultimap}, which it is specified in terms of {@link Object#equals}.
*
* <p>The collections returned by {@code keySet} and {@code asMap} iterate
* through the keys according to the key comparator ordering or the natural
* ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code
* replaceValues} return collections that iterate through the values according
* to the value comparator ordering or the natural ordering of the values. The
* collections generated by {@code entries}, {@code keys}, and {@code values}
* iterate across the keys according to the above key ordering, and for each
* key they iterate across the values according to the value ordering.
*
* <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>Null keys and values are permitted (provided, of course, that the
* respective comparators support them). 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#synchronizedSortedSetMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class TreeMultimap<K, V> extends AbstractSortedKeySortedSetMultimap<K, V> {
private transient Comparator<? super K> keyComparator;
private transient Comparator<? super V> valueComparator;
/**
* Creates an empty {@code TreeMultimap} ordered by the natural ordering of
* its keys and values.
*/
public static <K extends Comparable, V extends Comparable>
TreeMultimap<K, V> create() {
return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural());
}
/**
* Creates an empty {@code TreeMultimap} instance using explicit comparators.
* Neither comparator may be null; use {@link Ordering#natural()} to specify
* natural order.
*
* @param keyComparator the comparator that determines the key ordering
* @param valueComparator the comparator that determines the value ordering
*/
public static <K, V> TreeMultimap<K, V> create(
Comparator<? super K> keyComparator,
Comparator<? super V> valueComparator) {
return new TreeMultimap<K, V>(checkNotNull(keyComparator),
checkNotNull(valueComparator));
}
/**
* Constructs a {@code TreeMultimap}, ordered by the natural ordering of its
* keys and values, with the same mappings as the specified multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K extends Comparable, V extends Comparable>
TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(),
multimap);
}
TreeMultimap(Comparator<? super K> keyComparator,
Comparator<? super V> valueComparator) {
super(new TreeMap<K, Collection<V>>(keyComparator));
this.keyComparator = keyComparator;
this.valueComparator = valueComparator;
}
private TreeMultimap(Comparator<? super K> keyComparator,
Comparator<? super V> valueComparator,
Multimap<? extends K, ? extends V> multimap) {
this(keyComparator, valueComparator);
putAll(multimap);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code TreeSet} for a collection of values for one key.
*
* @return a new {@code TreeSet} containing a collection of values for one
* key
*/
@Override SortedSet<V> createCollection() {
return new TreeSet<V>(valueComparator);
}
@Override
Collection<V> createCollection(@Nullable K key) {
if (key == null) {
keyComparator().compare(key, key);
}
return super.createCollection(key);
}
/**
* Returns the comparator that orders the multimap keys.
*/
public Comparator<? super K> keyComparator() {
return keyComparator;
}
@Override
public Comparator<? super V> valueComparator() {
return valueComparator;
}
/*
* The following @GwtIncompatible methods override the methods in
* AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM implementations,
* which return SortedSets and SortedMaps.
*/
@Override
@GwtIncompatible("NavigableMap")
NavigableMap<K, Collection<V>> backingMap() {
return (NavigableMap<K, Collection<V>>) super.backingMap();
}
/**
* @since 14.0 (present with return type {@code SortedSet} since 2.0)
*/
@Override
@GwtIncompatible("NavigableSet")
public NavigableSet<V> get(@Nullable K key) {
return (NavigableSet<V>) super.get(key);
}
@Override
@GwtIncompatible("NavigableSet")
Collection<V> unmodifiableCollectionSubclass(Collection<V> collection) {
return Sets.unmodifiableNavigableSet((NavigableSet<V>) collection);
}
@Override
@GwtIncompatible("NavigableSet")
Collection<V> wrapCollection(K key, Collection<V> collection) {
return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
}
/**
* {@inheritDoc}
*
* <p>Because a {@code TreeMultimap} has unique sorted keys, this method
* returns a {@link NavigableSet}, instead of the {@link java.util.Set} specified
* in the {@link Multimap} interface.
*
* @since 14.0 (present with return type {@code SortedSet} since 2.0)
*/
@Override
@GwtIncompatible("NavigableSet")
public NavigableSet<K> keySet() {
return (NavigableSet<K>) super.keySet();
}
@Override
@GwtIncompatible("NavigableSet")
NavigableSet<K> createKeySet() {
return new NavigableKeySet(backingMap());
}
/**
* {@inheritDoc}
*
* <p>Because a {@code TreeMultimap} has unique sorted keys, this method
* returns a {@link NavigableMap}, instead of the {@link java.util.Map} specified
* in the {@link Multimap} interface.
*
* @since 14.0 (present with return type {@code SortedMap} since 2.0)
*/
@Override
@GwtIncompatible("NavigableMap")
public NavigableMap<K, Collection<V>> asMap() {
return (NavigableMap<K, Collection<V>>) super.asMap();
}
@Override
@GwtIncompatible("NavigableMap")
NavigableMap<K, Collection<V>> createAsMap() {
return new NavigableAsMap(backingMap());
}
/**
* @serialData key comparator, value comparator, number of distinct keys, and
* then for each distinct key: the key, number of values for that key, and
* key values
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyComparator());
stream.writeObject(valueComparator());
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyComparator = checkNotNull((Comparator<? super K>) stream.readObject());
valueComparator = checkNotNull((Comparator<? super V>) stream.readObject());
setMap(new TreeMap<K, Collection<V>>(keyComparator));
Serialization.populateMultimap(this, stream);
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/TreeMultimap.java | Java | asf20 | 9,448 |
/*
* 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. See the {@link Multimap}
* documentation for information common to all multimaps.
*
* <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods
* each return a {@link 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><b>Note:</b> The returned map's values are guaranteed to be of type
* {@link List}. To obtain this map with the more specific generic type
* {@code Map<K, List<V>>}, call {@link Multimaps#asMap(ListMultimap)}
* instead.
*/
@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);
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ListMultimap.java | Java | asf20 | 3,373 |
/*
* 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 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 indexOf(object);
}
@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(@Nullable 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
int copyIntoArray(Object[] dst, int offset) {
dst[offset] = element;
return offset + 1;
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SingletonImmutableList.java | Java | asf20 | 3,097 |
/*
* 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.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import javax.annotation.Nullable;
/**
* This class contains static utility methods that operate on or return objects
* of type {@code Iterable}. Except as noted, each method has a corresponding
* {@link Iterator}-based method in the {@link Iterators} class.
*
* <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables
* produced in this class are <i>lazy</i>, which means that their iterators
* only advance the backing iteration when absolutely necessary.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables">
* {@code Iterables}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Iterables {
private Iterables() {}
/** Returns an unmodifiable view of {@code iterable}. */
public static <T> Iterable<T> unmodifiableIterable(
final Iterable<T> iterable) {
checkNotNull(iterable);
if (iterable instanceof UnmodifiableIterable ||
iterable instanceof ImmutableCollection) {
return iterable;
}
return new UnmodifiableIterable<T>(iterable);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <E> Iterable<E> unmodifiableIterable(
ImmutableCollection<E> iterable) {
return checkNotNull(iterable);
}
private static final class UnmodifiableIterable<T> extends FluentIterable<T> {
private final Iterable<T> iterable;
private UnmodifiableIterable(Iterable<T> iterable) {
this.iterable = iterable;
}
@Override
public Iterator<T> iterator() {
return Iterators.unmodifiableIterator(iterable.iterator());
}
@Override
public String toString() {
return iterable.toString();
}
// no equals and hashCode; it would break the contract!
}
/**
* Returns the number of elements in {@code iterable}.
*/
public static int size(Iterable<?> iterable) {
return (iterable instanceof Collection)
? ((Collection<?>) iterable).size()
: Iterators.size(iterable.iterator());
}
/**
* Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)}
* is true.
*/
public static boolean contains(Iterable<?> iterable, @Nullable Object element) {
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
return Collections2.safeContains(collection, element);
}
return Iterators.contains(iterable.iterator(), element);
}
/**
* Removes, from an iterable, every element that belongs to the provided
* collection.
*
* <p>This method calls {@link Collection#removeAll} if {@code iterable} is a
* collection, and {@link Iterators#removeAll} otherwise.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param elementsToRemove the elements to remove
* @return {@code true} if any element was removed from {@code iterable}
*/
public static boolean removeAll(
Iterable<?> removeFrom, Collection<?> elementsToRemove) {
return (removeFrom instanceof Collection)
? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove))
: Iterators.removeAll(removeFrom.iterator(), elementsToRemove);
}
/**
* Removes, from an iterable, every element that does not belong to the
* provided collection.
*
* <p>This method calls {@link Collection#retainAll} if {@code iterable} is a
* collection, and {@link Iterators#retainAll} otherwise.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param elementsToRetain the elements to retain
* @return {@code true} if any element was removed from {@code iterable}
*/
public static boolean retainAll(
Iterable<?> removeFrom, Collection<?> elementsToRetain) {
return (removeFrom instanceof Collection)
? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain))
: Iterators.retainAll(removeFrom.iterator(), elementsToRetain);
}
/**
* Removes, from an iterable, every element that satisfies the provided
* predicate.
*
* @param removeFrom the iterable 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 iterable
*
* @throws UnsupportedOperationException if the iterable does not support
* {@code remove()}.
* @since 2.0
*/
public static <T> boolean removeIf(
Iterable<T> removeFrom, Predicate<? super T> predicate) {
if (removeFrom instanceof RandomAccess && removeFrom instanceof List) {
return removeIfFromRandomAccessList(
(List<T>) removeFrom, checkNotNull(predicate));
}
return Iterators.removeIf(removeFrom.iterator(), predicate);
}
private static <T> boolean removeIfFromRandomAccessList(
List<T> list, Predicate<? super T> predicate) {
// Note: Not all random access lists support set() so we need to deal with
// those that don't and attempt the slower remove() based solution.
int from = 0;
int to = 0;
for (; from < list.size(); from++) {
T element = list.get(from);
if (!predicate.apply(element)) {
if (from > to) {
try {
list.set(to, element);
} catch (UnsupportedOperationException e) {
slowRemoveIfForRemainingElements(list, predicate, to, from);
return true;
}
}
to++;
}
}
// Clear the tail of any remaining items
list.subList(to, list.size()).clear();
return from != to;
}
private static <T> void slowRemoveIfForRemainingElements(List<T> list,
Predicate<? super T> predicate, int to, int from) {
// Here we know that:
// * (to < from) and that both are valid indices.
// * Everything with (index < to) should be kept.
// * Everything with (to <= index < from) should be removed.
// * The element with (index == from) should be kept.
// * Everything with (index > from) has not been checked yet.
// Check from the end of the list backwards (minimize expected cost of
// moving elements when remove() is called). Stop before 'from' because
// we already know that should be kept.
for (int n = list.size() - 1; n > from; n--) {
if (predicate.apply(list.get(n))) {
list.remove(n);
}
}
// And now remove everything in the range [to, from) (going backwards).
for (int n = from - 1; n >= to; n--) {
list.remove(n);
}
}
/**
* Removes and returns the first matching element, or returns {@code null} if there is none.
*/
@Nullable
static <T> T removeFirstMatching(Iterable<T> removeFrom, Predicate<? super T> predicate) {
checkNotNull(predicate);
Iterator<T> iterator = removeFrom.iterator();
while (iterator.hasNext()) {
T next = iterator.next();
if (predicate.apply(next)) {
iterator.remove();
return next;
}
}
return null;
}
/**
* Determines whether two iterables contain equal elements in the same order.
* More specifically, this method returns {@code true} if {@code iterable1}
* and {@code iterable2} contain the same number of elements and every element
* of {@code iterable1} is equal to the corresponding element of
* {@code iterable2}.
*/
public static boolean elementsEqual(
Iterable<?> iterable1, Iterable<?> iterable2) {
if (iterable1 instanceof Collection && iterable2 instanceof Collection) {
Collection<?> collection1 = (Collection<?>) iterable1;
Collection<?> collection2 = (Collection<?>) iterable2;
if (collection1.size() != collection2.size()) {
return false;
}
}
return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
}
/**
* Returns a string representation of {@code iterable}, with the format {@code
* [e1, e2, ..., en]} (that is, identical to {@link java.util.Arrays
* Arrays}{@code .toString(Iterables.toArray(iterable))}). Note that for
* <i>most</i> implementations of {@link Collection}, {@code
* collection.toString()} also gives the same result, but that behavior is not
* generally guaranteed.
*/
public static String toString(Iterable<?> iterable) {
return Iterators.toString(iterable.iterator());
}
/**
* Returns the single element contained in {@code iterable}.
*
* @throws NoSuchElementException if the iterable is empty
* @throws IllegalArgumentException if the iterable contains multiple
* elements
*/
public static <T> T getOnlyElement(Iterable<T> iterable) {
return Iterators.getOnlyElement(iterable.iterator());
}
/**
* Returns the single element contained in {@code iterable}, or {@code
* defaultValue} if the iterable is empty.
*
* @throws IllegalArgumentException if the iterator contains multiple
* elements
*/
@Nullable
public static <T> T getOnlyElement(
Iterable<? extends T> iterable, @Nullable T defaultValue) {
return Iterators.getOnlyElement(iterable.iterator(), defaultValue);
}
/**
* Copies an iterable's elements into an array.
*
* @param iterable the iterable to copy
* @param type the type of the elements
* @return a newly-allocated array into which all the elements of the iterable
* have been copied
*/
@GwtIncompatible("Array.newInstance(Class, int)")
public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
Collection<? extends T> collection = toCollection(iterable);
T[] array = ObjectArrays.newArray(type, collection.size());
return collection.toArray(array);
}
/**
* Copies an iterable's elements into an array.
*
* @param iterable the iterable to copy
* @return a newly-allocated array into which all the elements of the iterable
* have been copied
*/
static Object[] toArray(Iterable<?> iterable) {
return toCollection(iterable).toArray();
}
/**
* Converts an iterable into a collection. If the iterable is already a
* collection, it is returned. Otherwise, an {@link java.util.ArrayList} is
* created with the contents of the iterable in the same iteration order.
*/
private static <E> Collection<E> toCollection(Iterable<E> iterable) {
return (iterable instanceof Collection)
? (Collection<E>) iterable
: Lists.newArrayList(iterable.iterator());
}
/**
* Adds all elements in {@code iterable} to {@code collection}.
*
* @return {@code true} if {@code collection} was modified as a result of this
* operation.
*/
public static <T> boolean addAll(
Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
if (elementsToAdd instanceof Collection) {
Collection<? extends T> c = Collections2.cast(elementsToAdd);
return addTo.addAll(c);
}
return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator());
}
/**
* Returns the number of elements in the specified iterable that equal the
* specified object. This implementation avoids a full iteration when the
* iterable is a {@link Multiset} or {@link Set}.
*
* @see Collections#frequency
*/
public static int frequency(Iterable<?> iterable, @Nullable Object element) {
if ((iterable instanceof Multiset)) {
return ((Multiset<?>) iterable).count(element);
} else if ((iterable instanceof Set)) {
return ((Set<?>) iterable).contains(element) ? 1 : 0;
}
return Iterators.frequency(iterable.iterator(), element);
}
/**
* Returns an iterable whose iterators cycle indefinitely over the elements of
* {@code iterable}.
*
* <p>That iterator supports {@code remove()} if {@code iterable.iterator()}
* does. After {@code remove()} is called, subsequent cycles omit the removed
* element, which is no longer in {@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.
*
* <p>To cycle over the iterable {@code n} times, use the following:
* {@code Iterables.concat(Collections.nCopies(n, iterable))}
*/
public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.cycle(iterable);
}
@Override public String toString() {
return iterable.toString() + " (cycled)";
}
};
}
/**
* Returns an iterable whose iterators cycle indefinitely over the provided
* elements.
*
* <p>After {@code remove} is invoked on a generated iterator, the removed
* element will no longer appear in either that iterator or any other iterator
* created from the same source iterable. That is, this method behaves exactly
* as {@code Iterables.cycle(Lists.newArrayList(elements))}. 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.
*
* <p>To cycle over the elements {@code n} times, use the following:
* {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))}
*/
public static <T> Iterable<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
}
/**
* Combines two iterables into a single iterable. The returned iterable has an
* iterator that traverses the elements in {@code a}, followed by the elements
* in {@code b}. The source iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
public static <T> Iterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b) {
return concat(ImmutableList.of(a, b));
}
/**
* Combines three iterables into a single iterable. The returned iterable has
* an iterator that traverses 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 iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c) {
return concat(ImmutableList.of(a, b, c));
}
/**
* Combines four iterables into a single iterable. The returned iterable has
* an iterator that traverses 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 iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c,
Iterable<? extends T> d) {
return concat(ImmutableList.of(a, b, c, d));
}
/**
* Combines multiple iterables into a single iterable. The returned iterable
* has an iterator that traverses the elements of each iterable in
* {@code inputs}. The input iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*
* @throws NullPointerException if any of the provided iterables is null
*/
public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
return concat(ImmutableList.copyOf(inputs));
}
/**
* Combines multiple iterables into a single iterable. The returned iterable
* has an iterator that traverses the elements of each iterable in
* {@code inputs}. The input iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it. The methods of the returned
* iterable may throw {@code NullPointerException} if any of the input
* iterators is null.
*/
public static <T> Iterable<T> concat(
final Iterable<? extends Iterable<? extends T>> inputs) {
checkNotNull(inputs);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.concat(iterators(inputs));
}
};
}
/**
* Returns an iterator over the iterators of the given iterables.
*/
private static <T> Iterator<Iterator<? extends T>> iterators(
Iterable<? extends Iterable<? extends T>> iterables) {
return new TransformedIterator<Iterable<? extends T>, Iterator<? extends T>>(
iterables.iterator()) {
@Override
Iterator<? extends T> transform(Iterable<? extends T> from) {
return from.iterator();
}
};
}
/**
* Divides an iterable into unmodifiable sublists of the given size (the final
* iterable may be smaller). For example, partitioning an iterable containing
* {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
* [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of
* three and two elements, all in the original order.
*
* <p>Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method. The returned lists implement {@link
* RandomAccess}, whether or not the input list does.
*
* <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link
* Lists#partition(List, int)} instead.
*
* @param iterable the iterable to return a partitioned view of
* @param size the desired size of each partition (the last may be smaller)
* @return an iterable of unmodifiable lists containing the elements of {@code
* iterable} divided into partitions
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> Iterable<List<T>> partition(
final Iterable<T> iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new FluentIterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return Iterators.partition(iterable.iterator(), size);
}
};
}
/**
* Divides an iterable into unmodifiable sublists of the given size, padding
* the final iterable with null values if necessary. For example, partitioning
* an iterable containing {@code [a, b, c, d, e]} with a partition size of 3
* yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing
* two inner lists of three elements each, all in the original order.
*
* <p>Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method.
*
* @param iterable the iterable to return a partitioned view of
* @param size the desired size of each partition
* @return an iterable of unmodifiable lists containing the elements of {@code
* iterable} divided into partitions (the final iterable may have
* trailing null elements)
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> Iterable<List<T>> paddedPartition(
final Iterable<T> iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new FluentIterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return Iterators.paddedPartition(iterable.iterator(), size);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* resulting iterable's iterator does not support {@code remove()}.
*/
public static <T> Iterable<T> filter(
final Iterable<T> unfiltered, final Predicate<? super T> predicate) {
checkNotNull(unfiltered);
checkNotNull(predicate);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
};
}
/**
* Returns all instances of class {@code type} in {@code unfiltered}. The
* returned iterable has elements whose class is {@code type} or a subclass of
* {@code type}. The returned iterable's iterator does not support
* {@code remove()}.
*
* @param unfiltered an iterable containing objects of any type
* @param type the type of elements desired
* @return an unmodifiable iterable containing all elements of the original
* iterable that were of the requested type
*/
@GwtIncompatible("Class.isInstance")
public static <T> Iterable<T> filter(
final Iterable<?> unfiltered, final Class<T> type) {
checkNotNull(unfiltered);
checkNotNull(type);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.filter(unfiltered.iterator(), type);
}
};
}
/**
* Returns {@code true} if any element in {@code iterable} satisfies the predicate.
*/
public static <T> boolean any(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.any(iterable.iterator(), predicate);
}
/**
* Returns {@code true} if every element in {@code iterable} satisfies the
* predicate. If {@code iterable} is empty, {@code true} is returned.
*/
public static <T> boolean all(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.all(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate; use this method only when such an element is known to exist. If
* it is possible that <i>no</i> element will match, use {@link #tryFind} or
* {@link #find(Iterable, Predicate, Object)} instead.
*
* @throws NoSuchElementException if no element in {@code iterable} matches
* the given predicate
*/
public static <T> T find(Iterable<T> iterable,
Predicate<? super T> predicate) {
return Iterators.find(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate, or {@code defaultValue} if none found. Note that this can
* usually be handled more naturally using {@code
* tryFind(iterable, predicate).or(defaultValue)}.
*
* @since 7.0
*/
@Nullable
public static <T> T find(Iterable<? extends T> iterable,
Predicate<? super T> predicate, @Nullable T defaultValue) {
return Iterators.find(iterable.iterator(), predicate, defaultValue);
}
/**
* Returns an {@link Optional} containing the first element in {@code
* iterable} that satisfies the given predicate, if such an element exists.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
* null}. If {@code null} is matched in {@code iterable}, a
* NullPointerException will be thrown.
*
* @since 11.0
*/
public static <T> Optional<T> tryFind(Iterable<T> iterable,
Predicate<? super T> predicate) {
return Iterators.tryFind(iterable.iterator(), predicate);
}
/**
* Returns the index in {@code iterable} of the first element that satisfies
* the provided {@code predicate}, or {@code -1} if the Iterable has no such
* elements.
*
* <p>More formally, returns the lowest index {@code i} such that
* {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true},
* or {@code -1} if there is no such index.
*
* @since 2.0
*/
public static <T> int indexOf(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.indexOf(iterable.iterator(), predicate);
}
/**
* Returns an iterable that applies {@code function} to each element of {@code
* fromIterable}.
*
* <p>The returned iterable's iterator supports {@code remove()} if the
* provided iterator does. After a successful {@code remove()} call,
* {@code fromIterable} no longer contains the corresponding element.
*
* <p>If the input {@code Iterable} is known to be a {@code List} or other
* {@code Collection}, consider {@link Lists#transform} and {@link
* Collections2#transform}.
*/
public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable,
final Function<? super F, ? extends T> function) {
checkNotNull(fromIterable);
checkNotNull(function);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.transform(fromIterable.iterator(), function);
}
};
}
/**
* Returns the element at the specified position in an iterable.
*
* @param position position of the element to return
* @return the element at the specified position in {@code iterable}
* @throws IndexOutOfBoundsException if {@code position} is negative or
* greater than or equal to the size of {@code iterable}
*/
public static <T> T get(Iterable<T> iterable, int position) {
checkNotNull(iterable);
return (iterable instanceof List)
? ((List<T>) iterable).get(position)
: Iterators.get(iterable.iterator(), position);
}
/**
* Returns the element at the specified position in an iterable or a default
* value otherwise.
*
* @param position position of the element to return
* @param defaultValue the default value to return if {@code position} is
* greater than or equal to the size of the iterable
* @return the element at the specified position in {@code iterable} or
* {@code defaultValue} if {@code iterable} contains fewer than
* {@code position + 1} elements.
* @throws IndexOutOfBoundsException if {@code position} is negative
* @since 4.0
*/
@Nullable
public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) {
checkNotNull(iterable);
Iterators.checkNonnegative(position);
if (iterable instanceof List) {
List<? extends T> list = Lists.cast(iterable);
return (position < list.size()) ? list.get(position) : defaultValue;
} else {
Iterator<? extends T> iterator = iterable.iterator();
Iterators.advance(iterator, position);
return Iterators.getNext(iterator, defaultValue);
}
}
/**
* Returns the first element in {@code iterable} or {@code defaultValue} if
* the iterable is empty. The {@link Iterators} analog to this method is
* {@link Iterators#getNext}.
*
* <p>If no default value is desired (and the caller instead wants a
* {@link NoSuchElementException} to be thrown), it is recommended that
* {@code iterable.iterator().next()} is used instead.
*
* @param defaultValue the default value to return if the iterable is empty
* @return the first element of {@code iterable} or the default value
* @since 7.0
*/
@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) {
return Iterators.getNext(iterable.iterator(), defaultValue);
}
/**
* Returns the last element of {@code iterable}.
*
* @return the last element of {@code iterable}
* @throws NoSuchElementException if the iterable is empty
*/
public static <T> T getLast(Iterable<T> iterable) {
// TODO(kevinb): Support a concurrently modified collection?
if (iterable instanceof List) {
List<T> list = (List<T>) iterable;
if (list.isEmpty()) {
throw new NoSuchElementException();
}
return getLastInNonemptyList(list);
}
return Iterators.getLast(iterable.iterator());
}
/**
* Returns the last element of {@code iterable} or {@code defaultValue} if
* the iterable is empty.
*
* @param defaultValue the value to return if {@code iterable} is empty
* @return the last element of {@code iterable} or the default value
* @since 3.0
*/
@Nullable
public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) {
if (iterable instanceof Collection) {
Collection<? extends T> c = Collections2.cast(iterable);
if (c.isEmpty()) {
return defaultValue;
} else if (iterable instanceof List) {
return getLastInNonemptyList(Lists.cast(iterable));
}
}
return Iterators.getLast(iterable.iterator(), defaultValue);
}
private static <T> T getLastInNonemptyList(List<T> list) {
return list.get(list.size() - 1);
}
/**
* Returns a view of {@code iterable} that skips its first
* {@code numberToSkip} elements. If {@code iterable} contains fewer than
* {@code numberToSkip} elements, the returned iterable skips all of its
* elements.
*
* <p>Modifications to the underlying {@link Iterable} before a call to
* {@code iterator()} are reflected in the returned iterator. That is, the
* iterator skips the first {@code numberToSkip} elements that exist when the
* {@code Iterator} is created, not when {@code skip()} is called.
*
* <p>The returned iterable's iterator supports {@code remove()} if the
* iterator of the underlying iterable supports it. Note that it is
* <i>not</i> possible to delete the last skipped element by immediately
* calling {@code remove()} on that iterator, as the {@code Iterator}
* contract states that a call to {@code remove()} before a call to
* {@code next()} will throw an {@link IllegalStateException}.
*
* @since 3.0
*/
public static <T> Iterable<T> skip(final Iterable<T> iterable,
final int numberToSkip) {
checkNotNull(iterable);
checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
if (iterable instanceof List) {
final List<T> list = (List<T>) iterable;
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
// TODO(kevinb): Support a concurrently modified collection?
int toSkip = Math.min(list.size(), numberToSkip);
return list.subList(toSkip, list.size()).iterator();
}
};
}
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
final Iterator<T> iterator = iterable.iterator();
Iterators.advance(iterator, numberToSkip);
/*
* We can't just return the iterator because an immediate call to its
* remove() method would remove one of the skipped elements instead of
* throwing an IllegalStateException.
*/
return new Iterator<T>() {
boolean atStart = true;
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
T result = iterator.next();
atStart = false; // not called if next() fails
return result;
}
@Override
public void remove() {
checkRemove(!atStart);
iterator.remove();
}
};
}
};
}
/**
* Creates an iterable with the first {@code limitSize} elements of the given
* iterable. If the original iterable does not contain that many elements, the
* returned iterable will have the same behavior as the original iterable. The
* returned iterable's iterator supports {@code remove()} if the original
* iterator does.
*
* @param iterable the iterable to limit
* @param limitSize the maximum number of elements in the returned iterable
* @throws IllegalArgumentException if {@code limitSize} is negative
* @since 3.0
*/
public static <T> Iterable<T> limit(
final Iterable<T> iterable, final int limitSize) {
checkNotNull(iterable);
checkArgument(limitSize >= 0, "limit is negative");
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.limit(iterable.iterator(), limitSize);
}
};
}
/**
* Returns a view of the supplied iterable that wraps each generated
* {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}.
*
* <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will
* get entries from {@link Queue#remove()} since {@link Queue}'s iteration
* order is undefined. Calling {@link Iterator#hasNext()} on a generated
* iterator from the returned iterable may cause an item to be immediately
* dequeued for return on a subsequent call to {@link Iterator#next()}.
*
* @param iterable the iterable to wrap
* @return a view of the supplied iterable that wraps each generated iterator
* through {@link Iterators#consumingIterator(Iterator)}; for queues,
* an iterable that generates iterators that return and consume the
* queue's elements in queue order
*
* @see Iterators#consumingIterator(Iterator)
* @since 2.0
*/
public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) {
if (iterable instanceof Queue) {
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return new ConsumingQueueIterator<T>((Queue<T>) iterable);
}
@Override
public String toString() {
return "Iterables.consumingIterable(...)";
}
};
}
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.consumingIterator(iterable.iterator());
}
@Override
public String toString() {
return "Iterables.consumingIterable(...)";
}
};
}
private static class ConsumingQueueIterator<T> extends AbstractIterator<T> {
private final Queue<T> queue;
private ConsumingQueueIterator(Queue<T> queue) {
this.queue = queue;
}
@Override public T computeNext() {
try {
return queue.remove();
} catch (NoSuchElementException e) {
return endOfData();
}
}
}
// Methods only in Iterables, not in Iterators
/**
* Determines if the given iterable contains no elements.
*
* <p>There is no precise {@link Iterator} equivalent to this method, since
* one can only ask an iterator whether it has any elements <i>remaining</i>
* (which one does using {@link Iterator#hasNext}).
*
* @return {@code true} if the iterable contains no elements
*/
public static boolean isEmpty(Iterable<?> iterable) {
if (iterable instanceof Collection) {
return ((Collection<?>) iterable).isEmpty();
}
return !iterable.iterator().hasNext();
}
/**
* Returns an iterable over the merged contents of all given
* {@code iterables}. Equivalent entries will not be de-duplicated.
*
* <p>Callers must ensure that the source {@code iterables} are in
* non-descending order as this method does not sort its input.
*
* <p>For any equivalent elements across all {@code iterables}, it is
* undefined which element is returned first.
*
* @since 11.0
*/
@Beta
public static <T> Iterable<T> mergeSorted(
final Iterable<? extends Iterable<? extends T>> iterables,
final Comparator<? super T> comparator) {
checkNotNull(iterables, "iterables");
checkNotNull(comparator, "comparator");
Iterable<T> iterable = new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.mergeSorted(
Iterables.transform(iterables, Iterables.<T>toIterator()),
comparator);
}
};
return new UnmodifiableIterable<T>(iterable);
}
// TODO(user): Is this the best place for this? Move to fluent functions?
// Useful as a public method?
private static <T> Function<Iterable<? extends T>, Iterator<? extends T>>
toIterator() {
return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
@Override
public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
return iterable.iterator();
}
};
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/Iterables.java | Java | asf20 | 37,957 |
/*
* 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.collect.BoundType.CLOSED;
import static com.google.common.collect.BoundType.OPEN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Multiset.Entry;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static utility methods for creating and working with
* {@link SortedMultiset} instances.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
final class SortedMultisets {
private SortedMultisets() {
}
/**
* A skeleton implementation for {@link SortedMultiset#elementSet}.
*/
static class ElementSet<E> extends Multisets.ElementSet<E> implements
SortedSet<E> {
private final SortedMultiset<E> multiset;
ElementSet(SortedMultiset<E> multiset) {
this.multiset = multiset;
}
@Override final SortedMultiset<E> multiset() {
return multiset;
}
@Override public Comparator<? super E> comparator() {
return multiset().comparator();
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return multiset().subMultiset(fromElement, CLOSED, toElement, OPEN).elementSet();
}
@Override public SortedSet<E> headSet(E toElement) {
return multiset().headMultiset(toElement, OPEN).elementSet();
}
@Override public SortedSet<E> tailSet(E fromElement) {
return multiset().tailMultiset(fromElement, CLOSED).elementSet();
}
@Override public E first() {
return getElementOrThrow(multiset().firstEntry());
}
@Override public E last() {
return getElementOrThrow(multiset().lastEntry());
}
}
/**
* A skeleton navigable implementation for {@link SortedMultiset#elementSet}.
*/
@GwtIncompatible("Navigable")
static class NavigableElementSet<E> extends ElementSet<E> implements NavigableSet<E> {
NavigableElementSet(SortedMultiset<E> multiset) {
super(multiset);
}
@Override
public E lower(E e) {
return getElementOrNull(multiset().headMultiset(e, OPEN).lastEntry());
}
@Override
public E floor(E e) {
return getElementOrNull(multiset().headMultiset(e, CLOSED).lastEntry());
}
@Override
public E ceiling(E e) {
return getElementOrNull(multiset().tailMultiset(e, CLOSED).firstEntry());
}
@Override
public E higher(E e) {
return getElementOrNull(multiset().tailMultiset(e, OPEN).firstEntry());
}
@Override
public NavigableSet<E> descendingSet() {
return new NavigableElementSet<E>(multiset().descendingMultiset());
}
@Override
public Iterator<E> descendingIterator() {
return descendingSet().iterator();
}
@Override
public E pollFirst() {
return getElementOrNull(multiset().pollFirstEntry());
}
@Override
public E pollLast() {
return getElementOrNull(multiset().pollLastEntry());
}
@Override
public NavigableSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return new NavigableElementSet<E>(multiset().subMultiset(
fromElement, BoundType.forBoolean(fromInclusive),
toElement, BoundType.forBoolean(toInclusive)));
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new NavigableElementSet<E>(
multiset().headMultiset(toElement, BoundType.forBoolean(inclusive)));
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new NavigableElementSet<E>(
multiset().tailMultiset(fromElement, BoundType.forBoolean(inclusive)));
}
}
private static <E> E getElementOrThrow(Entry<E> entry) {
if (entry == null) {
throw new NoSuchElementException();
}
return entry.getElement();
}
private static <E> E getElementOrNull(@Nullable Entry<E> entry) {
return (entry == null) ? null : entry.getElement();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/SortedMultisets.java | Java | asf20 | 4,772 |
/*
* 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.Set;
import javax.annotation.Nullable;
/**
* An empty immutable set.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
final class EmptyImmutableSet extends ImmutableSet<Object> {
static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet();
private EmptyImmutableSet() {}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean contains(@Nullable Object target) {
return false;
}
@Override public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override public UnmodifiableIterator<Object> iterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
@Override
int copyIntoArray(Object[] dst, int offset) {
return offset;
}
@Override
public ImmutableList<Object> asList() {
return ImmutableList.of();
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.isEmpty();
}
return false;
}
@Override public final int hashCode() {
return 0;
}
@Override boolean isHashCodeFast() {
return true;
}
@Override public String toString() {
return "[]";
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/EmptyImmutableSet.java | Java | asf20 | 2,207 |
/*
* 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.io.Serializable;
import javax.annotation.Nullable;
/**
* @see com.google.common.collect.Maps#immutableEntry(Object, Object)
*/
@GwtCompatible(serializable = true)
class ImmutableEntry<K, V> extends AbstractMapEntry<K, V>
implements Serializable {
final K key;
final V value;
ImmutableEntry(@Nullable K key, @Nullable V value) {
this.key = key;
this.value = value;
}
@Nullable @Override public final K getKey() {
return key;
}
@Nullable @Override public final V getValue() {
return value;
}
@Override public final V setValue(V value) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/ImmutableEntry.java | Java | asf20 | 1,388 |
/*
* 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/NullsLastOrdering.java | Java | asf20 | 2,345 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Basic implementation of a {@link SortedSetMultimap} with a sorted key set.
*
* This superclass allows {@code TreeMultimap} to override methods to return
* navigable set and map types in non-GWT only, while GWT code will inherit the
* SortedMap/SortedSet overrides.
*
* @author Louis Wasserman
*/
@GwtCompatible
abstract class AbstractSortedKeySortedSetMultimap<K, V> extends AbstractSortedSetMultimap<K, V> {
AbstractSortedKeySortedSetMultimap(SortedMap<K, Collection<V>> map) {
super(map);
}
@Override
public SortedMap<K, Collection<V>> asMap() {
return (SortedMap<K, Collection<V>>) super.asMap();
}
@Override
SortedMap<K, Collection<V>> backingMap() {
return (SortedMap<K, Collection<V>>) super.backingMap();
}
@Override
public SortedSet<K> keySet() {
return (SortedSet<K>) super.keySet();
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AbstractSortedKeySortedSetMultimap.java | Java | asf20 | 1,633 |
/*
* 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 static com.google.common.collect.CollectPreconditions.checkRemove;
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.ArrayDeque;
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.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): GWT compatibility
@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;
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() {
checkRemove(canRemove);
checkModCount();
canRemove = false;
expectedModCount++;
if (cursor < size()) {
MoveDesc<E> moved = removeAt(cursor);
if (moved != null) {
if (forgetMeNot == null) {
forgetMeNot = new ArrayDeque<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
}
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/MinMaxPriorityQueue.java | Java | asf20 | 31,227 |
/*
* 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.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static java.util.Collections.unmodifiableList;
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.io.Serializable;
import java.util.AbstractSequentialList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An implementation of {@code ListMultimap} that supports deterministic
* iteration order for both keys and values. The iteration order is preserved
* across non-distinct key values. For example, for the following multimap
* definition: <pre> {@code
*
* Multimap<K, V> multimap = LinkedListMultimap.create();
* multimap.put(key1, foo);
* multimap.put(key2, bar);
* multimap.put(key1, baz);}</pre>
*
* ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]},
* and similarly for {@link #entries()}. Unlike {@link LinkedHashMultimap}, the
* iteration order is kept consistent between keys, entries and values. For
* example, calling: <pre> {@code
*
* map.remove(key1, foo);}</pre>
*
* <p>changes the entries iteration order to {@code [key2=bar, key1=baz]} and the
* key iteration order to {@code [key2, key1]}. The {@link #entries()} iterator
* returns mutable map entries, and {@link #replaceValues} attempts to preserve
* iteration order as much as possible.
*
* <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate
* through the keys in the order they were first added to the multimap.
* Similarly, {@link #get}, {@link #removeAll}, and {@link #replaceValues}
* return collections that iterate through the values in the order they were
* added. The collections generated by {@link #entries()}, {@link #keys()}, and
* {@link #values} iterate across the key-value mappings in the order they were
* added to the multimap.
*
* <p>The {@link #values()} and {@link #entries()} methods both return a
* {@code List}, instead of the {@code Collection} specified by the {@link
* ListMultimap} interface.
*
* <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()},
* {@link #values}, {@link #entries()}, and {@link #asMap} return collections
* that are views of the multimap. If the multimap is modified while an
* iteration over any of those collections is in progress, except through the
* iterator's methods, the results of the iteration are undefined.
*
* <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#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 Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class LinkedListMultimap<K, V> extends AbstractMultimap<K, V>
implements ListMultimap<K, V>, Serializable {
/*
* Order is maintained using a linked list containing all key-value pairs. In
* addition, a series of disjoint linked lists of "siblings", each containing
* the values for a specific key, is used to implement {@link
* ValueForKeyIterator} in constant time.
*/
private static final class Node<K, V> extends AbstractMapEntry<K, V> {
final K key;
V value;
Node<K, V> next; // the next node (with any key)
Node<K, V> previous; // the previous node (with any key)
Node<K, V> nextSibling; // the next node with the same key
Node<K, V> previousSibling; // the previous node with the same key
Node(@Nullable K key, @Nullable V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(@Nullable V newValue) {
V result = value;
this.value = newValue;
return result;
}
}
private static class KeyList<K, V> {
Node<K, V> head;
Node<K, V> tail;
int count;
KeyList(Node<K, V> firstNode) {
this.head = firstNode;
this.tail = firstNode;
firstNode.previousSibling = null;
firstNode.nextSibling = null;
this.count = 1;
}
}
private transient Node<K, V> head; // the head for all keys
private transient Node<K, V> tail; // the tail for all keys
private transient Map<K, KeyList<K, V>> keyToKeyList;
private transient int size;
/*
* Tracks modifications to keyToKeyList so that addition or removal of keys invalidates
* preexisting iterators. This does *not* track simple additions and removals of values
* that are not the first to be added or last to be removed for their key.
*/
private transient int modCount;
/**
* Creates a new, empty {@code LinkedListMultimap} with the default initial
* capacity.
*/
public static <K, V> LinkedListMultimap<K, V> create() {
return new LinkedListMultimap<K, V>();
}
/**
* Constructs an empty {@code LinkedListMultimap} with enough capacity to hold
* the specified number of keys without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @throws IllegalArgumentException if {@code expectedKeys} is negative
*/
public static <K, V> LinkedListMultimap<K, V> create(int expectedKeys) {
return new LinkedListMultimap<K, V>(expectedKeys);
}
/**
* Constructs a {@code LinkedListMultimap} with the same mappings as the
* specified {@code Multimap}. The new multimap has the same
* {@link Multimap#entries()} iteration order as the input multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> LinkedListMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new LinkedListMultimap<K, V>(multimap);
}
LinkedListMultimap() {
keyToKeyList = Maps.newHashMap();
}
private LinkedListMultimap(int expectedKeys) {
keyToKeyList = new HashMap<K, KeyList<K, V>>(expectedKeys);
}
private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size());
putAll(multimap);
}
/**
* Adds a new node for the specified key-value pair before the specified
* {@code nextSibling} element, or at the end of the list if {@code
* nextSibling} is null. Note: if {@code nextSibling} is specified, it MUST be
* for an node for the same {@code key}!
*/
private Node<K, V> addNode(
@Nullable K key, @Nullable V value, @Nullable Node<K, V> nextSibling) {
Node<K, V> node = new Node<K, V>(key, value);
if (head == null) { // empty list
head = tail = node;
keyToKeyList.put(key, new KeyList<K, V>(node));
modCount++;
} else if (nextSibling == null) { // non-empty list, add to tail
tail.next = node;
node.previous = tail;
tail = node;
KeyList<K, V> keyList = keyToKeyList.get(key);
if (keyList == null) {
keyToKeyList.put(key, keyList = new KeyList<K, V>(node));
modCount++;
} else {
keyList.count++;
Node<K, V> keyTail = keyList.tail;
keyTail.nextSibling = node;
node.previousSibling = keyTail;
keyList.tail = node;
}
} else { // non-empty list, insert before nextSibling
KeyList<K, V> keyList = keyToKeyList.get(key);
keyList.count++;
node.previous = nextSibling.previous;
node.previousSibling = nextSibling.previousSibling;
node.next = nextSibling;
node.nextSibling = nextSibling;
if (nextSibling.previousSibling == null) { // nextSibling was key head
keyToKeyList.get(key).head = node;
} else {
nextSibling.previousSibling.nextSibling = node;
}
if (nextSibling.previous == null) { // nextSibling was head
head = node;
} else {
nextSibling.previous.next = node;
}
nextSibling.previous = node;
nextSibling.previousSibling = node;
}
size++;
return node;
}
/**
* Removes the specified node from the linked list. This method is only
* intended to be used from the {@code Iterator} classes. See also {@link
* LinkedListMultimap#removeAllNodes(Object)}.
*/
private void removeNode(Node<K, V> node) {
if (node.previous != null) {
node.previous.next = node.next;
} else { // node was head
head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else { // node was tail
tail = node.previous;
}
if (node.previousSibling == null && node.nextSibling == null) {
KeyList<K, V> keyList = keyToKeyList.remove(node.key);
keyList.count = 0;
modCount++;
} else {
KeyList<K, V> keyList = keyToKeyList.get(node.key);
keyList.count--;
if (node.previousSibling == null) {
keyList.head = node.nextSibling;
} else {
node.previousSibling.nextSibling = node.nextSibling;
}
if (node.nextSibling == null) {
keyList.tail = node.previousSibling;
} else {
node.nextSibling.previousSibling = node.previousSibling;
}
}
size--;
}
/** Removes all nodes for the specified key. */
private void removeAllNodes(@Nullable Object key) {
Iterators.clear(new ValueForKeyIterator(key));
}
/** Helper method for verifying that an iterator element is present. */
private static void checkElement(@Nullable Object node) {
if (node == null) {
throw new NoSuchElementException();
}
}
/** An {@code Iterator} over all nodes. */
private class NodeIterator implements ListIterator<Entry<K, V>> {
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
int expectedModCount = modCount;
NodeIterator(int index) {
int size = size();
checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = head;
while (index-- > 0) {
next();
}
}
current = null;
}
private void checkForConcurrentModification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForConcurrentModification();
return next != null;
}
@Override
public Node<K, V> next() {
checkForConcurrentModification();
checkElement(next);
previous = current = next;
next = next.next;
nextIndex++;
return current;
}
@Override
public void remove() {
checkForConcurrentModification();
checkRemove(current != null);
if (current != next) { // after call to next()
previous = current.previous;
nextIndex--;
} else { // after call to previous()
next = current.next;
}
removeNode(current);
current = null;
expectedModCount = modCount;
}
@Override
public boolean hasPrevious() {
checkForConcurrentModification();
return previous != null;
}
@Override
public Node<K, V> previous() {
checkForConcurrentModification();
checkElement(previous);
next = current = previous;
previous = previous.previous;
nextIndex--;
return current;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void set(Entry<K, V> e) {
throw new UnsupportedOperationException();
}
@Override
public void add(Entry<K, V> e) {
throw new UnsupportedOperationException();
}
void setValue(V value) {
checkState(current != null);
current.value = value;
}
}
/** An {@code Iterator} over distinct keys in key head order. */
private class DistinctKeyIterator implements Iterator<K> {
final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size());
Node<K, V> next = head;
Node<K, V> current;
int expectedModCount = modCount;
private void checkForConcurrentModification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForConcurrentModification();
return next != null;
}
@Override
public K next() {
checkForConcurrentModification();
checkElement(next);
current = next;
seenKeys.add(current.key);
do { // skip ahead to next unseen key
next = next.next;
} while ((next != null) && !seenKeys.add(next.key));
return current.key;
}
@Override
public void remove() {
checkForConcurrentModification();
checkRemove(current != null);
removeAllNodes(current.key);
current = null;
expectedModCount = modCount;
}
}
/** A {@code ListIterator} over values for a specified key. */
private class ValueForKeyIterator implements ListIterator<V> {
final Object key;
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
/** Constructs a new iterator over all values for the specified key. */
ValueForKeyIterator(@Nullable Object key) {
this.key = key;
KeyList<K, V> keyList = keyToKeyList.get(key);
next = (keyList == null) ? null : keyList.head;
}
/**
* Constructs a new iterator over all values for the specified key starting
* at the specified index. This constructor is optimized so that it starts
* at either the head or the tail, depending on which is closer to the
* specified index. This allows adds to the tail to be done in constant
* time.
*
* @throws IndexOutOfBoundsException if index is invalid
*/
public ValueForKeyIterator(@Nullable Object key, int index) {
KeyList<K, V> keyList = keyToKeyList.get(key);
int size = (keyList == null) ? 0 : keyList.count;
checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = (keyList == null) ? null : keyList.tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = (keyList == null) ? null : keyList.head;
while (index-- > 0) {
next();
}
}
this.key = key;
current = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public V next() {
checkElement(next);
previous = current = next;
next = next.nextSibling;
nextIndex++;
return current.value;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@Override
public V previous() {
checkElement(previous);
next = current = previous;
previous = previous.previousSibling;
nextIndex--;
return current.value;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void remove() {
checkRemove(current != null);
if (current != next) { // after call to next()
previous = current.previousSibling;
nextIndex--;
} else { // after call to previous()
next = current.nextSibling;
}
removeNode(current);
current = null;
}
@Override
public void set(V value) {
checkState(current != null);
current.value = value;
}
@Override
@SuppressWarnings("unchecked")
public void add(V value) {
previous = addNode((K) key, value, next);
nextIndex++;
current = null;
}
}
// Query Operations
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public boolean containsKey(@Nullable Object key) {
return keyToKeyList.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
// Modification Operations
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} always
*/
@Override
public boolean put(@Nullable K key, @Nullable V value) {
addNode(key, value, null);
return true;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>If any entries for the specified {@code key} already exist in the
* multimap, their values are changed in-place without affecting the iteration
* order.
*
* <p>The returned list is immutable and implements
* {@link java.util.RandomAccess}.
*/
@Override
public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
List<V> oldValues = getCopy(key);
ListIterator<V> keyValues = new ValueForKeyIterator(key);
Iterator<? extends V> newValues = values.iterator();
// Replace existing values, if any.
while (keyValues.hasNext() && newValues.hasNext()) {
keyValues.next();
keyValues.set(newValues.next());
}
// Remove remaining old values, if any.
while (keyValues.hasNext()) {
keyValues.next();
keyValues.remove();
}
// Add remaining new values, if any.
while (newValues.hasNext()) {
keyValues.add(newValues.next());
}
return oldValues;
}
private List<V> getCopy(@Nullable Object key) {
return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key)));
}
/**
* {@inheritDoc}
*
* <p>The returned list is immutable and implements
* {@link java.util.RandomAccess}.
*/
@Override
public List<V> removeAll(@Nullable Object key) {
List<V> oldValues = getCopy(key);
removeAllNodes(key);
return oldValues;
}
@Override
public void clear() {
head = null;
tail = null;
keyToKeyList.clear();
size = 0;
modCount++;
}
// Views
/**
* {@inheritDoc}
*
* <p>If the multimap is modified while an iteration over the list is in
* progress (except through the iterator's own {@code add}, {@code set} or
* {@code remove} operations) the results of the iteration are undefined.
*
* <p>The returned list is not serializable and does not have random access.
*/
@Override
public List<V> get(final @Nullable K key) {
return new AbstractSequentialList<V>() {
@Override public int size() {
KeyList<K, V> keyList = keyToKeyList.get(key);
return (keyList == null) ? 0 : keyList.count;
}
@Override public ListIterator<V> listIterator(int index) {
return new ValueForKeyIterator(key, index);
}
};
}
@Override
Set<K> createKeySet() {
return new Sets.ImprovedAbstractSet<K>() {
@Override public int size() {
return keyToKeyList.size();
}
@Override public Iterator<K> iterator() {
return new DistinctKeyIterator();
}
@Override public boolean contains(Object key) { // for performance
return containsKey(key);
}
@Override
public boolean remove(Object o) { // for performance
return !LinkedListMultimap.this.removeAll(o).isEmpty();
}
};
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* in the order they were added to the multimap. Because the values may have
* duplicates and follow the insertion ordering, this method returns a {@link
* List}, instead of the {@link Collection} specified in the {@link
* ListMultimap} interface.
*/
@Override
public List<V> values() {
return (List<V>) super.values();
}
@Override
List<V> createValues() {
return new AbstractSequentialList<V>() {
@Override public int size() {
return size;
}
@Override public ListIterator<V> listIterator(int index) {
final NodeIterator nodeItr = new NodeIterator(index);
return new TransformedListIterator<Entry<K, V>, V>(nodeItr) {
@Override
V transform(Entry<K, V> entry) {
return entry.getValue();
}
@Override
public void set(V value) {
nodeItr.setValue(value);
}
};
}
};
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the entries
* in the order they were added to the multimap. Because the entries may have
* duplicates and follow the insertion ordering, this method returns a {@link
* List}, instead of the {@link Collection} specified in the {@link
* ListMultimap} interface.
*
* <p>An entry's {@link Entry#getKey} method always returns the same key,
* regardless of what happens subsequently. As long as the corresponding
* key-value mapping is not removed from the multimap, {@link Entry#getValue}
* returns the value from the multimap, which may change over time, and {@link
* Entry#setValue} modifies that value. Removing the mapping from the
* multimap does not alter the value returned by {@code getValue()}, though a
* subsequent {@code setValue()} call won't update the multimap but will lead
* to a revised value being returned by {@code getValue()}.
*/
@Override
public List<Entry<K, V>> entries() {
return (List<Entry<K, V>>) super.entries();
}
@Override
List<Entry<K, V>> createEntries() {
return new AbstractSequentialList<Entry<K, V>>() {
@Override public int size() {
return size;
}
@Override public ListIterator<Entry<K, V>> listIterator(int index) {
return new NodeIterator(index);
}
};
}
@Override
Iterator<Entry<K, V>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
Map<K, Collection<V>> createAsMap() {
return new Multimaps.AsMap<K, V>(this);
}
/**
* @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(size());
for (Entry<K, V> entry : entries()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyToKeyList = Maps.newLinkedHashMap();
int size = stream.readInt();
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();
put(key, value);
}
}
@GwtIncompatible("java serialization not supported")
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/LinkedListMultimap.java | Java | asf20 | 24,783 |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Nullable;
/**
* An ordering that treats all references as equals, even nulls.
*
* @author Emily Soldal
*/
@GwtCompatible(serializable = true)
final class AllEqualOrdering extends Ordering<Object> implements Serializable {
static final AllEqualOrdering INSTANCE = new AllEqualOrdering();
@Override
public int compare(@Nullable Object left, @Nullable Object right) {
return 0;
}
@Override
public <E> List<E> sortedCopy(Iterable<E> iterable) {
return Lists.newArrayList(iterable);
}
@Override
public <E> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
return ImmutableList.copyOf(iterable);
}
@SuppressWarnings("unchecked")
@Override
public <S> Ordering<S> reverse() {
return (Ordering<S>) this;
}
private Object readResolve() {
return INSTANCE;
}
@Override
public String toString() {
return "Ordering.allEqual()";
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/AllEqualOrdering.java | Java | asf20 | 1,721 |
/*
* 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.collect.CollectPreconditions.checkEntryNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMapEntry.TerminalEntry;
import javax.annotation.Nullable;
/**
* 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 ImmutableMapEntry<K, V>[] entries;
// array of linked lists of entries
private final transient ImmutableMapEntry<K, V>[] table;
// 'and' with an int to get a table index
private final transient int mask;
RegularImmutableMap(TerminalEntry<?, ?>... theEntries) {
this(theEntries.length, theEntries);
}
/**
* Constructor for RegularImmutableMap that takes as input an array of {@code TerminalEntry}
* entries. Assumes that these entries have already been checked for null.
*
* <p>This allows reuse of the entry objects from the array in the actual implementation.
*/
RegularImmutableMap(int size, TerminalEntry<?, ?>[] theEntries) {
entries = createEntryArray(size);
int tableSize = Hashing.closedTableSize(size, MAX_LOAD_FACTOR);
table = createEntryArray(tableSize);
mask = tableSize - 1;
for (int entryIndex = 0; entryIndex < size; entryIndex++) {
@SuppressWarnings("unchecked")
TerminalEntry<K, V> entry = (TerminalEntry<K, V>) theEntries[entryIndex];
K key = entry.getKey();
int tableIndex = Hashing.smear(key.hashCode()) & mask;
@Nullable ImmutableMapEntry<K, V> existing = table[tableIndex];
// prepend, not append, so the entries can be immutable
ImmutableMapEntry<K, V> newEntry = (existing == null)
? entry
: new NonTerminalMapEntry<K, V>(entry, existing);
table[tableIndex] = newEntry;
entries[entryIndex] = newEntry;
checkNoConflictInBucket(key, newEntry, existing);
}
}
/**
* Constructor for RegularImmutableMap that makes no assumptions about the input entries.
*/
RegularImmutableMap(Entry<?, ?>[] theEntries) {
int size = theEntries.length;
entries = createEntryArray(size);
int tableSize = Hashing.closedTableSize(size, MAX_LOAD_FACTOR);
table = createEntryArray(tableSize);
mask = tableSize - 1;
for (int entryIndex = 0; entryIndex < size; entryIndex++) {
@SuppressWarnings("unchecked") // all our callers carefully put in only Entry<K, V>s
Entry<K, V> entry = (Entry<K, V>) theEntries[entryIndex];
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int tableIndex = Hashing.smear(key.hashCode()) & mask;
@Nullable ImmutableMapEntry<K, V> existing = table[tableIndex];
// prepend, not append, so the entries can be immutable
ImmutableMapEntry<K, V> newEntry = (existing == null)
? new TerminalEntry<K, V>(key, value)
: new NonTerminalMapEntry<K, V>(key, value, existing);
table[tableIndex] = newEntry;
entries[entryIndex] = newEntry;
checkNoConflictInBucket(key, newEntry, existing);
}
}
private void checkNoConflictInBucket(
K key, ImmutableMapEntry<K, V> entry, ImmutableMapEntry<K, V> bucketHead) {
for (; bucketHead != null; bucketHead = bucketHead.getNextInKeyBucket()) {
checkNoConflict(!key.equals(bucketHead.getKey()), "key", entry, bucketHead);
}
}
private static final class NonTerminalMapEntry<K, V> extends ImmutableMapEntry<K, V> {
private final ImmutableMapEntry<K, V> nextInKeyBucket;
NonTerminalMapEntry(K key, V value, ImmutableMapEntry<K, V> nextInKeyBucket) {
super(key, value);
this.nextInKeyBucket = nextInKeyBucket;
}
NonTerminalMapEntry(ImmutableMapEntry<K, V> contents, ImmutableMapEntry<K, V> nextInKeyBucket) {
super(contents);
this.nextInKeyBucket = nextInKeyBucket;
}
@Override
ImmutableMapEntry<K, V> getNextInKeyBucket() {
return nextInKeyBucket;
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInValueBucket() {
return null;
}
}
/**
* Closed addressing tends to perform well even with high load factors.
* Being conservative here ensures that the table is still likely to be
* relatively sparse (hence it misses fast) while saving space.
*/
private static final double MAX_LOAD_FACTOR = 1.2;
/**
* Creates an {@code ImmutableMapEntry} array to hold parameterized entries. The
* result must never be upcast back to ImmutableMapEntry[] (or Object[], etc.), or
* allowed to escape the class.
*/
@SuppressWarnings("unchecked") // Safe as long as the javadocs are followed
private ImmutableMapEntry<K, V>[] createEntryArray(int size) {
return new ImmutableMapEntry[size];
}
@Override public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int index = Hashing.smear(key.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = table[index];
entry != null;
entry = entry.getNextInKeyBucket()) {
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 boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
private class EntrySet extends ImmutableMapEntrySet<K, V> {
@Override ImmutableMap<K, V> map() {
return RegularImmutableMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<K, V>> createAsList() {
return new RegularImmutableAsList<Entry<K, V>>(this, entries);
}
}
// 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;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/RegularImmutableMap.java | Java | asf20 | 7,235 |
/*
* 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;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true)
class EmptyImmutableListMultimap extends ImmutableListMultimap<Object, Object> {
static final EmptyImmutableListMultimap INSTANCE
= new EmptyImmutableListMultimap();
private EmptyImmutableListMultimap() {
super(ImmutableMap.<Object, ImmutableList<Object>>of(), 0);
}
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava/src/com/google/common/collect/EmptyImmutableListMultimap.java | Java | asf20 | 1,255 |