code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.base;
import com.google.common.annotations.GwtCompatible;
/**
* Static methods pertaining to ASCII characters (those in the range of values
* {@code 0x00} through {@code 0x7F}), and to strings containing such
* characters.
*
* <p>ASCII utilities also exist in other classes of this package:
* <ul>
* <!-- TODO(kevinb): how can we make this not produce a warning when building gwt javadoc? -->
* <li>{@link Charsets#US_ASCII} specifies the {@code Charset} of ASCII characters.
* <li>{@link CharMatcher#ASCII} matches ASCII characters and provides text processing methods
* which operate only on the ASCII characters of a string.
* </ul>
*
* @author Craig Berry
* @author Gregory Kick
* @since 7.0
*/
@GwtCompatible
public final class Ascii {
private Ascii() {}
/* The ASCII control characters, per RFC 20. */
/**
* Null ('\0'): The all-zeros character which may serve to accomplish
* time fill and media fill. Normally used as a C string terminator.
* <p>Although RFC 20 names this as "Null", note that it is distinct
* from the C/C++ "NULL" pointer.
*
* @since 8.0
*/
public static final byte NUL = 0;
/**
* Start of Heading: A communication control character used at
* the beginning of a sequence of characters which constitute a
* machine-sensible address or routing information. Such a sequence is
* referred to as the "heading." An STX character has the effect of
* terminating a heading.
*
* @since 8.0
*/
public static final byte SOH = 1;
/**
* Start of Text: A communication control character which
* precedes a sequence of characters that is to be treated as an entity
* and entirely transmitted through to the ultimate destination. Such a
* sequence is referred to as "text." STX may be used to terminate a
* sequence of characters started by SOH.
*
* @since 8.0
*/
public static final byte STX = 2;
/**
* End of Text: A communication control character used to
* terminate a sequence of characters started with STX and transmitted
* as an entity.
*
* @since 8.0
*/
public static final byte ETX = 3;
/**
* End of Transmission: A communication control character used
* to indicate the conclusion of a transmission, which may have
* contained one or more texts and any associated headings.
*
* @since 8.0
*/
public static final byte EOT = 4;
/**
* Enquiry: A communication control character used in data
* communication systems as a request for a response from a remote
* station. It may be used as a "Who Are You" (WRU) to obtain
* identification, or may be used to obtain station status, or both.
*
* @since 8.0
*/
public static final byte ENQ = 5;
/**
* Acknowledge: A communication control character transmitted
* by a receiver as an affirmative response to a sender.
*
* @since 8.0
*/
public static final byte ACK = 6;
/**
* Bell ('\a'): A character for use when there is a need to call for
* human attention. It may control alarm or attention devices.
*
* @since 8.0
*/
public static final byte BEL = 7;
/**
* Backspace ('\b'): A format effector which controls the movement of
* the printing position one printing space backward on the same
* printing line. (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte BS = 8;
/**
* Horizontal Tabulation ('\t'): A format effector which controls the
* movement of the printing position to the next in a series of
* predetermined positions along the printing line. (Applicable also to
* display devices and the skip function on punched cards.)
*
* @since 8.0
*/
public static final byte HT = 9;
/**
* Line Feed ('\n'): A format effector which controls the movement of
* the printing position to the next printing line. (Applicable also to
* display devices.) Where appropriate, this character may have the
* meaning "New Line" (NL), a format effector which controls the
* movement of the printing point to the first printing position on the
* next printing line. Use of this convention requires agreement
* between sender and recipient of data.
*
* @since 8.0
*/
public static final byte LF = 10;
/**
* Alternate name for {@link #LF}. ({@code LF} is preferred.)
*
* @since 8.0
*/
public static final byte NL = 10;
/**
* Vertical Tabulation ('\v'): A format effector which controls the
* movement of the printing position to the next in a series of
* predetermined printing lines. (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte VT = 11;
/**
* Form Feed ('\f'): A format effector which controls the movement of
* the printing position to the first pre-determined printing line on
* the next form or page. (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte FF = 12;
/**
* Carriage Return ('\r'): A format effector which controls the
* movement of the printing position to the first printing position on
* the same printing line. (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte CR = 13;
/**
* Shift Out: A control character indicating that the code
* combinations which follow shall be interpreted as outside of the
* character set of the standard code table until a Shift In character
* is reached.
*
* @since 8.0
*/
public static final byte SO = 14;
/**
* Shift In: A control character indicating that the code
* combinations which follow shall be interpreted according to the
* standard code table.
*
* @since 8.0
*/
public static final byte SI = 15;
/**
* Data Link Escape: A communication control character which
* will change the meaning of a limited number of contiguously following
* characters. It is used exclusively to provide supplementary controls
* in data communication networks.
*
* @since 8.0
*/
public static final byte DLE = 16;
/**
* Device Control 1. Characters for the control
* of ancillary devices associated with data processing or
* telecommunication systems, more especially switching devices "on" or
* "off." (If a single "stop" control is required to interrupt or turn
* off ancillary devices, DC4 is the preferred assignment.)
*
* @since 8.0
*/
public static final byte DC1 = 17; // aka XON
/**
* Transmission On: Although originally defined as DC1, this ASCII
* control character is now better known as the XON code used for software
* flow control in serial communications. The main use is restarting
* the transmission after the communication has been stopped by the XOFF
* control code.
*
* @since 8.0
*/
public static final byte XON = 17; // aka DC1
/**
* Device Control 2. Characters for the control
* of ancillary devices associated with data processing or
* telecommunication systems, more especially switching devices "on" or
* "off." (If a single "stop" control is required to interrupt or turn
* off ancillary devices, DC4 is the preferred assignment.)
*
* @since 8.0
*/
public static final byte DC2 = 18;
/**
* Device Control 3. Characters for the control
* of ancillary devices associated with data processing or
* telecommunication systems, more especially switching devices "on" or
* "off." (If a single "stop" control is required to interrupt or turn
* off ancillary devices, DC4 is the preferred assignment.)
*
* @since 8.0
*/
public static final byte DC3 = 19; // aka XOFF
/**
* Transmission off. See {@link #XON} for explanation.
*
* @since 8.0
*/
public static final byte XOFF = 19; // aka DC3
/**
* Device Control 4. Characters for the control
* of ancillary devices associated with data processing or
* telecommunication systems, more especially switching devices "on" or
* "off." (If a single "stop" control is required to interrupt or turn
* off ancillary devices, DC4 is the preferred assignment.)
*
* @since 8.0
*/
public static final byte DC4 = 20;
/**
* Negative Acknowledge: A communication control character
* transmitted by a receiver as a negative response to the sender.
*
* @since 8.0
*/
public static final byte NAK = 21;
/**
* Synchronous Idle: A communication control character used by
* a synchronous transmission system in the absence of any other
* character to provide a signal from which synchronism may be achieved
* or retained.
*
* @since 8.0
*/
public static final byte SYN = 22;
/**
* End of Transmission Block: A communication control character
* used to indicate the end of a block of data for communication
* purposes. ETB is used for blocking data where the block structure is
* not necessarily related to the processing format.
*
* @since 8.0
*/
public static final byte ETB = 23;
/**
* Cancel: A control character used to indicate that the data
* with which it is sent is in error or is to be disregarded.
*
* @since 8.0
*/
public static final byte CAN = 24;
/**
* End of Medium: A control character associated with the sent
* data which may be used to identify the physical end of the medium, or
* the end of the used, or wanted, portion of information recorded on a
* medium. (The position of this character does not necessarily
* correspond to the physical end of the medium.)
*
* @since 8.0
*/
public static final byte EM = 25;
/**
* Substitute: A character that may be substituted for a
* character which is determined to be invalid or in error.
*
* @since 8.0
*/
public static final byte SUB = 26;
/**
* Escape: A control character intended to provide code
* extension (supplementary characters) in general information
* interchange. The Escape character itself is a prefix affecting the
* interpretation of a limited number of contiguously following
* characters.
*
* @since 8.0
*/
public static final byte ESC = 27;
/**
* File Separator: These four information separators may be
* used within data in optional fashion, except that their hierarchical
* relationship shall be: FS is the most inclusive, then GS, then RS,
* and US is least inclusive. (The content and length of a File, Group,
* Record, or Unit are not specified.)
*
* @since 8.0
*/
public static final byte FS = 28;
/**
* Group Separator: These four information separators may be
* used within data in optional fashion, except that their hierarchical
* relationship shall be: FS is the most inclusive, then GS, then RS,
* and US is least inclusive. (The content and length of a File, Group,
* Record, or Unit are not specified.)
*
* @since 8.0
*/
public static final byte GS = 29;
/**
* Record Separator: These four information separators may be
* used within data in optional fashion, except that their hierarchical
* relationship shall be: FS is the most inclusive, then GS, then RS,
* and US is least inclusive. (The content and length of a File, Group,
* Record, or Unit are not specified.)
*
* @since 8.0
*/
public static final byte RS = 30;
/**
* Unit Separator: These four information separators may be
* used within data in optional fashion, except that their hierarchical
* relationship shall be: FS is the most inclusive, then GS, then RS,
* and US is least inclusive. (The content and length of a File, Group,
* Record, or Unit are not specified.)
*
* @since 8.0
*/
public static final byte US = 31;
/**
* Space: A normally non-printing graphic character used to
* separate words. It is also a format effector which controls the
* movement of the printing position, one printing position forward.
* (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte SP = 32;
/**
* Alternate name for {@link #SP}.
*
* @since 8.0
*/
public static final byte SPACE = 32;
/**
* Delete: This character is used primarily to "erase" or
* "obliterate" erroneous or unwanted characters in perforated tape.
*
* @since 8.0
*/
public static final byte DEL = 127;
/**
* The minimum value of an ASCII character.
*
* @since 9.0 (was type {@code int} before 12.0)
*/
public static final char MIN = 0;
/**
* The maximum value of an ASCII character.
*
* @since 9.0 (was type {@code int} before 12.0)
*/
public static final char MAX = 127;
/**
* Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII
* characters} have been converted to lowercase. All other characters are copied without
* modification.
*/
public static String toLowerCase(String string) {
int length = string.length();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(toLowerCase(string.charAt(i)));
}
return builder.toString();
}
/**
* If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character} returns the
* lowercase equivalent. Otherwise returns the argument.
*/
public static char toLowerCase(char c) {
return isUpperCase(c) ? (char) (c ^ 0x20) : c;
}
/**
* Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII
* characters} have been converted to uppercase. All other characters are copied without
* modification.
*/
public static String toUpperCase(String string) {
int length = string.length();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(toUpperCase(string.charAt(i)));
}
return builder.toString();
}
/**
* If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character} returns the
* uppercase equivalent. Otherwise returns the argument.
*/
public static char toUpperCase(char c) {
return isLowerCase(c) ? (char) (c & 0x5f) : c;
}
/**
* Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters
* between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters)
* return {@code false}.
*/
public static boolean isLowerCase(char c) {
return (c >= 'a') && (c <= 'z');
}
/**
* Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters
* between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters)
* return {@code false}.
*/
public static boolean isUpperCase(char c) {
return (c >= 'A') && (c <= 'Z');
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.lang.reflect.Field;
import javax.annotation.Nullable;
/**
* Utility methods for working with {@link Enum} instances.
*
* @author Steve McKay
*
* @since 9.0
*/
@GwtCompatible(emulated = true)
@Beta
public final class Enums {
private Enums() {}
/**
* Returns the {@link Field} in which {@code enumValue} is defined.
* For example, to get the {@code Description} annotation on the {@code GOLF}
* constant of enum {@code Sport}, use
* {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
*
* @since 12.0
*/
@GwtIncompatible("reflection")
public static Field getField(Enum<?> enumValue) {
Class<?> clazz = enumValue.getDeclaringClass();
try {
return clazz.getDeclaredField(enumValue.name());
} catch (NoSuchFieldException impossible) {
throw new AssertionError(impossible);
}
}
/**
* Returns a {@link Function} that maps an {@link Enum} name to the associated
* {@code Enum} constant. The {@code Function} will return {@code null} if the
* {@code Enum} constant does not exist.
*
* @param enumClass the {@link Class} of the {@code Enum} declaring the
* constant values.
*/
public static <T extends Enum<T>> Function<String, T> valueOfFunction(Class<T> enumClass) {
return new ValueOfFunction<T>(enumClass);
}
/**
* A {@link Function} that maps an {@link Enum} name to the associated
* constant, or {@code null} if the constant does not exist.
*/
private static final class ValueOfFunction<T extends Enum<T>>
implements Function<String, T>, Serializable {
private final Class<T> enumClass;
private ValueOfFunction(Class<T> enumClass) {
this.enumClass = checkNotNull(enumClass);
}
@Override
public T apply(String value) {
try {
return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) {
return null;
}
}
@Override public boolean equals(@Nullable Object obj) {
return obj instanceof ValueOfFunction &&
enumClass.equals(((ValueOfFunction) obj).enumClass);
}
@Override public int hashCode() {
return enumClass.hashCode();
}
@Override public String toString() {
return "Enums.valueOf(" + enumClass + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
* constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
* user input or falling back to a default enum constant. For example,
* {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
*
* @since 12.0
*/
public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
checkNotNull(enumClass);
checkNotNull(value);
try {
return Optional.of(Enum.valueOf(enumClass, value));
} catch (IllegalArgumentException iae) {
return Optional.absent();
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* This class provides default values for all Java types, as defined by the JLS.
*
* @author Ben Yu
* @since 1.0
*/
public final class Defaults {
private Defaults() {}
private static final Map<Class<?>, Object> DEFAULTS;
static {
Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
put(map, boolean.class, false);
put(map, char.class, '\0');
put(map, byte.class, (byte) 0);
put(map, short.class, (short) 0);
put(map, int.class, 0);
put(map, long.class, 0L);
put(map, float.class, 0f);
put(map, double.class, 0d);
DEFAULTS = Collections.unmodifiableMap(map);
}
private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) {
map.put(type, value);
}
/**
* Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
* false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
* {@code void}, null is returned.
*/
@SuppressWarnings("unchecked")
public static <T> T defaultValue(Class<T> type) {
return (T) DEFAULTS.get(type);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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.
*/
@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
public Object apply(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.
*/
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(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.
*
* @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(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(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.toString() + "(" + f.toString() + ")";
}
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(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;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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() {}
/** Returns a thread-local 1024-char array. */
static char[] charBufferFromThreadLocal() {
return DEST_TL.get();
}
/** Calls {@link System#nanoTime()}. */
static long systemNanoTime() {
return System.nanoTime();
}
/**
* A thread-local destination buffer to keep us from creating new buffers.
* The starting size is 1024 characters. If we grow past this we don't
* put it back in the threadlocal, we just keep going and grow as needed.
*/
private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() {
@Override
protected char[] initialValue() {
return new char[1024];
}
};
static CharMatcher precomputeCharMatcher(CharMatcher matcher) {
return matcher.precomputedInternal();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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();
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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.
*/
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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();
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
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> implements Table<R, C, V> {
/** Returns an empty immutable table. */
@SuppressWarnings("unchecked")
public static final <R, C, V> ImmutableTable<R, C, V> of() {
return (ImmutableTable<R, C, V>) EmptyImmutableTable.INSTANCE;
}
/** Returns an immutable table containing a single cell. */
public static final <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 final <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 final <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 abstract ImmutableSet<Cell<R, C, V>> cellSet();
/**
* {@inheritDoc}
*
* @throws NullPointerException if {@code columnKey} is {@code null}
*/
@Override public abstract ImmutableMap<R, V> column(C columnKey);
@Override public abstract ImmutableSet<C> columnKeySet();
/**
* {@inheritDoc}
*
* <p>The value {@code Map<R, V>}s in the returned map are
* {@link ImmutableMap}s as well.
*/
@Override public abstract ImmutableMap<C, Map<R, V>> columnMap();
/**
* {@inheritDoc}
*
* @throws NullPointerException if {@code rowKey} is {@code null}
*/
@Override public abstract ImmutableMap<C, V> row(R rowKey);
@Override public abstract ImmutableSet<R> rowKeySet();
/**
* {@inheritDoc}
*
* <p>The value {@code Map<C, V>}s in the returned map are
* {@link ImmutableMap}s as well.
*/
@Override public abstract ImmutableMap<R, Map<C, V>> rowMap();
/**
* 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();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Table) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
return this.cellSet().equals(that.cellSet());
} else {
return false;
}
}
@Override public int hashCode() {
return cellSet().hashCode();
}
@Override public String toString() {
return rowMap().toString();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
/**
* 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);
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.BoundType.CLOSED;
import static com.google.common.collect.BoundType.OPEN;
import 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() {
StringBuilder builder = new StringBuilder();
builder.append(comparator).append(":");
switch (getLowerBoundType()) {
case CLOSED:
builder.append('[');
break;
case OPEN:
builder.append('(');
break;
}
if (hasLowerBound()) {
builder.append(getLowerEndpoint());
} else {
builder.append("-\u221e");
}
builder.append(',');
if (hasUpperBound()) {
builder.append(getUpperEndpoint());
} else {
builder.append("\u221e");
}
switch (getUpperBoundType()) {
case CLOSED:
builder.append(']');
break;
case OPEN:
builder.append(')');
break;
}
return builder.toString();
}
T getLowerEndpoint() {
return lowerEndpoint;
}
BoundType getLowerBoundType() {
return lowerBoundType;
}
T getUpperEndpoint() {
return upperEndpoint;
}
BoundType getUpperBoundType() {
return upperBoundType;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import 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>
*
* 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>
*
* 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> {
private final Comparator<? super E> comparator;
/**
* 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(comparator));
this.comparator = 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 implements Serializable {
Comparator comparator;
Object[] elements;
int[] counts;
SerializedForm(SortedMultiset<?> multiset) {
this.comparator = multiset.comparator();
int n = multiset.entrySet().size();
elements = new Object[n];
counts = new int[n];
int i = 0;
for (Entry<?> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
@SuppressWarnings("unchecked")
Object readResolve() {
int n = elements.length;
Builder<Object> builder = orderedBy(comparator);
for (int i = 0; i < n; i++) {
builder.addCopies(elements[i], counts[i]);
}
return builder.build();
}
}
@Override
Object writeReplace() {
return new SerializedForm(this);
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
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
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 SortedSet<E> elementSet() {
return (SortedSet<E>) super.elementSet();
}
@Override
SortedSet<E> createElementSet() {
return new SortedMultisets.ElementSet<E>() {
@Override
SortedMultiset<E> multiset() {
return AbstractSortedMultiset.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 SortedMultisets.DescendingMultiset<E>() {
@Override
SortedMultiset<E> forwardMultiset() {
return AbstractSortedMultiset.this;
}
@Override
Iterator<Entry<E>> entryIterator() {
return descendingEntryIterator();
}
@Override
public Iterator<E> iterator() {
return descendingIterator();
}
};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.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>
*
* 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 copyOf(Ordering.natural(), Arrays.asList(e1, e2));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5) {
return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4, e5));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
int size = remaining.length + 6;
List<E> all = new ArrayList<E>(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, remaining);
return copyOf(Ordering.natural(), all);
}
// TODO(kevinb): Consider factory methods that reject duplicates
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@link Comparable#compareTo}, only the first one specified is included.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(
E[] elements) {
return copyOf(Ordering.natural(), Arrays.asList(elements));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@code compareTo()}, only the first one specified is included. To create a
* copy of a {@code SortedSet} that preserves the comparator, call {@link
* #copyOfSorted} instead. This method iterates over {@code elements} at most
* once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code
* ImmutableSortedSet.copyOf(s)} returns an {@code ImmutableSortedSet<String>}
* containing each of the strings in {@code s}, while {@code
* ImmutableSortedSet.of(s)} returns an {@code
* ImmutableSortedSet<Set<String>>} containing one element (the given set
* itself).
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* <p>This method is not type-safe, as it may be called on elements that are
* not mutually comparable.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Iterable<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@code compareTo()}, only the first one specified is included. To create a
* copy of a {@code SortedSet} that preserves the comparator, call
* {@link #copyOfSorted} instead. This method iterates over {@code elements}
* at most once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then
* {@code ImmutableSortedSet.copyOf(s)} returns an
* {@code ImmutableSortedSet<String>} containing each of the strings in
* {@code s}, while {@code ImmutableSortedSet.of(s)} returns an
* {@code ImmutableSortedSet<Set<String>>} containing one element (the given
* set itself).
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code elements}
* is an {@code ImmutableSortedSet}, it may be returned instead of a copy.
*
* <p>This method is not type-safe, as it may be called on elements that are
* not mutually comparable.
*
* <p>This method is safe to use even when {@code elements} is a synchronized
* or concurrent collection that is currently being modified by another
* thread.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSortedSet<E> copyOf(
Collection<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* their natural ordering. When multiple elements are equivalent according to
* {@code compareTo()}, only the first one specified is included.
*
* <p>This method is not type-safe, as it may be called on elements that are
* not mutually comparable.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Iterator<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
return 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 copyOf(comparator, Lists.newArrayList(elements));
}
/**
* Returns an immutable sorted set containing the given elements sorted by
* the given {@code Comparator}. When multiple elements are equivalent
* according to {@code compare()}, only the first one specified is
* included. This method iterates over {@code elements} at most once.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if {@code comparator} or any of {@code
* elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
checkNotNull(comparator);
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);
E[] elements = (E[]) sortedSet.toArray();
if (elements.length == 0) {
return emptySet(comparator);
} else {
return new RegularImmutableSortedSet<E>(
ImmutableList.<E>asImmutableList(elements), comparator);
}
}
/**
* Sorts and eliminates duplicates from the first {@code n} positions in {@code contents}.
* Returns the number of unique elements. If this returns {@code k}, then the first {@code k}
* elements of {@code contents} will be the sorted, unique elements, and {@code
* contents[i] == null} for {@code k <= i < n}.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code contents} is
* null
*/
static <E> int sortAndUnique(
Comparator<? super E> comparator, int n, E... contents) {
if (n == 0) {
return 0;
}
for (int i = 0; i < n; i++) {
ObjectArrays.checkElementNotNull(contents[i], i);
}
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 uniques;
}
/**
* 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) {
int uniques = sortAndUnique(comparator, n, contents);
if (uniques == 0) {
return emptySet(comparator);
} else if (uniques < contents.length) {
contents = ObjectArrays.arraysCopyOf(contents, uniques);
}
return new RegularImmutableSortedSet<E>(
ImmutableList.<E>asImmutableList(contents), comparator);
}
/**
* Returns a builder that creates immutable sorted sets with an explicit
* comparator. If the comparator has a more general type than the set being
* generated, such as creating a {@code SortedSet<Integer>} with a
* {@code Comparator<Number>}, use the {@link Builder} constructor instead.
*
* @throws NullPointerException if {@code comparator} is null
*/
public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
return new Builder<E>(comparator);
}
/**
* Returns a builder that creates immutable sorted sets whose elements are
* ordered by the reverse of their natural ordering.
*
* <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather
* than {@code Comparable<? super E>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <E extends Comparable<E>> Builder<E> reverseOrder() {
return new Builder<E>(Ordering.natural().reverse());
}
/**
* Returns a builder that creates immutable sorted sets whose elements are
* ordered by their natural ordering. The sorted sets use {@link
* Ordering#natural()} as the comparator. This method provides more
* type-safety than {@link #builder}, as it can be called only for classes
* that implement {@link Comparable}.
*
* <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather
* than {@code Comparable<? super E>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <E extends Comparable<E>> Builder<E> naturalOrder() {
return new Builder<E>(Ordering.natural());
}
/**
* A builder for creating immutable sorted set instances, especially {@code
* public static final} sets ("constant sets"), with a given comparator.
* Example: <pre> {@code
*
* public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
* new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
* .addAll(SINGLE_DIGIT_PRIMES)
* .add(42)
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple sets in series. Each set is a superset of the set
* created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<E> extends ImmutableSet.Builder<E> {
private final Comparator<? super E> comparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSortedSet#orderedBy}.
*/
public Builder(Comparator<? super E> comparator) {
this.comparator = checkNotNull(comparator);
}
/**
* Adds {@code element} to the {@code ImmutableSortedSet}. If the
* {@code ImmutableSortedSet} already contains {@code element}, then
* {@code add} has no effect. (only the previously added element
* is retained).
*
* @param element the element to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
*/
@Override public Builder<E> add(E element) {
super.add(element);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@Override public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSortedSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet},
* ignoring duplicate elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSortedSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Returns a newly-created {@code ImmutableSortedSet} based on the contents
* of the {@code Builder} and its comparator.
*/
@Override public ImmutableSortedSet<E> build() {
@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 Iterables.getFirst(headSet(e, false).descendingSet(), null);
}
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public E floor(E e) {
return Iterables.getFirst(headSet(e, true).descendingSet(), 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);
}
/**
* 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() {
ImmutableSortedSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = createDescendingSet();
result.descendingSet = this;
}
return result;
}
@GwtIncompatible("NavigableSet")
abstract ImmutableSortedSet<E> createDescendingSet();
/**
* @since 12.0
*/
@GwtIncompatible("NavigableSet")
@Override
public UnmodifiableIterator<E> descendingIterator() {
return descendingSet().iterator();
}
/**
* Returns the position of an element within the set, or -1 if not present.
*/
abstract int indexOf(@Nullable Object target);
/*
* This class is used to serialize all ImmutableSortedSet instances,
* regardless of implementation type. It captures their "logical contents"
* only. This is necessary to ensure that the existence of a particular
* implementation type is an implementation detail.
*/
private static class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final Object[] elements;
public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
this.comparator = comparator;
this.elements = elements;
}
@SuppressWarnings("unchecked")
Object readResolve() {
return new Builder<E>(comparator).add((E[]) elements).build();
}
private static final long serialVersionUID = 0;
}
private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override Object writeReplace() {
return new SerializedForm<E>(comparator, toArray());
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet.ArrayImmutableSet;
/**
* Implementation of {@link ImmutableSet} with two or more elements.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class RegularImmutableSet<E> extends ArrayImmutableSet<E> {
// the same elements in hashed positions (plus nulls)
@VisibleForTesting final transient Object[] table;
// 'and' with an int to get a valid table index.
private final transient int mask;
private final transient int hashCode;
RegularImmutableSet(
Object[] elements, int hashCode, Object[] table, int mask) {
super(elements);
this.table = table;
this.mask = mask;
this.hashCode = hashCode;
}
@Override public boolean contains(Object target) {
if (target == null) {
return false;
}
for (int i = Hashing.smear(target.hashCode()); true; i++) {
Object candidate = table[i & mask];
if (candidate == null) {
return false;
}
if (candidate.equals(target)) {
return true;
}
}
}
@Override public int hashCode() {
return hashCode;
}
@Override boolean isHashCodeFast() {
return true;
}
}
| Java |
/*
* Copyright (C) 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(Object key) {
return delegate().containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return delegate().containsValue(value);
}
@Override
public V get(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
*/
@Beta 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
*/
@Beta protected void standardClear() {
Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
while (entryIterator.hasNext()) {
entryIterator.next();
entryIterator.remove();
}
}
/**
* 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() {}
@Override
Map<K, V> map() {
return 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() {}
@Override
Map<K, V> map() {
return 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
*/
@Beta 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
*/
@Beta 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
*/
@Beta 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
*/
@Beta 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
*/
@Beta protected String standardToString() {
return Maps.toStringImpl(this);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
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();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
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 java.util.TreeMap;
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 AbstractMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Sets.newLinkedHashSet();
}
private static final long serialVersionUID = 0;
}
/**
* Multimap for {@link ImmutableSetMultimap.Builder} that sorts keys and
* maintains value orderings.
*/
private static class SortedKeyBuilderMultimap<K, V>
extends AbstractMultimap<K, V> {
SortedKeyBuilderMultimap(
Comparator<? super K> keyComparator, Multimap<K, V> multimap) {
super(new TreeMap<K, Collection<V>>(keyComparator));
putAll(multimap);
}
@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>
*
* 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
*/
@Beta @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.
@Beta @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).onResultOf(new Function<Entry<K, Collection<V>>, K>() {
@Override
public K apply(Entry<K, Collection<V>> entry) {
return entry.getKey();
}
}));
for (Map.Entry<K, Collection<V>> entry : entries) {
sortedCopy.putAll(entry.getKey(), entry.getValue());
}
builderMultimap = sortedCopy;
}
return copyOf(builderMultimap, 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 = (valueComparator == null)
? ImmutableSet.copyOf(values)
: ImmutableSortedSet.copyOf(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 values are sorted and a missing key is provided.
private final transient ImmutableSortedSet<V> emptySet;
ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size,
@Nullable Comparator<? super V> valueComparator) {
super(map, size);
this.emptySet = (valueComparator == null)
? null : ImmutableSortedSet.<V>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);
if (set != null) {
return set;
} else if (emptySet != null) {
return emptySet;
} else {
return ImmutableSet.<V>of();
}
}
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
*/
@Beta
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.
*/
// TODO(kevinb): Fix this so that two copies of the entries are not created.
@Override public ImmutableSet<Entry<K, V>> entries() {
ImmutableSet<Entry<K, V>> result = entries;
return (result == null)
? (entries = ImmutableSet.copyOf(super.entries()))
: result;
}
/**
* @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, 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 = ImmutableSet.copyOf(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);
}
@GwtIncompatible("not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import 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;
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.EnumMap;
import java.util.Map;
/**
* A {@code BiMap} backed by two {@code EnumMap} instances. Null keys and values
* are not permitted. An {@code EnumBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>>
extends AbstractBiMap<K, V> {
private transient Class<K> keyType;
private transient Class<V> valueType;
/**
* Returns a new, empty {@code EnumBiMap} using the specified key and value
* types.
*
* @param keyType the key type
* @param valueType the value type
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V>
create(Class<K> keyType, Class<V> valueType) {
return new EnumBiMap<K, V>(keyType, valueType);
}
/**
* Returns a new bimap with the same mappings as the specified map. If the
* specified map is an {@code EnumBiMap}, the new bimap has the same types as
* the provided map. Otherwise, the specified map must contain at least one
* mapping, in order to determine the key and value types.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V>
create(Map<K, V> map) {
EnumBiMap<K, V> bimap = create(inferKeyType(map), inferValueType(map));
bimap.putAll(map);
return bimap;
}
private EnumBiMap(Class<K> keyType, Class<V> valueType) {
super(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
WellBehavedMap.wrap(new EnumMap<V, K>(valueType)));
this.keyType = keyType;
this.valueType = valueType;
}
static <K extends Enum<K>> Class<K> inferKeyType(Map<K, ?> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<K, ?>) map).keyType();
}
if (map instanceof EnumHashBiMap) {
return ((EnumHashBiMap<K, ?>) map).keyType();
}
checkArgument(!map.isEmpty());
return map.keySet().iterator().next().getDeclaringClass();
}
private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<?, V>) map).valueType;
}
checkArgument(!map.isEmpty());
return map.values().iterator().next().getDeclaringClass();
}
/** Returns the associated key type. */
public Class<K> keyType() {
return keyType;
}
/** Returns the associated value type. */
public Class<V> valueType() {
return valueType;
}
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override
V checkValue(V value) {
return checkNotNull(value);
}
/**
* @serialData the key class, value class, number of entries, first key, first
* value, second key, second value, and so on.
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyType);
stream.writeObject(valueType);
Serialization.writeMap(this, stream);
}
@SuppressWarnings("unchecked") // reading fields populated by writeObject
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyType = (Class<K>) stream.readObject();
valueType = (Class<V>) stream.readObject();
setDelegates(
WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
WellBehavedMap.wrap(new EnumMap<V, K>(valueType)));
Serialization.populateMap(this, stream);
}
@GwtIncompatible("not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import com.google.common.math.IntMath;
import java.io.IOException;
import java.io.ObjectInputStream;
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.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 new ImmutableEnumSet<E>(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) {
Iterator<E> iterator = elements.iterator();
if (!iterator.hasNext()) {
return ImmutableSet.of();
}
if (elements instanceof EnumSet) {
EnumSet<E> enumSetClone = EnumSet.copyOf((EnumSet<E>) elements);
return new ImmutableEnumSet<E>(enumSetClone);
}
E first = iterator.next();
EnumSet<E> set = EnumSet.of(first);
while (iterator.hasNext()) {
set.add(iterator.next());
}
return new ImmutableEnumSet<E>(set);
}
/**
* 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) {
/*
* TODO(cpovirk): noneOf() and addAll() will both throw
* NullPointerExceptions when appropriate. However, NullPointerTester will
* fail on this method because it passes in Class.class instead of an enum
* type. This means that, when iterable is null but elementType is not,
* noneOf() will throw a ClassCastException before addAll() has a chance to
* throw a NullPointerException. NullPointerTester considers this a failure.
* Ideally the test would be fixed, but it would require a special case for
* Class<E> where E extends Enum. Until that happens (if ever), leave
* checkNotNull() here. For now, contemplate the irony that checking
* elementType, the problem argument, is harmful, while checking iterable,
* the innocent bystander, is effective.
*/
checkNotNull(iterable);
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();
while (elements.hasNext()) {
set.add(elements.next());
}
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();
for (E element : elements) {
set.add(element);
}
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();
for (E element : elements) {
set.add(element);
}
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;
}
/*
* Regarding newSetForMap() and SetFromMap:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/**
* 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>
*
* 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 new SetFromMap<E>(map);
}
private static class SetFromMap<E> extends AbstractSet<E>
implements Set<E>, Serializable {
private final Map<E, Boolean> m; // The backing map
private transient Set<E> s; // Its keySet
SetFromMap(Map<E, Boolean> map) {
checkArgument(map.isEmpty(), "Map is non-empty");
m = map;
s = map.keySet();
}
@Override public void clear() {
m.clear();
}
@Override public int size() {
return m.size();
}
@Override public boolean isEmpty() {
return m.isEmpty();
}
@Override public boolean contains(Object o) {
return m.containsKey(o);
}
@Override public boolean remove(Object o) {
return m.remove(o) != null;
}
@Override public boolean add(E e) {
return m.put(e, Boolean.TRUE) == null;
}
@Override public Iterator<E> iterator() {
return s.iterator();
}
@Override public Object[] toArray() {
return s.toArray();
}
@Override public <T> T[] toArray(T[] a) {
return s.toArray(a);
}
@Override public String toString() {
return s.toString();
}
@Override public int hashCode() {
return s.hashCode();
}
@Override public boolean equals(@Nullable Object object) {
return this == object || this.s.equals(object);
}
@Override public boolean containsAll(Collection<?> c) {
return s.containsAll(c);
}
@Override public boolean removeAll(Collection<?> c) {
return s.removeAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return s.retainAll(c);
}
// addAll is the only inherited implementation
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
s = m.keySet();
}
}
/**
* 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>
*
* 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
*/
@SuppressWarnings("unchecked")
public static <E> SortedSet<E> filter(
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 FilteredCollection<E>
implements SortedSet<E> {
FilteredSortedSet(SortedSet<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);
}
@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 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>
*
* 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>
*
* The order in which these lists are returned is not guaranteed, however the
* position of an element inside a tuple always corresponds to the position of
* the set from which it came in the input list. 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) {
for (Set<? extends B> set : sets) {
if (set.isEmpty()) {
return ImmutableSet.of();
}
}
CartesianSet<B> cartesianSet = new CartesianSet<B>(sets);
return cartesianSet;
}
/**
* 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>
*
* 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>
*
* The order in which these lists are returned is not guaranteed, however the
* position of an element inside a tuple always corresponds to the position of
* the set from which it came in the input list. Note that if any input set is
* empty, the Cartesian product will also be empty. If no sets at all are
* provided, 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 class CartesianSet<B> extends AbstractSet<List<B>> {
final ImmutableList<Axis> axes;
final int size;
CartesianSet(List<? extends Set<? extends B>> sets) {
int dividend = 1;
ImmutableList.Builder<Axis> builder = ImmutableList.builder();
try {
for (Set<? extends B> set : sets) {
Axis axis = new Axis(set, dividend);
builder.add(axis);
dividend = IntMath.checkedMultiply(dividend, axis.size());
}
} catch (ArithmeticException overflow) {
throw new IllegalArgumentException("cartesian product too big");
}
this.axes = builder.build();
size = dividend;
}
@Override public int size() {
return size;
}
@Override public UnmodifiableIterator<List<B>> iterator() {
return new AbstractIndexedListIterator<List<B>>(size) {
@Override
protected List<B> get(int index) {
Object[] tuple = new Object[axes.size()];
for (int i = 0 ; i < tuple.length; i++) {
tuple[i] = axes.get(i).getForIndex(index);
}
@SuppressWarnings("unchecked") // only B's are put in here
List<B> result = (ImmutableList<B>) ImmutableList.copyOf(tuple);
return result;
}
};
}
@Override public boolean contains(Object element) {
if (!(element instanceof List)) {
return false;
}
List<?> tuple = (List<?>) element;
int dimensions = axes.size();
if (tuple.size() != dimensions) {
return false;
}
for (int i = 0; i < dimensions; i++) {
if (!axes.get(i).contains(tuple.get(i))) {
return false;
}
}
return true;
}
@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;
}
return axes.hashCode() + adjust;
}
private class Axis {
final ImmutableSet<? extends B> choices;
final ImmutableList<? extends B> choicesList;
final int dividend;
Axis(Set<? extends B> set, int dividend) {
choices = ImmutableSet.copyOf(set);
choicesList = choices.asList();
this.dividend = dividend;
}
int size() {
return choices.size();
}
B getForIndex(int index) {
return choicesList.get(index / dividend % size());
}
boolean contains(Object target) {
return choices.contains(target);
}
@Override public boolean equals(Object obj) {
if (obj instanceof CartesianSet.Axis) {
CartesianSet.Axis that = (CartesianSet.Axis) obj;
return this.choices.equals(that.choices);
// dividends must be equal or we wouldn't have gotten this far
}
return false;
}
@Override public int hashCode() {
// Because Axis instances are not exposed, we can
// opportunistically choose whatever bizarre formula happens
// to make CartesianSet.hashCode() as simple as possible.
return size / choices.size() * choices.hashCode();
}
}
}
/**
* 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 few bytes of memory regardless of their size.
*
* @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) {
ImmutableSet<E> input = ImmutableSet.copyOf(set);
checkArgument(input.size() <= 30,
"Too many elements to create power set: %s > 30", input.size());
return new PowerSet<E>(input);
}
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableSet<E> inputSet;
final ImmutableList<E> inputList;
final int powerSetSize;
PowerSet(ImmutableSet<E> input) {
this.inputSet = input;
this.inputList = input.asList();
this.powerSetSize = 1 << input.size();
}
@Override public int size() {
return powerSetSize;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Iterator<Set<E>> iterator() {
return new AbstractIndexedListIterator<Set<E>>(powerSetSize) {
@Override protected Set<E> get(final int setBits) {
return new AbstractSet<E>() {
@Override public int size() {
return Integer.bitCount(setBits);
}
@Override public Iterator<E> iterator() {
return new BitFilteredSetIterator<E>(inputList, setBits);
}
};
}
};
}
private static final class BitFilteredSetIterator<E>
extends UnmodifiableIterator<E> {
final ImmutableList<E> input;
int remainingSetBits;
BitFilteredSetIterator(ImmutableList<E> input, int allSetBits) {
this.input = input;
this.remainingSetBits = allSetBits;
}
@Override public boolean hasNext() {
return remainingSetBits != 0;
}
@Override public E next() {
int index = Integer.numberOfTrailingZeros(remainingSetBits);
if (index == 32) {
throw new NoSuchElementException();
}
int currentElementMask = 1 << index;
remainingSetBits &= ~currentElementMask;
return input.get(index);
}
}
@Override public boolean contains(@Nullable Object obj) {
if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
return inputSet.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.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;
}
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>
*
* 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>
*
* 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
*/
@Beta
@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()) {
Iterator<?> setIterator = set.iterator();
boolean changed = false;
while (setIterator.hasNext()) {
if (collection.contains(setIterator.next())) {
changed = true;
setIterator.remove();
}
}
return changed;
} 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();
}
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> SortedSet<T> cast(Iterable<T> iterable) {
return (SortedSet<T>) iterable;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.collect.ObjectArrays.checkElementNotNull;
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.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* A high-performance, immutable, random-access {@code List} implementation.
* Does not permit null elements.
*
* <p>Unlike {@link Collections#unmodifiableList}, which is a <i>view</i> of a
* separate collection that can still change, an instance of {@code
* ImmutableList} contains its own private data and will <i>never</i> change.
* {@code ImmutableList} is convenient for {@code public static final} lists
* ("constant lists") and also lets you easily make a "defensive copy" of a list
* provided to your class by a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this type are
* guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @see ImmutableMap
* @see ImmutableSet
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableList<E> extends ImmutableCollection<E>
implements List<E>, RandomAccess {
/**
* Returns the empty immutable list. This set behaves and performs comparably
* to {@link Collections#emptyList}, and is preferable mainly for consistency
* and maintainability of your code.
*/
// Casting to any type is safe because the list will never hold any elements.
@SuppressWarnings("unchecked")
public static <E> ImmutableList<E> of() {
return (ImmutableList<E>) EmptyImmutableList.INSTANCE;
}
/**
* Returns an immutable list containing a single element. This list behaves
* and performs comparably to {@link Collections#singleton}, but will not
* accept a null element. It is preferable mainly for consistency and
* maintainability of your code.
*
* @throws NullPointerException if {@code element} is null
*/
public static <E> ImmutableList<E> of(E element) {
return new SingletonImmutableList<E>(element);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2) {
return construct(e1, e2);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
return construct(e1, e2, e3);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
return construct(e1, e2, e3, e4);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
return construct(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
return construct(e1, e2, e3, e4, e5, e6);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
return construct(e1, e2, e3, e4, e5, e6, e7);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
}
// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12,
E... others) {
Object[] array = new Object[12 + others.length];
array[0] = e1;
array[1] = e2;
array[2] = e3;
array[3] = e4;
array[4] = e5;
array[5] = e6;
array[6] = e7;
array[7] = e8;
array[8] = e9;
array[9] = e10;
array[10] = e11;
array[11] = e12;
System.arraycopy(others, 0, array, 12, others.length);
return construct(array);
}
/**
* Returns an immutable list containing the given elements, in order. If
* {@code elements} is a {@link Collection}, this method behaves exactly as
* {@link #copyOf(Collection)}; otherwise, it behaves exactly as {@code
* copyOf(elements.iterator()}.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
return (elements instanceof Collection)
? copyOf(Collections2.cast(elements))
: copyOf(elements.iterator());
}
/**
* Returns an immutable list containing the given elements, in order.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* <p>Note that if {@code list} is a {@code List<String>}, then {@code
* ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>}
* containing each of the strings in {@code list}, while
* ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>}
* containing one element (the given list itself).
*
* <p>This method is safe to use even when {@code elements} is a synchronized
* or concurrent collection that is currently being modified by another
* thread.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
if (elements instanceof ImmutableCollection) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
return list.isPartialView() ? copyFromCollection(list) : list;
}
return copyFromCollection(elements);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
// 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 construct(elements.clone());
}
}
/**
* Views the array as an immutable list. The array must have only non-null {@code E} elements.
*
* <p>The array must be internally created.
*/
static <E> ImmutableList<E> asImmutableList(Object[] elements) {
switch (elements.length) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") // collection had only Es in it
ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
return list;
default:
return construct(elements);
}
}
private static <E> ImmutableList<E> copyFromCollection(
Collection<? extends E> collection) {
return asImmutableList(collection.toArray());
}
/** {@code elements} has to be internally created array. */
private static <E> ImmutableList<E> construct(Object... elements) {
for (int i = 0; i < elements.length; i++) {
ObjectArrays.checkElementNotNull(elements[i], i);
}
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 ImmutableList<E> asList() {
return this;
}
/**
* Returns a view of this immutable list in reverse order. For example, {@code
* ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code
* ImmutableList.of(3, 2, 1)}.
*
* @return a view of this immutable list in reverse order
* @since 7.0
*/
public ImmutableList<E> reverse() {
return new ReverseImmutableList<E>(this);
}
private static class ReverseImmutableList<E> extends ImmutableList<E> {
private final transient ImmutableList<E> forwardList;
private final transient int size;
ReverseImmutableList(ImmutableList<E> backingList) {
this.forwardList = backingList;
this.size = backingList.size();
}
private int reverseIndex(int index) {
return (size - 1) - index;
}
private int reversePosition(int index) {
return size - index;
}
@Override public ImmutableList<E> reverse() {
return forwardList;
}
@Override public boolean contains(@Nullable Object object) {
return forwardList.contains(object);
}
@Override public boolean containsAll(Collection<?> targets) {
return forwardList.containsAll(targets);
}
@Override public int indexOf(@Nullable Object object) {
int index = forwardList.lastIndexOf(object);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public int lastIndexOf(@Nullable Object object) {
int index = forwardList.indexOf(object);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
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 UnmodifiableListIterator<E> listIterator(int index) {
checkPositionIndex(index, size);
final UnmodifiableListIterator<E> forward =
forwardList.listIterator(reversePosition(index));
return new UnmodifiableListIterator<E>() {
@Override public boolean hasNext() {
return forward.hasPrevious();
}
@Override public boolean hasPrevious() {
return forward.hasNext();
}
@Override public E next() {
return forward.previous();
}
@Override public int nextIndex() {
return reverseIndex(forward.previousIndex());
}
@Override public E previous() {
return forward.next();
}
@Override public int previousIndex() {
return reverseIndex(forward.nextIndex());
}
};
}
@Override public int size() {
return size;
}
@Override public boolean isEmpty() {
return forwardList.isEmpty();
}
@Override boolean isPartialView() {
return forwardList.isPartialView();
}
}
@Override public boolean equals(Object obj) {
return Lists.equalsImpl(this, obj);
}
@Override public int hashCode() {
return Lists.hashCodeImpl(this);
}
/*
* Serializes ImmutableLists as their logical contents. This ensures that
* implementation types do not leak into the serialized representation.
*/
private static class SerializedForm implements Serializable {
final Object[] elements;
SerializedForm(Object[] elements) {
this.elements = elements;
}
Object readResolve() {
return copyOf(elements);
}
private static final long serialVersionUID = 0;
}
private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override Object writeReplace() {
return new SerializedForm(toArray());
}
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<E>();
}
/**
* A builder for creating immutable list instances, especially {@code public
* static final} lists ("constant lists"). Example: <pre> {@code
*
* public static final ImmutableList<Color> GOOGLE_COLORS
* = new ImmutableList.Builder<Color>()
* .addAll(WEBSAFE_COLORS)
* .add(new Color(0, 191, 255))
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple lists in series. Each new list contains all the
* elements of the ones created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<E> extends ImmutableCollection.Builder<E> {
private Object[] contents;
private int size;
/**
* 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) {
this.contents = new Object[capacity];
this.size = 0;
}
/**
* Expand capacity to allow the specified number of elements to be added.
*/
Builder<E> expandFor(int count) {
int minCapacity = size + count;
if (contents.length < minCapacity) {
this.contents = ObjectArrays.arraysCopyOf(
this.contents, expandedCapacity(contents.length, minCapacity));
}
return this;
}
/**
* 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) {
checkNotNull(element);
expandFor(1);
contents[size++] = element;
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableList}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableList}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
Collection<?> collection = (Collection<?>) elements;
expandFor(collection.size());
}
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableList}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableList}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> add(E... elements) {
for (int i = 0; i < elements.length; i++) {
checkElementNotNull(elements[i], i);
}
expandFor(elements.length);
System.arraycopy(elements, 0, contents, size, elements.length);
size += elements.length;
return this;
}
/**
* Adds each element of {@code elements} to the {@code 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() {
switch (size) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") // guaranteed to be an E
E singleElement = (E) contents[0];
return of(singleElement);
default:
if (size == contents.length) {
// no need to copy; any further add operations on the builder will copy the buffer
return new RegularImmutableList<E>(contents);
} else {
return new RegularImmutableList<E>(ObjectArrays.arraysCopyOf(contents, size));
}
}
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
/**
* Wraps an exception that occurred during a computation in a different thread.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
* @deprecated this class is unused by com.google.common.collect. <b>This class
* is scheduled for deletion in November 2012.</b>
*/
@Deprecated
public
class AsynchronousComputationException extends ComputationException {
/**
* Creates a new instance with the given cause.
*/
public AsynchronousComputationException(Throwable cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Factory and utilities pertaining to the {@code MapConstraint} interface.
*
* @see Constraints
* @author Mike Bostock
* @since 3.0
*/
@Beta
@GwtCompatible
public final class MapConstraints {
private MapConstraints() {}
/**
* Returns a constraint that verifies that neither the key nor the value is
* null. If either is null, a {@link NullPointerException} is thrown.
*/
public static MapConstraint<Object, Object> notNull() {
return NotNullMapConstraint.INSTANCE;
}
// enum singleton pattern
private enum NotNullMapConstraint implements MapConstraint<Object, Object> {
INSTANCE;
@Override
public void checkKeyValue(Object key, Object value) {
checkNotNull(key);
checkNotNull(value);
}
@Override public String toString() {
return "Not null";
}
}
/**
* Returns a constrained view of the specified map, using the specified
* constraint. Any operations that add new mappings will call the provided
* constraint. However, this method does not verify that existing mappings
* satisfy the constraint.
*
* <p>The returned map is not serializable.
*
* @param map the map to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified map
*/
public static <K, V> Map<K, V> constrainedMap(
Map<K, V> map, MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedMap<K, V>(map, constraint);
}
/**
* Returns a constrained view of the specified multimap, using the specified
* constraint. Any operations that add new mappings will call the provided
* constraint. However, this method does not verify that existing mappings
* satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
*
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the multimap
*/
public static <K, V> Multimap<K, V> constrainedMultimap(
Multimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified list multimap, using the
* specified constraint. Any operations that add new mappings will call the
* provided constraint. However, this method does not verify that existing
* mappings satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
*
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> constrainedListMultimap(
ListMultimap<K, V> multimap,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedListMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified set multimap, using the
* specified constraint. Any operations that add new mappings will call the
* provided constraint. However, this method does not verify that existing
* mappings satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> constrainedSetMultimap(
SetMultimap<K, V> multimap,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedSetMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified sorted-set multimap, using the
* specified constraint. Any operations that add new mappings will call the
* provided constraint. However, this method does not verify that existing
* mappings satisfy the constraint.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are not
* constrained.
* <p>The returned multimap is not serializable.
*
* @param multimap the multimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V> constrainedSortedSetMultimap(
SortedSetMultimap<K, V> multimap,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedSortedSetMultimap<K, V>(multimap, constraint);
}
/**
* Returns a constrained view of the specified entry, using the specified
* constraint. The {@link Entry#setValue} operation will be verified with the
* constraint.
*
* @param entry the entry to constrain
* @param constraint the constraint for the entry
* @return a constrained view of the specified entry
*/
private static <K, V> Entry<K, V> constrainedEntry(
final Entry<K, V> entry,
final MapConstraint<? super K, ? super V> constraint) {
checkNotNull(entry);
checkNotNull(constraint);
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return entry;
}
@Override public V setValue(V value) {
constraint.checkKeyValue(getKey(), value);
return entry.setValue(value);
}
};
}
/**
* Returns a constrained view of the specified {@code asMap} entry, using the
* specified constraint. The {@link Entry#setValue} operation will be verified
* with the constraint, and the collection returned by {@link Entry#getValue}
* will be similarly constrained.
*
* @param entry the {@code asMap} entry to constrain
* @param constraint the constraint for the entry
* @return a constrained view of the specified entry
*/
private static <K, V> Entry<K, Collection<V>> constrainedAsMapEntry(
final Entry<K, Collection<V>> entry,
final MapConstraint<? super K, ? super V> constraint) {
checkNotNull(entry);
checkNotNull(constraint);
return new ForwardingMapEntry<K, Collection<V>>() {
@Override protected Entry<K, Collection<V>> delegate() {
return entry;
}
@Override public Collection<V> getValue() {
return Constraints.constrainedTypePreservingCollection(
entry.getValue(), new Constraint<V>() {
@Override
public V checkElement(V value) {
constraint.checkKeyValue(getKey(), value);
return value;
}
});
}
};
}
/**
* Returns a constrained view of the specified set of {@code asMap} entries,
* using the specified constraint. The {@link Entry#setValue} operation will
* be verified with the constraint, and the collection returned by {@link
* Entry#getValue} will be similarly constrained. The {@code add} and {@code
* addAll} operations simply forward to the underlying set, which throws an
* {@link UnsupportedOperationException} per the multimap specification.
*
* @param entries the entries to constrain
* @param constraint the constraint for the entries
* @return a constrained view of the entries
*/
private static <K, V> Set<Entry<K, Collection<V>>> constrainedAsMapEntries(
Set<Entry<K, Collection<V>>> entries,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedAsMapEntries<K, V>(entries, constraint);
}
/**
* Returns a constrained view of the specified collection (or set) of entries,
* using the specified constraint. The {@link Entry#setValue} operation will
* be verified with the constraint, along with add operations on the returned
* collection. The {@code add} and {@code addAll} operations simply forward to
* the underlying collection, which throws an {@link
* UnsupportedOperationException} per the map and multimap specification.
*
* @param entries the entries to constrain
* @param constraint the constraint for the entries
* @return a constrained view of the specified entries
*/
private static <K, V> Collection<Entry<K, V>> constrainedEntries(
Collection<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
if (entries instanceof Set) {
return constrainedEntrySet((Set<Entry<K, V>>) entries, constraint);
}
return new ConstrainedEntries<K, V>(entries, constraint);
}
/**
* Returns a constrained view of the specified set of entries, using the
* specified constraint. The {@link Entry#setValue} operation will be verified
* with the constraint, along with add operations on the returned set. The
* {@code add} and {@code addAll} operations simply forward to the underlying
* set, which throws an {@link UnsupportedOperationException} per the map and
* multimap specification.
*
* <p>The returned multimap is not serializable.
*
* @param entries the entries to constrain
* @param constraint the constraint for the entries
* @return a constrained view of the specified entries
*/
private static <K, V> Set<Entry<K, V>> constrainedEntrySet(
Set<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedEntrySet<K, V>(entries, constraint);
}
/** @see MapConstraints#constrainedMap */
static class ConstrainedMap<K, V> extends ForwardingMap<K, V> {
private final Map<K, V> delegate;
final MapConstraint<? super K, ? super V> constraint;
private transient Set<Entry<K, V>> entrySet;
ConstrainedMap(
Map<K, V> delegate, MapConstraint<? super K, ? super V> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Map<K, V> delegate() {
return delegate;
}
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
if (result == null) {
entrySet = result =
constrainedEntrySet(delegate.entrySet(), constraint);
}
return result;
}
@Override public V put(K key, V value) {
constraint.checkKeyValue(key, value);
return delegate.put(key, value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
delegate.putAll(checkMap(map, constraint));
}
}
/**
* Returns a constrained view of the specified bimap, using the specified
* constraint. Any operations that modify the bimap will have the associated
* keys and values verified with the constraint.
*
* <p>The returned bimap is not serializable.
*
* @param map the bimap to constrain
* @param constraint the constraint that validates added entries
* @return a constrained view of the specified bimap
*/
public static <K, V> BiMap<K, V> constrainedBiMap(
BiMap<K, V> map, MapConstraint<? super K, ? super V> constraint) {
return new ConstrainedBiMap<K, V>(map, null, constraint);
}
/** @see MapConstraints#constrainedBiMap */
private static class ConstrainedBiMap<K, V> extends ConstrainedMap<K, V>
implements BiMap<K, V> {
/*
* We could switch to racy single-check lazy init and remove volatile, but
* there's a downside. That's because this field is also written in the
* constructor. Without volatile, the constructor's write of the existing
* inverse BiMap could occur after inverse()'s read of the field's initial
* null value, leading inverse() to overwrite the existing inverse with a
* doubly indirect version. This wouldn't be catastrophic, but it's
* something to keep in mind if we make the change.
*
* Note that UnmodifiableBiMap *does* use racy single-check lazy init.
* TODO(cpovirk): pick one and standardize
*/
volatile BiMap<V, K> inverse;
ConstrainedBiMap(BiMap<K, V> delegate, @Nullable BiMap<V, K> inverse,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
this.inverse = inverse;
}
@Override protected BiMap<K, V> delegate() {
return (BiMap<K, V>) super.delegate();
}
@Override
public V forcePut(K key, V value) {
constraint.checkKeyValue(key, value);
return delegate().forcePut(key, value);
}
@Override
public BiMap<V, K> inverse() {
if (inverse == null) {
inverse = new ConstrainedBiMap<V, K>(delegate().inverse(), this,
new InverseConstraint<V, K>(constraint));
}
return inverse;
}
@Override public Set<V> values() {
return delegate().values();
}
}
/** @see MapConstraints#constrainedBiMap */
private static class InverseConstraint<K, V> implements MapConstraint<K, V> {
final MapConstraint<? super V, ? super K> constraint;
public InverseConstraint(MapConstraint<? super V, ? super K> constraint) {
this.constraint = checkNotNull(constraint);
}
@Override
public void checkKeyValue(K key, V value) {
constraint.checkKeyValue(value, key);
}
}
/** @see MapConstraints#constrainedMultimap */
private static class ConstrainedMultimap<K, V>
extends ForwardingMultimap<K, V> {
final MapConstraint<? super K, ? super V> constraint;
final Multimap<K, V> delegate;
transient Collection<Entry<K, V>> entries;
transient Map<K, Collection<V>> asMap;
public ConstrainedMultimap(Multimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Multimap<K, V> delegate() {
return delegate;
}
@Override public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
if (result == null) {
final Map<K, Collection<V>> asMapDelegate = delegate.asMap();
asMap = result = new ForwardingMap<K, Collection<V>>() {
Set<Entry<K, Collection<V>>> entrySet;
Collection<Collection<V>> values;
@Override protected Map<K, Collection<V>> delegate() {
return asMapDelegate;
}
@Override public Set<Entry<K, Collection<V>>> entrySet() {
Set<Entry<K, Collection<V>>> result = entrySet;
if (result == null) {
entrySet = result = constrainedAsMapEntries(
asMapDelegate.entrySet(), constraint);
}
return result;
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
try {
Collection<V> collection = ConstrainedMultimap.this.get((K) key);
return collection.isEmpty() ? null : collection;
} catch (ClassCastException e) {
return null; // key wasn't a K
}
}
@Override public Collection<Collection<V>> values() {
Collection<Collection<V>> result = values;
if (result == null) {
values = result = new ConstrainedAsMapValues<K, V>(
delegate().values(), entrySet());
}
return result;
}
@Override public boolean containsValue(Object o) {
return values().contains(o);
}
};
}
return result;
}
@Override public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
if (result == null) {
entries = result = constrainedEntries(delegate.entries(), constraint);
}
return result;
}
@Override public Collection<V> get(final K key) {
return Constraints.constrainedTypePreservingCollection(
delegate.get(key), new Constraint<V>() {
@Override
public V checkElement(V value) {
constraint.checkKeyValue(key, value);
return value;
}
});
}
@Override public boolean put(K key, V value) {
constraint.checkKeyValue(key, value);
return delegate.put(key, value);
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
return delegate.putAll(key, checkValues(key, values, constraint));
}
@Override public boolean putAll(
Multimap<? extends K, ? extends V> multimap) {
boolean changed = false;
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
changed |= put(entry.getKey(), entry.getValue());
}
return changed;
}
@Override public Collection<V> replaceValues(
K key, Iterable<? extends V> values) {
return delegate.replaceValues(key, checkValues(key, values, constraint));
}
}
/** @see ConstrainedMultimap#asMap */
private static class ConstrainedAsMapValues<K, V>
extends ForwardingCollection<Collection<V>> {
final Collection<Collection<V>> delegate;
final Set<Entry<K, Collection<V>>> entrySet;
/**
* @param entrySet map entries, linking each key with its corresponding
* values, that already enforce the constraint
*/
ConstrainedAsMapValues(Collection<Collection<V>> delegate,
Set<Entry<K, Collection<V>>> entrySet) {
this.delegate = delegate;
this.entrySet = entrySet;
}
@Override protected Collection<Collection<V>> delegate() {
return delegate;
}
@Override public Iterator<Collection<V>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = entrySet.iterator();
return new Iterator<Collection<V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Collection<V> next() {
return iterator.next().getValue();
}
@Override
public void remove() {
iterator.remove();
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return standardContains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean remove(Object o) {
return standardRemove(o);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** @see MapConstraints#constrainedEntries */
private static class ConstrainedEntries<K, V>
extends ForwardingCollection<Entry<K, V>> {
final MapConstraint<? super K, ? super V> constraint;
final Collection<Entry<K, V>> entries;
ConstrainedEntries(Collection<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
this.entries = entries;
this.constraint = constraint;
}
@Override protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = entries.iterator();
return new ForwardingIterator<Entry<K, V>>() {
@Override public Entry<K, V> next() {
return constrainedEntry(iterator.next(), constraint);
}
@Override protected Iterator<Entry<K, V>> delegate() {
return iterator;
}
};
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean remove(Object o) {
return Maps.removeEntryImpl(delegate(), o);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** @see MapConstraints#constrainedEntrySet */
static class ConstrainedEntrySet<K, V>
extends ConstrainedEntries<K, V> implements Set<Entry<K, V>> {
ConstrainedEntrySet(Set<Entry<K, V>> entries,
MapConstraint<? super K, ? super V> constraint) {
super(entries, constraint);
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/** @see MapConstraints#constrainedAsMapEntries */
static class ConstrainedAsMapEntries<K, V>
extends ForwardingSet<Entry<K, Collection<V>>> {
private final MapConstraint<? super K, ? super V> constraint;
private final Set<Entry<K, Collection<V>>> entries;
ConstrainedAsMapEntries(Set<Entry<K, Collection<V>>> entries,
MapConstraint<? super K, ? super V> constraint) {
this.entries = entries;
this.constraint = constraint;
}
@Override protected Set<Entry<K, Collection<V>>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = entries.iterator();
return new ForwardingIterator<Entry<K, Collection<V>>>() {
@Override public Entry<K, Collection<V>> next() {
return constrainedAsMapEntry(iterator.next(), constraint);
}
@Override protected Iterator<Entry<K, Collection<V>>> delegate() {
return iterator;
}
};
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@Override public int hashCode() {
return standardHashCode();
}
@Override public boolean remove(Object o) {
return Maps.removeEntryImpl(delegate(), o);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
private static class ConstrainedListMultimap<K, V>
extends ConstrainedMultimap<K, V> implements ListMultimap<K, V> {
ConstrainedListMultimap(ListMultimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
}
@Override public List<V> get(K key) {
return (List<V>) super.get(key);
}
@Override public List<V> removeAll(Object key) {
return (List<V>) super.removeAll(key);
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
return (List<V>) super.replaceValues(key, values);
}
}
private static class ConstrainedSetMultimap<K, V>
extends ConstrainedMultimap<K, V> implements SetMultimap<K, V> {
ConstrainedSetMultimap(SetMultimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
}
@Override public Set<V> get(K key) {
return (Set<V>) super.get(key);
}
@Override public Set<Map.Entry<K, V>> entries() {
return (Set<Map.Entry<K, V>>) super.entries();
}
@Override public Set<V> removeAll(Object key) {
return (Set<V>) super.removeAll(key);
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
return (Set<V>) super.replaceValues(key, values);
}
}
private static class ConstrainedSortedSetMultimap<K, V>
extends ConstrainedSetMultimap<K, V> implements SortedSetMultimap<K, V> {
ConstrainedSortedSetMultimap(SortedSetMultimap<K, V> delegate,
MapConstraint<? super K, ? super V> constraint) {
super(delegate, constraint);
}
@Override public SortedSet<V> get(K key) {
return (SortedSet<V>) super.get(key);
}
@Override public SortedSet<V> removeAll(Object key) {
return (SortedSet<V>) super.removeAll(key);
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
return (SortedSet<V>) super.replaceValues(key, values);
}
@Override
public Comparator<? super V> valueComparator() {
return ((SortedSetMultimap<K, V>) delegate()).valueComparator();
}
}
private static <K, V> Collection<V> checkValues(K key,
Iterable<? extends V> values,
MapConstraint<? super K, ? super V> constraint) {
Collection<V> copy = Lists.newArrayList(values);
for (V value : copy) {
constraint.checkKeyValue(key, value);
}
return copy;
}
private static <K, V> Map<K, V> checkMap(Map<? extends K, ? extends V> map,
MapConstraint<? super K, ? super V> constraint) {
Map<K, V> copy = new LinkedHashMap<K, V>(map);
for (Entry<K, V> entry : copy.entrySet()) {
constraint.checkKeyValue(entry.getKey(), entry.getValue());
}
return copy;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
/**
* "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>
*
* 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
*/
@GwtCompatible
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.
*/
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
/**
* Bimap with one or more mappings.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
final transient ImmutableMap<K, V> delegate;
final transient ImmutableBiMap<V, K> inverse;
RegularImmutableBiMap(ImmutableMap<K, V> delegate) {
this.delegate = delegate;
ImmutableMap.Builder<V, K> builder = ImmutableMap.builder();
for (Entry<K, V> entry : delegate.entrySet()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableMap<V, K> backwardMap = builder.build();
this.inverse = new RegularImmutableBiMap<V, K>(backwardMap, this);
}
RegularImmutableBiMap(ImmutableMap<K, V> delegate,
ImmutableBiMap<V, K> inverse) {
this.delegate = delegate;
this.inverse = inverse;
}
@Override ImmutableMap<K, V> delegate() {
return delegate;
}
@Override public ImmutableBiMap<V, K> inverse() {
return inverse;
}
@Override boolean isPartialView() {
return delegate.isPartialView() || inverse.delegate().isPartialView();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import 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;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
/**
* A {@link Multiset} which maintains the ordering of its elements, according to
* either their natural order or an explicit {@link Comparator}. In all cases,
* this implementation uses {@link Comparable#compareTo} or
* {@link Comparator#compare} instead of {@link Object#equals} to determine
* equivalence of instances.
*
* <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as
* explained by the {@link Comparable} class specification. Otherwise, the
* resulting multiset will violate the {@link 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
public interface SortedMultiset<E> extends Multiset<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 SortedSet} view of the distinct elements in this multiset.
*/
@Override SortedSet<E> elementSet();
/**
* {@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);
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Iterator;
/** An ordering that uses the reverse of the natural order of the values. */
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this??
final class ReverseNaturalOrdering
extends Ordering<Comparable> implements Serializable {
static final ReverseNaturalOrdering INSTANCE = new ReverseNaturalOrdering();
@Override public int compare(Comparable left, Comparable right) {
checkNotNull(left); // right null is caught later
if (left == right) {
return 0;
}
return right.compareTo(left);
}
@Override public <S extends Comparable> Ordering<S> reverse() {
return Ordering.natural();
}
// Override the min/max methods to "hoist" delegation outside loops
@Override public <E extends Comparable> E min(E a, E b) {
return NaturalOrdering.INSTANCE.max(a, b);
}
@Override public <E extends Comparable> E min(E a, E b, E c, E... rest) {
return NaturalOrdering.INSTANCE.max(a, b, c, rest);
}
@Override public <E extends Comparable> E min(Iterator<E> iterator) {
return NaturalOrdering.INSTANCE.max(iterator);
}
@Override public <E extends Comparable> E min(Iterable<E> iterable) {
return NaturalOrdering.INSTANCE.max(iterable);
}
@Override public <E extends Comparable> E max(E a, E b) {
return NaturalOrdering.INSTANCE.min(a, b);
}
@Override public <E extends Comparable> E max(E a, E b, E c, E... rest) {
return NaturalOrdering.INSTANCE.min(a, b, c, rest);
}
@Override public <E extends Comparable> E max(Iterator<E> iterator) {
return NaturalOrdering.INSTANCE.min(iterator);
}
@Override public <E extends Comparable> E max(Iterable<E> iterable) {
return NaturalOrdering.INSTANCE.min(iterable);
}
// preserving singleton-ness gives equals()/hashCode() for free
private Object readResolve() {
return INSTANCE;
}
@Override public String toString() {
return "Ordering.natural().reverse()";
}
private ReverseNaturalOrdering() {}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedSet;
/**
* Factories and utilities pertaining to the {@link Constraint} interface.
*
* @see MapConstraints
* @author Mike Bostock
* @author Jared Levy
* @since 3.0
*/
@Beta
@GwtCompatible
public final class Constraints {
private Constraints() {}
// enum singleton pattern
private enum NotNullConstraint implements Constraint<Object> {
INSTANCE;
@Override
public Object checkElement(Object element) {
return checkNotNull(element);
}
@Override public String toString() {
return "Not null";
}
}
/**
* Returns a constraint that verifies that the element is not null. If the
* element is null, a {@link NullPointerException} is thrown.
*/
// safe to narrow the type since checkElement returns its argument directly
@SuppressWarnings("unchecked")
public static <E> Constraint<E> notNull() {
return (Constraint<E>) NotNullConstraint.INSTANCE;
}
/**
* Returns a constrained view of the specified collection, using the specified
* constraint. Any operations that add new elements to the collection will
* call the provided constraint. However, this method does not verify that
* existing elements satisfy the constraint.
*
* <p>The returned collection is not serializable.
*
* @param collection the collection to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the collection
*/
public static <E> Collection<E> constrainedCollection(
Collection<E> collection, Constraint<? super E> constraint) {
return new ConstrainedCollection<E>(collection, constraint);
}
/** @see Constraints#constrainedCollection */
static class ConstrainedCollection<E> extends ForwardingCollection<E> {
private final Collection<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedCollection(
Collection<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Collection<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
}
/**
* Returns a constrained view of the specified set, using the specified
* constraint. Any operations that add new elements to the set will call the
* provided constraint. However, this method does not verify that existing
* elements satisfy the constraint.
*
* <p>The returned set is not serializable.
*
* @param set the set to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the set
*/
public static <E> Set<E> constrainedSet(
Set<E> set, Constraint<? super E> constraint) {
return new ConstrainedSet<E>(set, constraint);
}
/** @see Constraints#constrainedSet */
static class ConstrainedSet<E> extends ForwardingSet<E> {
private final Set<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedSet(Set<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Set<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
}
/**
* Returns a constrained view of the specified sorted set, using the specified
* constraint. Any operations that add new elements to the sorted set will
* call the provided constraint. However, this method does not verify that
* existing elements satisfy the constraint.
*
* <p>The returned set is not serializable.
*
* @param sortedSet the sorted set to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the sorted set
*/
public static <E> SortedSet<E> constrainedSortedSet(
SortedSet<E> sortedSet, Constraint<? super E> constraint) {
return new ConstrainedSortedSet<E>(sortedSet, constraint);
}
/** @see Constraints#constrainedSortedSet */
private static class ConstrainedSortedSet<E> extends ForwardingSortedSet<E> {
final SortedSet<E> delegate;
final Constraint<? super E> constraint;
ConstrainedSortedSet(
SortedSet<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected SortedSet<E> delegate() {
return delegate;
}
@Override public SortedSet<E> headSet(E toElement) {
return constrainedSortedSet(delegate.headSet(toElement), constraint);
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return constrainedSortedSet(
delegate.subSet(fromElement, toElement), constraint);
}
@Override public SortedSet<E> tailSet(E fromElement) {
return constrainedSortedSet(delegate.tailSet(fromElement), constraint);
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
}
/**
* Returns a constrained view of the specified list, using the specified
* constraint. Any operations that add new elements to the list will call the
* provided constraint. However, this method does not verify that existing
* elements satisfy the constraint.
*
* <p>If {@code list} implements {@link RandomAccess}, so will the returned
* list. The returned list is not serializable.
*
* @param list the list to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the list
*/
public static <E> List<E> constrainedList(
List<E> list, Constraint<? super E> constraint) {
return (list instanceof RandomAccess)
? new ConstrainedRandomAccessList<E>(list, constraint)
: new ConstrainedList<E>(list, constraint);
}
/** @see Constraints#constrainedList */
@GwtCompatible
private static class ConstrainedList<E> extends ForwardingList<E> {
final List<E> delegate;
final Constraint<? super E> constraint;
ConstrainedList(List<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected List<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
constraint.checkElement(element);
return delegate.add(element);
}
@Override public void add(int index, E element) {
constraint.checkElement(element);
delegate.add(index, element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
@Override public boolean addAll(int index, Collection<? extends E> elements)
{
return delegate.addAll(index, checkElements(elements, constraint));
}
@Override public ListIterator<E> listIterator() {
return constrainedListIterator(delegate.listIterator(), constraint);
}
@Override public ListIterator<E> listIterator(int index) {
return constrainedListIterator(delegate.listIterator(index), constraint);
}
@Override public E set(int index, E element) {
constraint.checkElement(element);
return delegate.set(index, element);
}
@Override public List<E> subList(int fromIndex, int toIndex) {
return constrainedList(
delegate.subList(fromIndex, toIndex), constraint);
}
}
/** @see Constraints#constrainedList */
static class ConstrainedRandomAccessList<E> extends ConstrainedList<E>
implements RandomAccess {
ConstrainedRandomAccessList(
List<E> delegate, Constraint<? super E> constraint) {
super(delegate, constraint);
}
}
/**
* Returns a constrained view of the specified list iterator, using the
* specified constraint. Any operations that would add new elements to the
* underlying list will be verified by the constraint.
*
* @param listIterator the iterator for which to return a constrained view
* @param constraint the constraint for elements in the list
* @return a constrained view of the specified iterator
*/
private static <E> ListIterator<E> constrainedListIterator(
ListIterator<E> listIterator, Constraint<? super E> constraint) {
return new ConstrainedListIterator<E>(listIterator, constraint);
}
/** @see Constraints#constrainedListIterator */
static class ConstrainedListIterator<E> extends ForwardingListIterator<E> {
private final ListIterator<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedListIterator(
ListIterator<E> delegate, Constraint<? super E> constraint) {
this.delegate = delegate;
this.constraint = constraint;
}
@Override protected ListIterator<E> delegate() {
return delegate;
}
@Override public void add(E element) {
constraint.checkElement(element);
delegate.add(element);
}
@Override public void set(E element) {
constraint.checkElement(element);
delegate.set(element);
}
}
static <E> Collection<E> constrainedTypePreservingCollection(
Collection<E> collection, Constraint<E> constraint) {
if (collection instanceof SortedSet) {
return constrainedSortedSet((SortedSet<E>) collection, constraint);
} else if (collection instanceof Set) {
return constrainedSet((Set<E>) collection, constraint);
} else if (collection instanceof List) {
return constrainedList((List<E>) collection, constraint);
} else {
return constrainedCollection(collection, constraint);
}
}
/**
* Returns a constrained view of the specified multiset, using the specified
* constraint. Any operations that add new elements to the multiset will call
* the provided constraint. However, this method does not verify that
* existing elements satisfy the constraint.
*
* <p>The returned multiset is not serializable.
*
* @param multiset the multiset to constrain
* @param constraint the constraint that validates added elements
* @return a constrained view of the multiset
*/
public static <E> Multiset<E> constrainedMultiset(
Multiset<E> multiset, Constraint<? super E> constraint) {
return new ConstrainedMultiset<E>(multiset, constraint);
}
/** @see Constraints#constrainedMultiset */
static class ConstrainedMultiset<E> extends ForwardingMultiset<E> {
private Multiset<E> delegate;
private final Constraint<? super E> constraint;
public ConstrainedMultiset(
Multiset<E> delegate, Constraint<? super E> constraint) {
this.delegate = checkNotNull(delegate);
this.constraint = checkNotNull(constraint);
}
@Override protected Multiset<E> delegate() {
return delegate;
}
@Override public boolean add(E element) {
return standardAdd(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
return delegate.addAll(checkElements(elements, constraint));
}
@Override public int add(E element, int occurrences) {
constraint.checkElement(element);
return delegate.add(element, occurrences);
}
@Override public int setCount(E element, int count) {
constraint.checkElement(element);
return delegate.setCount(element, count);
}
@Override public boolean setCount(E element, int oldCount, int newCount) {
constraint.checkElement(element);
return delegate.setCount(element, oldCount, newCount);
}
}
/*
* TODO(kevinb): For better performance, avoid making a copy of the elements
* by having addAll() call add() repeatedly instead.
*/
private static <E> Collection<E> checkElements(
Collection<E> elements, Constraint<? super E> constraint) {
Collection<E> copy = Lists.newArrayList(elements);
for (E element : copy) {
constraint.checkElement(element);
}
return copy;
}
}
| Java |
/*
* Copyright (C) 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 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.primitives.Ints;
import java.io.Serializable;
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) {
checkArgument(arraySize >= 0);
// 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) {
checkNotNull(elements); // for GWT
ArrayList<E> list = newArrayList();
while (elements.hasNext()) {
list.add(elements.next());
}
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) {
checkArgument(initialArraySize >= 0); // 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();
for (E element : elements) {
list.add(element);
}
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 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) {
final ListIterator<F> delegate = fromList.listIterator(index);
return new ListIterator<T>() {
@Override
public void add(T e) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public boolean hasPrevious() {
return delegate.hasPrevious();
}
@Override
public T next() {
return function.apply(delegate.next());
}
@Override
public int nextIndex() {
return delegate.nextIndex();
}
@Override
public T previous() {
return function.apply(delegate.previous());
}
@Override
public int previousIndex() {
return delegate.previousIndex();
}
@Override
public void remove() {
delegate.remove();
}
@Override
public void set(T e) {
throw new UnsupportedOperationException("not supported");
}
};
}
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 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) {
int listSize = size();
checkElementIndex(index, listSize);
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override public int size() {
// TODO(user): refactor to common.math.IntMath.divide
int result = list.size() / size;
if (result * size != list.size()) {
result++;
}
return result;
}
@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();
}
@Override public boolean equals(@Nullable Object obj) {
if (!(obj instanceof List)) {
return false;
}
List<?> list = (List<?>) obj;
int n = string.length();
if (n != list.size()) {
return false;
}
Iterator<?> iterator = list.iterator();
for (int i = 0; i < n; i++) {
Object elem = iterator.next();
if (!(elem instanceof Character)
|| ((Character) elem).charValue() != string.charAt(i)) {
return false;
}
}
return true;
}
int hash = 0;
@Override public int hashCode() {
int h = hash;
if (h == 0) {
h = 1;
for (int i = 0; i < string.length(); i++) {
h = h * 31 + string.charAt(i);
}
hash = h;
}
return h;
}
}
/**
* 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 boolean contains(@Nullable Object o) {
return indexOf(o) >= 0;
}
@Override public int indexOf(@Nullable Object o) {
if (o instanceof Character) {
char c = (Character) o;
for (int i = 0; i < sequence.length(); i++) {
if (sequence.charAt(i) == c) {
return i;
}
}
}
return -1;
}
@Override public int lastIndexOf(@Nullable Object o) {
if (o instanceof Character) {
char c = ((Character) o).charValue();
for (int i = sequence.length() - 1; i >= 0; i--) {
if (sequence.charAt(i) == c) {
return i;
}
}
}
return -1;
}
@Override public int size() {
return sequence.length();
}
@Override public List<Character> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(sequence.subSequence(fromIndex, toIndex));
}
@Override public int hashCode() {
int hash = 1;
for (int i = 0; i < sequence.length(); i++) {
hash = hash * 31 + sequence.charAt(i);
}
return hash;
}
@Override public boolean equals(@Nullable Object o) {
if (!(o instanceof List)) {
return false;
}
List<?> list = (List<?>) o;
int n = sequence.length();
if (n != list.size()) {
return false;
}
Iterator<?> iterator = list.iterator();
for (int i = 0; i < n; i++) {
Object elem = iterator.next();
if (!(elem instanceof Character)
|| ((Character) elem).charValue() != sequence.charAt(i)) {
return false;
}
}
return true;
}
}
/**
* 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 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 boolean isEmpty() {
return forwardList.isEmpty();
}
@Override public int size() {
return forwardList.size();
}
@Override public boolean contains(@Nullable Object o) {
return forwardList.contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return forwardList.containsAll(c);
}
@Override public List<T> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
return reverse(forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)));
}
@Override public int indexOf(@Nullable Object o) {
int index = forwardList.lastIndexOf(o);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public int lastIndexOf(@Nullable Object o) {
int index = forwardList.indexOf(o);
return (index >= 0) ? reverseIndex(index) : -1;
}
@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 canRemove;
boolean canSet;
@Override public void add(T e) {
forwardIterator.add(e);
forwardIterator.previous();
canSet = canRemove = false;
}
@Override public boolean hasNext() {
return forwardIterator.hasPrevious();
}
@Override public boolean hasPrevious() {
return forwardIterator.hasNext();
}
@Override public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
canSet = canRemove = true;
return forwardIterator.previous();
}
@Override public int nextIndex() {
return reversePosition(forwardIterator.nextIndex());
}
@Override public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
canSet = canRemove = true;
return forwardIterator.next();
}
@Override public int previousIndex() {
return nextIndex() - 1;
}
@Override public void remove() {
checkState(canRemove);
forwardIterator.remove();
canRemove = canSet = false;
}
@Override public void set(T e) {
checkState(canSet);
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){
int hashCode = 1;
for (Object o : list) {
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
}
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;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.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);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* An immutable {@link ListMultimap} with reliable user-specified key and value
* iteration order. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableListMultimap(ListMultimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableListMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableListMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableListMultimap<K, V>
extends ImmutableMultimap<K, V>
implements ListMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableListMultimap<K, V> of() {
return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
builder.put(k5, v5);
return builder.build();
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* A builder for creating immutable {@code ListMultimap} instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableListMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<K, V>
extends ImmutableMultimap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableListMultimap#builder}.
*/
public Builder() {}
@Override public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
/**
* {@inheritDoc}
*
* @since 11.0
*/
@Override public Builder<K, V> put(
Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
@Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
super.putAll(key, values);
return this;
}
@Override public Builder<K, V> putAll(K key, V... values) {
super.putAll(key, values);
return this;
}
@Override public Builder<K, V> putAll(
Multimap<? extends K, ? extends V> multimap) {
super.putAll(multimap);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Beta @Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
super.orderKeysBy(keyComparator);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Beta @Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/**
* Returns a newly-created immutable list multimap.
*/
@Override public ImmutableListMultimap<K, V> build() {
return (ImmutableListMultimap<K, V>) super.build();
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code
* multimap}. The generated multimap's key and value orderings correspond to
* the iteration ordering of the {@code multimap.asMap()} view.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableListMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap.isEmpty()) {
return of();
}
// TODO(user): copy ImmutableSetMultimap by using asList() on the sets
if (multimap instanceof ImmutableListMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableListMultimap<K, V> kvMultimap
= (ImmutableListMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder();
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
ImmutableList<V> list = ImmutableList.copyOf(entry.getValue());
if (!list.isEmpty()) {
builder.put(entry.getKey(), list);
size += list.size();
}
}
return new ImmutableListMultimap<K, V>(builder.build(), size);
}
ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
super(map, size);
}
// views
/**
* Returns an immutable list of the values for the given key. If no mappings
* in the multimap have the provided key, an empty immutable list is
* returned. The values are in the same order as the parameters used to build
* this multimap.
*/
@Override public ImmutableList<V> get(@Nullable K key) {
// This cast is safe as its type is known in constructor.
ImmutableList<V> list = (ImmutableList<V>) map.get(key);
return (list == null) ? ImmutableList.<V>of() : list;
}
private transient ImmutableListMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a list multimap can contain multiple pairs with
* the same key and value, this method returns an {@code
* ImmutableListMultimap} rather than the {@code ImmutableMultimap} specified
* in the {@code ImmutableMultimap} class.
*
* @since 11
*/
@Beta
@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;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and
* a {@code HashMap} instance for values-to-keys. Null keys are not permitted,
* but null values are. An {@code EnumHashBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumHashBiMap<K extends Enum<K>, V>
extends AbstractBiMap<K, V> {
private transient Class<K> keyType;
/**
* Returns a new, empty {@code EnumHashBiMap} using the specified key type.
*
* @param keyType the key type
*/
public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
create(Class<K> keyType) {
return new EnumHashBiMap<K, V>(keyType);
}
/**
* Constructs a new bimap with the same mappings as the specified map. If the
* specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new
* bimap has the same key type as the input bimap. Otherwise, the specified
* map must contain at least one mapping, in order to determine the key type.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an
* {@code EnumHashBiMap} instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
create(Map<K, ? extends V> map) {
EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
bimap.putAll(map);
return bimap;
}
private EnumHashBiMap(Class<K> keyType) {
super(WellBehavedMap.wrap(
new EnumMap<K, V>(keyType)),
Maps.<V, K>newHashMapWithExpectedSize(
keyType.getEnumConstants().length));
this.keyType = keyType;
}
// Overriding these 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;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* This class provides a skeletal implementation of the {@code Iterator}
* interface, to make this interface easier to implement for certain types of
* data sources.
*
* <p>{@code Iterator} requires its implementations to support querying the
* end-of-data status without changing the iterator's state, using the {@link
* #hasNext} method. But many data sources, such as {@link
* java.io.Reader#read()}, do not expose this information; the only way to
* discover whether there is any data left is by trying to retrieve it. These
* types of data sources are ordinarily difficult to write iterators for. But
* using this class, one must implement only the {@link #computeNext} method,
* and invoke the {@link #endOfData} method when appropriate.
*
* <p>Another example is an iterator that skips over null elements in a backing
* iterator. This could be implemented as: <pre> {@code
*
* public static Iterator<String> skipNulls(final Iterator<String> in) {
* return new AbstractIterator<String>() {
* protected String computeNext() {
* while (in.hasNext()) {
* String s = in.next();
* if (s != null) {
* return s;
* }
* }
* return endOfData();
* }
* };
* }}</pre>
*
* This class supports iterators that include null elements.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
// When making changes to this class, please also update the copy at
// com.google.common.base.AbstractIterator
@GwtCompatible
public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> {
private State state = State.NOT_READY;
/** Constructor for use by subclasses. */
protected AbstractIterator() {}
private enum State {
/** We have computed the next element and haven't returned it yet. */
READY,
/** We haven't yet computed or have already returned the element. */
NOT_READY,
/** We have reached the end of the data and are finished. */
DONE,
/** We've suffered an exception and are kaput. */
FAILED,
}
private T next;
/**
* Returns the next element. <b>Note:</b> the implementation must call {@link
* #endOfData()} when there are no elements left in the iteration. Failure to
* do so could result in an infinite loop.
*
* <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls
* this method, as does the first invocation of {@code hasNext} or {@code
* next} following each successful call to {@code next}. Once the
* implementation either invokes {@code endOfData} or throws an exception,
* {@code computeNext} is guaranteed to never be called again.
*
* <p>If this method throws an exception, it will propagate outward to the
* {@code hasNext} or {@code next} invocation that invoked this method. Any
* further attempts to use the iterator will result in an {@link
* IllegalStateException}.
*
* <p>The implementation of this method may not invoke the {@code hasNext},
* {@code next}, or {@link #peek()} methods on this instance; if it does, an
* {@code IllegalStateException} will result.
*
* @return the next element if there was one. If {@code endOfData} was called
* during execution, the return value will be ignored.
* @throws RuntimeException if any unrecoverable error happens. This exception
* will propagate outward to the {@code hasNext()}, {@code next()}, or
* {@code peek()} invocation that invoked this method. Any further
* attempts to use the iterator will result in an
* {@link IllegalStateException}.
*/
protected abstract T computeNext();
/**
* Implementations of {@link #computeNext} <b>must</b> invoke this method when
* there are no elements left in the iteration.
*
* @return {@code null}; a convenience so your {@code computeNext}
* implementation can use the simple statement {@code return endOfData();}
*/
protected final T endOfData() {
state = State.DONE;
return null;
}
@Override
public final boolean hasNext() {
checkState(state != State.FAILED);
switch (state) {
case DONE:
return false;
case READY:
return true;
default:
}
return tryToComputeNext();
}
private boolean tryToComputeNext() {
state = State.FAILED; // temporary pessimism
next = computeNext();
if (state != State.DONE) {
state = State.READY;
return true;
}
return false;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
state = State.NOT_READY;
return next;
}
/**
* Returns the next element in the iteration without advancing the iteration,
* according to the contract of {@link PeekingIterator#peek()}.
*
* <p>Implementations of {@code AbstractIterator} that wish to expose this
* functionality should implement {@code PeekingIterator}.
*/
public final T peek() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return next;
}
}
| Java |
/*
* Copyright (C) 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();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* A descriptor for a <i>discrete</i> {@code Comparable} domain such as all
* {@link Integer}s. 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
* @see DiscreteDomains
*/
@GwtCompatible
@Beta
public abstract class DiscreteDomain<C extends Comparable> {
/** 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();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 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.DiscreteDomain}
* <li>{@link com.google.common.collect.DiscreteDomains}
* <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.ForwardingSortedSet}
* <li>{@link com.google.common.collect.ForwardingSortedSetMultimap}
* <li>{@link com.google.common.collect.ForwardingTable}
* </ul>
*/
@javax.annotation.ParametersAreNonnullByDefault
package com.google.common.collect;
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.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;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
/**
* An immutable hash-based multiset. Does not permit null elements.
*
* <p>Its iterator orders elements according to the first appearance of the
* element among the items passed to the factory method or builder. When the
* multiset contains multiple instances of an element, those instances are
* consecutive in the iteration order.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial") // we're overriding default serialization
// TODO(user): write an efficient asList() implementation
public abstract class ImmutableMultiset<E> extends ImmutableCollection<E>
implements Multiset<E> {
/**
* Returns the empty immutable multiset.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static <E> ImmutableMultiset<E> of() {
return (ImmutableMultiset<E>) EmptyImmutableMultiset.INSTANCE;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if {@code element} is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") // generic array created but never written
public static <E> ImmutableMultiset<E> of(E element) {
return copyOfInternal(element);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2) {
return copyOfInternal(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
return copyOfInternal(e1, e2, e3);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
return copyOfInternal(e1, e2, e3, e4);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
return copyOfInternal(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
int size = others.length + 6;
List<E> all = new ArrayList<E>(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, others);
return copyOf(all);
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.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();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multiset) {
Multiset<?> that = (Multiset<?>) object;
if (this.size() != that.size()) {
return false;
}
for (Entry<?> entry : that.entrySet()) {
if (count(entry.getElement()) != entry.getCount()) {
return false;
}
}
return true;
}
return false;
}
@Override public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override public String toString() {
return entrySet().toString();
}
private transient ImmutableSet<Entry<E>> entrySet;
@Override
public ImmutableSet<Entry<E>> entrySet() {
ImmutableSet<Entry<E>> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
abstract ImmutableSet<Entry<E>> createEntrySet();
abstract class EntrySet extends ImmutableSet<Entry<E>> {
@Override
boolean isPartialView() {
return ImmutableMultiset.this.isPartialView();
}
@Override
public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = count(entry.getElement());
return count == entry.getCount();
}
return false;
}
/*
* TODO(hhchan): Revert once we have a separate, manual emulation of this
* class.
*/
@Override
public Object[] toArray() {
Object[] newArray = new Object[size()];
return toArray(newArray);
}
/*
* TODO(hhchan): Revert once we have a separate, manual emulation of this
* class.
*/
@Override
public <T> T[] toArray(T[] other) {
int size = size();
if (other.length < size) {
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires
Object[] otherAsObjectArray = other;
int index = 0;
for (Entry<?> element : this) {
otherAsObjectArray[index++] = element;
}
return other;
}
@Override
public int hashCode() {
return ImmutableMultiset.this.hashCode();
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
// TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
Object writeReplace() {
return new EntrySetSerializedForm<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>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multisets in series.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
final Multiset<E> contents;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMultiset#builder}.
*/
public Builder() {
this(LinkedHashMultiset.<E>create());
}
Builder(Multiset<E> contents) {
this.contents = contents;
}
/**
* Adds {@code element} to the {@code ImmutableMultiset}.
*
* @param element the element to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
*/
@Override public Builder<E> add(E element) {
contents.add(checkNotNull(element));
return this;
}
/**
* Adds a number of occurrences of an element to this {@code
* ImmutableMultiset}.
*
* @param element the element to add
* @param occurrences the number of occurrences of the element to add. May
* be zero, in which case no change will be made.
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code occurrences} is negative, or
* if this operation would result in more than {@link Integer#MAX_VALUE}
* occurrences of the element
*/
public Builder<E> addCopies(E element, int occurrences) {
contents.add(checkNotNull(element), occurrences);
return this;
}
/**
* Adds or removes the necessary occurrences of an element such that the
* element attains the desired count.
*
* @param element the element to add or remove occurrences of
* @param count the desired count of the element in this multiset
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code count} is negative
*/
public Builder<E> setCount(E element, int count) {
contents.setCount(checkNotNull(element), count);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the {@code Iterable} to add to the {@code
* ImmutableMultiset}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Multiset) {
Multiset<? extends E> multiset = Multisets.cast(elements);
for (Entry<? extends E> entry : multiset.entrySet()) {
addCopies(entry.getElement(), entry.getCount());
}
} else {
super.addAll(elements);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add to the {@code ImmutableMultiset}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Returns a newly-created {@code ImmutableMultiset} based on the contents
* of the {@code Builder}.
*/
@Override public ImmutableMultiset<E> build() {
return copyOf(contents);
}
}
}
| Java |
/*
* Copyright (C) 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);
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.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);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* 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
*/
@Beta
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 poll(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 poll(delegate().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.
*/
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);
}
@Nullable
private E poll(Iterator<E> iterator) {
if (iterator.hasNext()) {
E result = iterator.next();
iterator.remove();
return result;
}
return null;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import 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;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.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();
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMultiset} with one or more elements.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial")
// uses writeReplace(), not default serialization
class RegularImmutableMultiset<E> extends ImmutableMultiset<E> {
private final transient ImmutableMap<E, Integer> map;
private final transient int size;
RegularImmutableMultiset(ImmutableMap<E, Integer> map, int size) {
this.map = map;
this.size = size;
}
@Override
boolean isPartialView() {
return map.isPartialView();
}
@Override
public int count(@Nullable Object element) {
Integer value = map.get(element);
return (value == null) ? 0 : value;
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(@Nullable Object element) {
return map.containsKey(element);
}
@Override
public ImmutableSet<E> elementSet() {
return map.keySet();
}
private static <E> Entry<E> entryFromMapEntry(Map.Entry<E, Integer> entry) {
return Multisets.immutableEntry(entry.getKey(), entry.getValue());
}
@Override
ImmutableSet<Entry<E>> createEntrySet() {
return new EntrySet();
}
private class EntrySet extends ImmutableMultiset<E>.EntrySet {
@Override
public int size() {
return map.size();
}
@Override
public UnmodifiableIterator<Entry<E>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<E>> createAsList() {
final ImmutableList<Map.Entry<E, Integer>> entryList = map.entrySet().asList();
return new ImmutableAsList<Entry<E>>() {
@Override
public Entry<E> get(int index) {
return entryFromMapEntry(entryList.get(index));
}
@Override
ImmutableCollection<Entry<E>> delegateCollection() {
return EntrySet.this;
}
};
}
}
@Override
public int hashCode() {
return map.hashCode();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Nullable;
/** An ordering that compares objects according to a given order. */
@GwtCompatible(serializable = true)
final class ExplicitOrdering<T> extends Ordering<T> implements Serializable {
final ImmutableMap<T, Integer> rankMap;
ExplicitOrdering(List<T> valuesInOrder) {
this(buildRankMap(valuesInOrder));
}
ExplicitOrdering(ImmutableMap<T, Integer> rankMap) {
this.rankMap = rankMap;
}
@Override public int compare(T left, T right) {
return rank(left) - rank(right); // safe because both are nonnegative
}
private int rank(T value) {
Integer rank = rankMap.get(value);
if (rank == null) {
throw new IncomparableValueException(value);
}
return rank;
}
private static <T> ImmutableMap<T, Integer> buildRankMap(
List<T> valuesInOrder) {
ImmutableMap.Builder<T, Integer> builder = ImmutableMap.builder();
int rank = 0;
for (T value : valuesInOrder) {
builder.put(value, rank++);
}
return builder.build();
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof ExplicitOrdering) {
ExplicitOrdering<?> that = (ExplicitOrdering<?>) object;
return this.rankMap.equals(that.rankMap);
}
return false;
}
@Override public int hashCode() {
return rankMap.hashCode();
}
@Override public String toString() {
return "Ordering.explicit(" + rankMap.keySet() + ")";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 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>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>Though the method signature doesn't say so explicitly, the returned map
* has {@link Set} values.
*/
@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);
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.SortedMap;
/**
* An object representing the differences between two sorted maps.
*
* @author Louis Wasserman
* @since 8.0
*/
@Beta
@GwtCompatible
public interface SortedMapDifference<K, V> extends MapDifference<K, V> {
@Override
SortedMap<K, V> entriesOnlyOnLeft();
@Override
SortedMap<K, V> entriesOnlyOnRight();
@Override
SortedMap<K, V> entriesInCommon();
@Override
SortedMap<K, ValueDifference<V>> entriesDiffering();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
/** An ordering that uses the natural order of the values. */
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this??
final class NaturalOrdering
extends Ordering<Comparable> implements Serializable {
static final NaturalOrdering INSTANCE = new NaturalOrdering();
@Override public int compare(Comparable left, Comparable right) {
checkNotNull(left); // for GWT
checkNotNull(right);
if (left == right) {
return 0;
}
return left.compareTo(right);
}
@Override public <S extends Comparable> Ordering<S> reverse() {
return (Ordering<S>) ReverseNaturalOrdering.INSTANCE;
}
// Override to remove a level of indirection from inner loop
@Override public int binarySearch(
List<? extends Comparable> sortedList, Comparable key) {
return Collections.binarySearch((List) sortedList, key);
}
// Override to remove a level of indirection from inner loop
@Override public <E extends Comparable> List<E> sortedCopy(
Iterable<E> iterable) {
List<E> list = Lists.newArrayList(iterable);
Collections.sort(list);
return list;
}
// preserving singleton-ness gives equals()/hashCode() for free
private Object readResolve() {
return INSTANCE;
}
@Override public String toString() {
return "Ordering.natural()";
}
private NaturalOrdering() {}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.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() {}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
* #newEnumMap} instead.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity"
* that it <i>should</i> hold {@code expectedSize} elements without growth.
* This behavior cannot be broadly guaranteed, but it is observed to be true
* for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of elements you expect to add to the
* returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
int expectedSize) {
return new HashMap<K, V>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as
* long as it grows no larger than expectedSize and the load factor is >= its
* default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkArgument(expectedSize >= 0);
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
return expectedSize + expectedSize / 3;
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as
* the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link
* #newEnumMap} instead.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code
* map}
*/
public static <K, V> HashMap<K, V> newHashMap(
Map<? extends K, ? extends V> map) {
return new HashMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap}
* instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
/**
* Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance
* with the same mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from
* {@code map}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(
Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
}
/**
* Returns a general-purpose instance of {@code ConcurrentMap}, which supports
* all optional operations of the ConcurrentMap interface. It does not permit
* null keys or values. It is serializable.
*
* <p>This is currently accomplished by calling {@link MapMaker#makeMap()}.
*
* <p>It is preferable to use {@code MapMaker} directly (rather than through
* this method), as it presents numerous useful configuration options,
* such as the concurrency level, load factor, key/value reference types,
* and value computation.
*
* @return a new, empty {@code ConcurrentMap}
* @since 3.0
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new MapMaker().<K, V>makeMap();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural
* ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#of()} instead.
*
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
/**
* Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as
* the specified map and using the same ordering as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
* @param map the sorted map whose mappings are to be placed in the new map
* and whose comparator is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code
* map} and using the comparator of {@code map}
*/
public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
return new TreeMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(
@Nullable Comparator<C> comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator<Class<?>> comparator = null;
// Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
return new TreeMap<K, V>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
return new EnumMap<K, V>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code
* map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(
Map<K, ? extends V> map) {
return new EnumMap<K, V>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<K, V>();
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* <p><b>Note:</b>If you only need to know whether two maps have the same
* mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
@SuppressWarnings("unchecked")
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
SortedMapDifference<K, V> result = difference(sortedLeft, right);
return result;
}
return difference(left, right, 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();
boolean eq = true;
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
eq = false;
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
eq = false;
onlyOnLeft.put(leftKey, leftValue);
}
}
boolean areEqual = eq && onlyOnRight.isEmpty();
return mapDifference(
areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> MapDifference<K, V> mapDifference(boolean areEqual,
Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
return new MapDifferenceImpl<K, V>(areEqual,
Collections.unmodifiableMap(onlyOnLeft),
Collections.unmodifiableMap(onlyOnRight),
Collections.unmodifiableMap(onBoth),
Collections.unmodifiableMap(differences));
}
static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
final boolean areEqual;
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(boolean areEqual, Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.areEqual = areEqual;
this.onlyOnLeft = onlyOnLeft;
this.onlyOnRight = onlyOnRight;
this.onBoth = onBoth;
this.differences = differences;
}
@Override
public boolean areEqual() {
return areEqual;
}
@Override
public Map<K, V> entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map<K, V> entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map<K, V> entriesInCommon() {
return onBoth;
}
@Override
public Map<K, ValueDifference<V>> entriesDiffering() {
return differences;
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference<?, ?> other = (MapDifference<?, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(),
entriesInCommon(), entriesDiffering());
}
@Override public String toString() {
if (areEqual) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl<V>
implements MapDifference.ValueDifference<V> {
private final V left;
private final V right;
static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) {
return new ValueDifferenceImpl<V>(left, right);
}
private ValueDifferenceImpl(@Nullable V left, @Nullable V right) {
this.left = left;
this.right = right;
}
@Override
public V leftValue() {
return left;
}
@Override
public V rightValue() {
return right;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof MapDifference.ValueDifference) {
MapDifference.ValueDifference<?> that =
(MapDifference.ValueDifference<?>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(left, right);
}
@Override public String toString() {
return "(" + left + ", " + right + ")";
}
}
/**
* Computes the difference between two sorted maps, using the comparator of
* the left map, or {@code Ordering.natural()} if the left map uses the
* natural ordering of its elements. This difference is an immutable snapshot
* of the state of the maps at the time this method is called. It will never
* change, even if the maps change at a later time.
*
* <p>Since this method uses {@code TreeMap} instances internally, the keys of
* the right map must all compare as distinct according to the comparator
* of the left map.
*
* <p><b>Note:</b>If you only need to know whether two sorted maps have the
* same mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
public static <K, V> SortedMapDifference<K, V> difference(
SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator<? super K> comparator = orNaturalOrder(left.comparator());
SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences =
Maps.newTreeMap(comparator);
boolean eq = true;
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (Objects.equal(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
eq = false;
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
eq = false;
onlyOnLeft.put(leftKey, leftValue);
}
}
boolean areEqual = eq && onlyOnRight.isEmpty();
return sortedMapDifference(
areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> SortedMapDifference<K, V> sortedMapDifference(
boolean areEqual, SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight,
SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) {
return new SortedMapDifferenceImpl<K, V>(areEqual,
Collections.unmodifiableSortedMap(onlyOnLeft),
Collections.unmodifiableSortedMap(onlyOnRight),
Collections.unmodifiableSortedMap(onBoth),
Collections.unmodifiableSortedMap(differences));
}
static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(boolean areEqual, SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override public SortedMap<K, ValueDifference<V>> entriesDiffering() {
return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
}
@Override public SortedMap<K, V> entriesInCommon() {
return (SortedMap<K, V>) super.entriesInCommon();
}
@Override public SortedMap<K, V> entriesOnlyOnLeft() {
return (SortedMap<K, V>) super.entriesOnlyOnLeft();
}
@Override public SortedMap<K, V> entriesOnlyOnRight() {
return (SortedMap<K, V>) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code
* Ordering.natural()}. This method is an abomination of generics; the only
* purpose of this method is to contain the ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static <E> Comparator<? super E> orNaturalOrder(
@Nullable Comparator<? super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator<E>) Ordering.natural();
}
/**
* Returns a view of the 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> 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> keySet() {
// probably not worth caching
return removeOnlySet(backingSet());
}
@Override
public Collection<V> values() {
// probably not worth caching
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 (backingSet().contains(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();
}
protected Entry<K, V> entry(K key) {
return immutableEntry(key, function.apply(key));
}
@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() {
final Iterator<K> backingIterator = backingSet().iterator();
return new Iterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public Entry<K, V> next() {
return entry(backingIterator.next());
}
@Override
public void remove() {
backingIterator.remove();
}
};
}
};
}
}
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 SortedAsMapView<K, V> implements NavigableMap<K, V> {
NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) {
super(ks, vFunction);
}
@Override
NavigableSet<K> backingSet() {
return (NavigableSet<K>) super.backingSet();
}
private Entry<K, V> firstEntry(NavigableSet<K> set) {
if (set.isEmpty()) {
return null;
}
return entry(set.first());
}
private K firstKey(NavigableSet<K> set) {
if (set.isEmpty()) {
return null;
}
return set.first();
}
private Entry<K, V> lastEntry(NavigableSet<K> set) {
if (set.isEmpty()) {
return null;
}
return entry(set.last());
}
private K lastKey(NavigableSet<K> set) {
if (set.isEmpty()) {
return null;
}
return set.last();
}
@Override
public Entry<K, V> lowerEntry(K key) {
return lastEntry(backingSet().headSet(key, false));
}
@Override
public K lowerKey(K key) {
return lastKey(backingSet().headSet(key, false));
}
@Override
public Entry<K, V> floorEntry(K key) {
return lastEntry(backingSet().headSet(key, true));
}
@Override
public K floorKey(K key) {
return lastKey(backingSet().headSet(key, true));
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return firstEntry(backingSet().tailSet(key, true));
}
@Override
public K ceilingKey(K key) {
return firstKey(backingSet().tailSet(key, true));
}
@Override
public Entry<K, V> higherEntry(K key) {
return firstEntry(backingSet().tailSet(key, false));
}
@Override
public K higherKey(K key) {
return firstKey(backingSet().tailSet(key, false));
}
@Override
public Entry<K, V> firstEntry() {
return firstEntry(backingSet());
}
@Override
public Entry<K, V> lastEntry() {
return lastEntry(backingSet());
}
@Override
public Entry<K, V> pollFirstEntry() {
if (!isEmpty()) {
K key = backingSet().pollFirst();
return entry(key);
}
return null;
}
@Override
public Entry<K, V> pollLastEntry() {
if (!isEmpty()) {
K key = backingSet().pollLast();
return entry(key);
}
return null;
}
@Override
public NavigableMap<K, V> descendingMap() {
return asMap(backingSet().descendingSet(), function);
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
@Override
public NavigableSet<K> navigableKeySet() {
return removeOnlyNavigableSet(backingSet());
}
@Override
public NavigableSet<K> descendingKeySet() {
return removeOnlyNavigableSet(backingSet().descendingSet());
}
@Override
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive) {
return asMap(
backingSet().subSet(fromKey, fromInclusive, toKey, toInclusive),
function);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return asMap(backingSet().headSet(toKey, inclusive), function);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return asMap(backingSet().tailSet(fromKey, inclusive), 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 for which the given {@code keys} are mapped to
* values by the given function in the order they appear in the original
* iterable. If {@code keys} contains duplicate elements, the returned map
* will contain each distinct key once in the order it first appears 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(Iterable<K> keys,
Function<? super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map for which the given {@code keys} are mapped to
* values by the given function in the order they appear in the original
* iterator. If {@code keys} contains duplicate elements, the returned map
* will contain each distinct key once in the order it first appears 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<K, V> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V getValue() {
return entry.getValue();
}
};
}
/** @see Multimaps#unmodifiableEntries */
static class UnmodifiableEntries<K, V>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
UnmodifiableEntries(Collection<Entry<K, V>> entries) {
this.entries = entries;
}
@Override protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> delegate = super.iterator();
return new ForwardingIterator<Entry<K, V>>() {
@Override public Entry<K, V> next() {
return unmodifiableEntry(super.next());
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
@Override protected Iterator<Entry<K, V>> delegate() {
return delegate;
}
};
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean add(Entry<K, V> element) {
throw new UnsupportedOperationException();
}
@Override public boolean addAll(
Collection<? extends Entry<K, V>> collection) {
throw new UnsupportedOperationException();
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object object) {
throw new UnsupportedOperationException();
}
@Override public boolean removeAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override public boolean retainAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
}
/** @see Maps#unmodifiableEntrySet(Set) */
static class UnmodifiableEntrySet<K, V>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
super(entries);
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/**
* Returns a synchronized (thread-safe) bimap backed by the specified bimap.
* In order to guarantee serial access, it is critical that <b>all</b> access
* to the backing bimap is accomplished through the returned bimap.
*
* <p>It is imperative that the user manually synchronize on the returned map
* when accessing any of its collection views: <pre> {@code
*
* BiMap<Long, String> map = Maps.synchronizedBiMap(
* HashBiMap.<Long, String>create());
* ...
* Set<Long> set = map.keySet(); // Needn't be in synchronized block
* ...
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<Long> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap to be wrapped in a synchronized view
* @return a sychronized view of the specified bimap
*/
public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
return Synchronized.biMap(bimap, null);
}
/**
* Returns an unmodifiable view of the specified bimap. This method allows
* modules to provide users with "read-only" access to internal bimaps. Query
* operations on the returned bimap "read through" to the specified bimap, and
* attempts to modify the returned map, whether direct or via its collection
* views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified bimap
*/
public static <K, V> BiMap<K, V> unmodifiableBiMap(
BiMap<? extends K, ? extends V> bimap) {
return new UnmodifiableBiMap<K, V>(bimap, null);
}
/** @see Maps#unmodifiableBiMap(BiMap) */
private static class UnmodifiableBiMap<K, V>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
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.transformSortedValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*
* @since 11.0
*/
@Beta
public static <K, V1, V2> SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, 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
*/
@Beta
@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));
}
private 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);
}
};
}
/**
* Returns a view of a map whose values are derived from the original map's
* entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "no" + key;
* }
* };
* Map<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {verbose=verbose, sort=nosort}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 7.0
*/
public static <K, V1, V2> Map<K, V2> transformEntries(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
if (fromMap instanceof SortedMap) {
return transformEntries((SortedMap<K, V1>) fromMap, transformer);
}
return new TransformedEntriesMap<K, V1, V2>(fromMap, transformer);
}
/**
* Returns a view of a sorted map whose values are derived from the original
* sorted map's entries. In contrast to {@link #transformValues}, this
* method's entry-transformation logic may depend on the key as well as the
* value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableSortedMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "yes" + key;
* }
* };
* SortedMap<String, String> transformed =
* LabsMaps.transformSortedEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 11.0
*/
@Beta
public static <K, V1, V2> SortedMap<K, V2> transformEntries(
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
*/
@Beta
@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);
}
static class TransformedEntriesMap<K, V1, V2>
extends AbstractMap<K, V2> {
final Map<K, V1> fromMap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMap(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMap = checkNotNull(fromMap);
this.transformer = checkNotNull(transformer);
}
@Override public int size() {
return fromMap.size();
}
@Override public boolean containsKey(Object key) {
return fromMap.containsKey(key);
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 get(Object key) {
V1 value = fromMap.get(key);
return (value != null || fromMap.containsKey(key))
? transformer.transformEntry((K) key, value)
: null;
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 remove(Object key) {
return fromMap.containsKey(key)
? transformer.transformEntry((K) key, fromMap.remove(key))
: null;
}
@Override public void clear() {
fromMap.clear();
}
@Override public Set<K> keySet() {
return fromMap.keySet();
}
Set<Entry<K, V2>> entrySet;
@Override public Set<Entry<K, V2>> entrySet() {
Set<Entry<K, V2>> result = entrySet;
if (result == null) {
entrySet = result = new EntrySet<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
@Override public Iterator<Entry<K, V2>> iterator() {
return new TransformedIterator<Entry<K, V1>, Entry<K, V2>>(
fromMap.entrySet().iterator()) {
@Override
Entry<K, V2> transform(final Entry<K, V1> entry) {
return new AbstractMapEntry<K, V2>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V2 getValue() {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
};
}
};
}
return result;
}
Collection<V2> values;
@Override public Collection<V2> values() {
Collection<V2> result = values;
if (result == null) {
return values = new Values<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
};
}
return result;
}
}
static class TransformedEntriesSortedMap<K, V1, V2>
extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
protected SortedMap<K, V1> fromMap() {
return (SortedMap<K, V1>) fromMap;
}
TransformedEntriesSortedMap(SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override public Comparator<? super K> comparator() {
return fromMap().comparator();
}
@Override public K firstKey() {
return fromMap().firstKey();
}
@Override public SortedMap<K, V2> headMap(K toKey) {
return transformEntries(fromMap().headMap(toKey), transformer);
}
@Override public K lastKey() {
return fromMap().lastKey();
}
@Override public SortedMap<K, V2> subMap(K fromKey, K toKey) {
return transformEntries(
fromMap().subMap(fromKey, toKey), transformer);
}
@Override public SortedMap<K, V2> tailMap(K fromKey) {
return transformEntries(fromMap().tailMap(fromKey), transformer);
}
}
@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);
}
private Entry<K, V2> transformEntry(Entry<K, V1> entry) {
if (entry == null) {
return null;
}
K key = entry.getKey();
V2 v2 = transformer.transformEntry(key, entry.getValue());
return Maps.immutableEntry(key, v2);
}
@Override protected NavigableMap<K, V1> fromMap() {
return (NavigableMap<K, V1>) super.fromMap();
}
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*/
public static <K, V> Map<K, V> filterKeys(
Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof SortedMap) {
return filterKeys((SortedMap<K, V>) unfiltered, keyPredicate);
}
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredKeyMap<K, V>(
checkNotNull(unfiltered), keyPredicate, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* keys satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO: Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*/
public static <K, V> Map<K, V> filterValues(
Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
if (unfiltered instanceof SortedMap) {
return filterValues((SortedMap<K, V>) unfiltered, valuePredicate);
}
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* values satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a map containing the mappings in {@code unfiltered} that satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes
* to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*/
public static <K, V> Map<K, V> filterEntries(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
if (unfiltered instanceof SortedMap) {
return filterEntries((SortedMap<K, V>) unfiltered, entryPredicate);
}
checkNotNull(entryPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntrySortedMap)
? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered map.
*/
private static <K, V> Map<K, V> filterFiltered(AbstractFilteredMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate =
Predicates.and(map.predicate, entryPredicate);
return new FilteredEntryMap<K, V>(map.unfiltered, predicate);
}
private abstract static class AbstractFilteredMap<K, V>
extends AbstractMap<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
AbstractFilteredMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
boolean apply(Object key, V value) {
// This method is called only when the key is in the map, implying that
// key is a K.
@SuppressWarnings("unchecked")
K k = (K) key;
return predicate.apply(Maps.immutableEntry(k, value));
}
@Override public V put(K key, V value) {
checkArgument(apply(key, value));
return unfiltered.put(key, value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
checkArgument(apply(entry.getKey(), entry.getValue()));
}
unfiltered.putAll(map);
}
@Override public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
}
@Override public V get(Object key) {
V value = unfiltered.get(key);
return ((value != null) && apply(key, value)) ? value : null;
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public V remove(Object key) {
return containsKey(key) ? unfiltered.remove(key) : null;
}
Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = new Values() : result;
}
class Values extends AbstractCollection<V> {
@Override public Iterator<V> iterator() {
final Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
@Override public int size() {
return entrySet().size();
}
@Override public void clear() {
entrySet().clear();
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public boolean remove(Object o) {
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> collection) {
checkNotNull(collection);
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (collection.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> collection) {
checkNotNull(collection);
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!collection.contains(entry.getValue())
&& predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered sorted map.
*/
private static <K, V> SortedMap<K, V> filterFiltered(
FilteredEntrySortedMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredEntrySortedMap<K, V>(map.sortedMap(), predicate);
}
private static class FilteredEntrySortedMap<K, V>
extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
FilteredEntrySortedMap(SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
}
SortedMap<K, V> sortedMap() {
return (SortedMap<K, V>) unfiltered;
}
@Override public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override public K firstKey() {
// correctly throws NoSuchElementException when filtered map is empty.
return keySet().iterator().next();
}
@Override public K lastKey() {
SortedMap<K, V> headMap = sortedMap();
while (true) {
// correctly throws NoSuchElementException when filtered map is empty.
K key = headMap.lastKey();
if (apply(key, unfiltered.get(key))) {
return key;
}
headMap = sortedMap().headMap(key);
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
return new FilteredEntrySortedMap<K, V>(sortedMap().headMap(toKey), predicate);
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().subMap(fromKey, toKey), predicate);
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().tailMap(fromKey), predicate);
}
}
private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> {
Predicate<? super K> keyPredicate;
FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate,
Predicate<Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null)
? entrySet = Sets.filter(unfiltered.entrySet(), predicate)
: result;
}
Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null)
? keySet = Sets.filter(unfiltered.keySet(), keyPredicate)
: result;
}
// The cast is called only when the key is in the unfiltered map, implying
// that key is a K.
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
}
}
static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> {
/**
* Entries in this set satisfy the predicate, but they don't validate the
* input to {@code Entry.setValue()}.
*/
final Set<Entry<K, V>> filteredEntrySet;
FilteredEntryMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
}
Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = new EntrySet() : result;
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
@Override protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator();
return new UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry<K, V> next() {
final Entry<K, V> entry = iterator.next();
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return entry;
}
@Override public V setValue(V value) {
checkArgument(apply(entry.getKey(), value));
return super.setValue(value);
}
};
}
};
}
}
Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = new KeySet() : result;
}
private class KeySet extends Sets.ImprovedAbstractSet<K> {
@Override public Iterator<K> iterator() {
final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator();
return new UnmodifiableIterator<K>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public K next() {
return iterator.next().getKey();
}
};
}
@Override public int size() {
return filteredEntrySet.size();
}
@Override public void clear() {
filteredEntrySet.clear();
}
@Override public boolean contains(Object o) {
return containsKey(o);
}
@Override public boolean remove(Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
@Override public boolean retainAll(Collection<?> collection) {
checkNotNull(collection); // for GWT
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (predicate.apply(entry) && !collection.contains(entry.getKey())) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
/**
* Returns an unmodifiable view of the specified navigable map. Query operations on the returned
* map read through to the specified map, and attempts to modify the returned map, whether direct
* or via its views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned navigable map will be serializable if the specified navigable map is
* serializable.
*
* @param map the navigable map for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable map
* @since 12.0
*/
@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, V> map) {
checkNotNull(map);
if (map instanceof UnmodifiableNavigableMap) {
return map;
} else {
return new UnmodifiableNavigableMap<K, V>(map);
}
}
@Nullable private static <K, V> Entry<K, V> unmodifiableOrNull(@Nullable Entry<K, V> entry) {
return (entry == null) ? null : Maps.unmodifiableEntry(entry);
}
@GwtIncompatible("NavigableMap")
static class UnmodifiableNavigableMap<K, V>
extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable {
private final NavigableMap<K, V> delegate;
UnmodifiableNavigableMap(NavigableMap<K, V> delegate) {
this.delegate = delegate;
}
@Override
protected SortedMap<K, V> delegate() {
return Collections.unmodifiableSortedMap(delegate);
}
@Override
public Entry<K, V> lowerEntry(K key) {
return unmodifiableOrNull(delegate.lowerEntry(key));
}
@Override
public K lowerKey(K key) {
return delegate.lowerKey(key);
}
@Override
public Entry<K, V> floorEntry(K key) {
return unmodifiableOrNull(delegate.floorEntry(key));
}
@Override
public K floorKey(K key) {
return delegate.floorKey(key);
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return unmodifiableOrNull(delegate.ceilingEntry(key));
}
@Override
public K ceilingKey(K key) {
return delegate.ceilingKey(key);
}
@Override
public Entry<K, V> higherEntry(K key) {
return unmodifiableOrNull(delegate.higherEntry(key));
}
@Override
public K higherKey(K key) {
return delegate.higherKey(key);
}
@Override
public Entry<K, V> firstEntry() {
return unmodifiableOrNull(delegate.firstEntry());
}
@Override
public Entry<K, V> lastEntry() {
return unmodifiableOrNull(delegate.lastEntry());
}
@Override
public final Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public final Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
private transient UnmodifiableNavigableMap<K, V> descendingMap;
@Override
public NavigableMap<K, V> descendingMap() {
UnmodifiableNavigableMap<K, V> result = descendingMap;
if (result == null) {
descendingMap = result = new UnmodifiableNavigableMap<K, V>(delegate.descendingMap());
result.descendingMap = this;
}
return result;
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
@Override
public NavigableSet<K> navigableKeySet() {
return Sets.unmodifiableNavigableSet(delegate.navigableKeySet());
}
@Override
public NavigableSet<K> descendingKeySet() {
return Sets.unmodifiableNavigableSet(delegate.descendingKeySet());
}
@Override
public 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>
*
* 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>
*
* 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
*/
@Beta
@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.
*/
protected abstract Set<Entry<K, V>> createEntrySet();
private Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
if (result == null) {
entrySet = result = createEntrySet();
}
return result;
}
private Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
return keySet = new KeySet<K, V>() {
@Override Map<K, V> map() {
return ImprovedAbstractMap.this;
}
};
}
return result;
}
private Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
return values = new Values<K, V>() {
@Override Map<K, V> map() {
return ImprovedAbstractMap.this;
}
};
}
return result;
}
}
static final MapJoiner STANDARD_JOINER =
Collections2.STANDARD_JOINER.withKeyValueSeparator("=");
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code
* ClassCastException}.
*/
static <V> V safeGet(Map<?, V> map, Object key) {
try {
return map.get(key);
} catch (ClassCastException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code
* ClassCastException}
*/
static boolean safeContainsKey(Map<?, ?> map, Object key) {
try {
return map.containsKey(key);
} catch (ClassCastException e) {
return false;
}
}
/**
* Implements {@code Collection.contains} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is the backing (delegate) collection, rather than
* the forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object that might be contained in {@code c}
* @return {@code true} if {@code c} contains {@code o}
*/
static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.contains(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* Implements {@code Collection.remove} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is backing (delegate) collection, rather than the
* forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object to remove from {@code c}
* @return {@code true} if {@code c} was changed
*/
static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.remove(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* An implementation of {@link Map#equals}.
*/
static boolean equalsImpl(Map<?, ?> map, Object object) {
if (map == object) {
return true;
}
if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
/**
* An implementation of {@link Map#toString}.
*/
static String toStringImpl(Map<?, ?> map) {
StringBuilder sb
= Collections2.newStringBuilderForCollection(map.size()).append('{');
STANDARD_JOINER.appendTo(sb, map);
return sb.append('}').toString();
}
/**
* An implementation of {@link Map#putAll}.
*/
static <K, V> void putAllImpl(
Map<K, V> self, Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
self.put(entry.getKey(), entry.getValue());
}
}
/**
* An admittedly inefficient implementation of {@link Map#containsKey}.
*/
static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) {
for (Entry<?, ?> entry : map.entrySet()) {
if (Objects.equal(entry.getKey(), key)) {
return true;
}
}
return false;
}
/**
* An implementation of {@link Map#containsValue}.
*/
static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) {
for (Entry<?, ?> entry : map.entrySet()) {
if (Objects.equal(entry.getValue(), value)) {
return true;
}
}
return false;
}
static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, K>(entryIterator) {
@Override
K transform(Entry<K, V> entry) {
return entry.getKey();
}
};
}
abstract static class KeySet<K, V> extends Sets.ImprovedAbstractSet<K> {
abstract Map<K, V> 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();
}
@GwtIncompatible("NavigableMap")
abstract static class NavigableKeySet<K, V> extends KeySet<K, V> implements NavigableSet<K> {
@Override
abstract NavigableMap<K, V> map();
@Override
public Comparator<? super K> comparator() {
return map().comparator();
}
@Override
public K first() {
return map().firstKey();
}
@Override
public K last() {
return map().lastKey();
}
@Override
public K lower(K e) {
return map().lowerKey(e);
}
@Override
public K floor(K e) {
return map().floorKey(e);
}
@Override
public K ceiling(K e) {
return map().ceilingKey(e);
}
@Override
public K higher(K e) {
return map().higherKey(e);
}
@Override
public K pollFirst() {
return keyOrNull(map().pollFirstEntry());
}
@Override
public K pollLast() {
return keyOrNull(map().pollLastEntry());
}
@Override
public NavigableSet<K> descendingSet() {
return map().descendingKeySet();
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> subSet(
K fromElement,
boolean fromInclusive,
K toElement,
boolean toInclusive) {
return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet();
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return map().headMap(toElement, inclusive).navigableKeySet();
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return map().tailMap(fromElement, inclusive).navigableKeySet();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public SortedSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
}
static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, V>(entryIterator) {
@Override
V transform(Entry<K, V> entry) {
return entry.getValue();
}
};
}
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();
}
};
}
abstract static class Values<K, V> extends AbstractCollection<V> {
abstract Map<K, V> 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 = map().get(key);
return Objects.equal(value, entry.getValue())
&& (value != null || map().containsKey(key));
}
return false;
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return map().keySet().remove(entry.getKey());
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
boolean changed = true;
for (Object o : c) {
changed |= remove(o);
}
return changed;
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size());
for (Object o : c) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
keys.add(entry.getKey());
}
}
return map().keySet().retainAll(keys);
}
}
}
@GwtIncompatible("NavigableMap")
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;
if (result == null) {
result = navigableKeySet = new NavigableKeySet<K, V>() {
@Override
NavigableMap<K, V> map() {
return DescendingMap.this;
}
};
}
return result;
}
@Override
public NavigableSet<K> descendingKeySet() {
return forward().navigableKeySet();
}
@Override
public
NavigableMap<K, V>
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap();
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return forward().tailMap(toKey, inclusive).descendingMap();
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return forward().headMap(fromKey, inclusive).descendingMap();
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public Collection<V> values() {
return new Values<K, V>() {
@Override
Map<K, V> map() {
return DescendingMap.this;
}
};
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import 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 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.
*
* <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]
* George: [Washington, Bush, Bush]
* Grover: [Cleveland]
* ...}</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.
*
* <h3>Uses</h3>
*
* <p>Multimaps are commonly used anywhere a {@code Map<K, Collection<V>>} would
* otherwise have appeared. The advantages 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>It will not retain empty collections after the last value for a key is
* removed. As a result, {@link #containsKey} behaves logically, and the
* multimap won't leak memory.
* <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>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 the multimap. */
int size();
/** Returns {@code true} if the multimap contains no key-value pairs. */
boolean isEmpty();
/**
* Returns {@code true} if the multimap contains any values for the specified
* key.
*
* @param key key to search for in multimap
*/
boolean containsKey(@Nullable Object key);
/**
* Returns {@code true} if the multimap contains the specified value for any
* key.
*
* @param value value to search for in multimap
*/
boolean containsValue(@Nullable Object value);
/**
* Returns {@code true} if the multimap contains the specified key-value pair.
*
* @param key key to search for in multimap
* @param value value to search for in multimap
*/
boolean containsEntry(@Nullable Object key, @Nullable Object value);
// Modification Operations
/**
* Stores a key-value pair in the 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.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @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 from the multimap.
*
* @param key key of entry to remove from the multimap
* @param value value of entry to remove the multimap
* @return {@code true} if the multimap changed
*/
boolean remove(@Nullable Object key, @Nullable Object value);
// Bulk Operations
/**
* Stores a collection of values with the same key.
*
* @param key key to store in the multimap
* @param values values to store in the multimap
* @return {@code true} if the multimap changed
*/
boolean putAll(@Nullable K key, Iterable<? extends V> values);
/**
* Copies all of another multimap's key-value pairs into this multimap. The
* order in which the mappings are added is determined by
* {@code multimap.entries()}.
*
* @param multimap mappings to store in this multimap
* @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.
*
* @param key key to store in the multimap
* @param values values to store in the multimap
* @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 a given key.
*
* @param key key of entries to remove from the multimap
* @return the collection of removed values, or an empty collection if no
* values were associated with the provided key. The 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.
*/
void clear();
// Views
/**
* Returns a collection view of all values associated with a key. If no
* mappings in the multimap have the provided key, an empty collection is
* returned.
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa.
*
* @param key key to search for in multimap
* @return the collection of values that the key maps to
*/
Collection<V> get(@Nullable K key);
/**
* Returns the set of all keys, each appearing once in the returned set.
* Changes to the returned set will update the underlying multimap, and vice
* versa.
*
* @return the collection of distinct keys
*/
Set<K> keySet();
/**
* Returns a collection, which may contain duplicates, of all keys. The number
* of times of key appears in the returned multiset equals the number of
* mappings the key has in the multimap. Changes to the returned multiset will
* update the underlying multimap, and vice versa.
*
* @return a multiset with keys corresponding to the distinct keys of the
* multimap and frequencies corresponding to the number of values that
* each key maps to
*/
Multiset<K> keys();
/**
* Returns a collection of all values in the multimap. Changes to the returned
* collection will update the underlying multimap, and vice versa.
*
* @return collection of values, which may include the same value multiple
* times if it occurs in multiple mappings
*/
Collection<V> values();
/**
* Returns a collection of all key-value pairs. Changes to the returned
* collection will update the underlying multimap, and vice versa. The entries
* collection does not support the {@code add} or {@code addAll} operations.
*
* @return collection of map entries consisting of key-value pairs
*/
Collection<Map.Entry<K, V>> entries();
/**
* Returns a map view that associates each key with the corresponding values
* in the multimap. Changes to the returned map, such as element removal, will
* update the underlying multimap. The map does not support {@code setValue()}
* on its entries, {@code put}, or {@code putAll}.
*
* <p>When passed a key that is present in the map, {@code
* asMap().get(Object)} has the same behavior as {@link #get}, returning a
* live collection. When passed a key that is not present, however, {@code
* asMap().get(Object)} returns {@code null} instead of an empty collection.
*
* @return a map view from a key to its collection of values
*/
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();
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.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();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* An empty immutable multiset.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
final class EmptyImmutableMultiset extends ImmutableMultiset<Object> {
static final EmptyImmutableMultiset INSTANCE = new EmptyImmutableMultiset();
@Override
public int count(@Nullable Object element) {
return 0;
}
@Override
public boolean contains(@Nullable Object object) {
return false;
}
@Override
public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override
public UnmodifiableIterator<Object> iterator() {
return Iterators.emptyIterator();
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Multiset) {
Multiset<?> other = (Multiset<?>) object;
return other.isEmpty();
}
return false;
}
@Override
public int hashCode() {
return 0;
}
@Override
public ImmutableSet<Object> elementSet() {
return ImmutableSet.of();
}
@Override
public ImmutableSet<Entry<Object>> entrySet() {
return ImmutableSet.of();
}
@Override
ImmutableSet<Entry<Object>> createEntrySet() {
throw new AssertionError("should never be called");
}
@Override
public int size() {
return 0;
}
@Override
boolean isPartialView() {
return false;
}
@Override
public Object[] toArray() {
return ObjectArrays.EMPTY_ARRAY;
}
@Override
public <T> T[] toArray(T[] other) {
return asList().toArray(other);
}
@Override
public ImmutableList<Object> asList() {
return ImmutableList.of();
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A set multimap which forwards all its method calls to another set multimap.
* Subclasses should override one or more methods to modify the behavior of
* the backing multimap as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Kurt Alfred Kluever
* @since 3.0
*/
@GwtCompatible
public abstract class ForwardingSetMultimap<K, V>
extends ForwardingMultimap<K, V> implements SetMultimap<K, V> {
@Override protected abstract SetMultimap<K, V> delegate();
@Override public Set<Entry<K, V>> entries() {
return delegate().entries();
}
@Override public Set<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override public Set<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@Override public Set<V> replaceValues(K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
}
| Java |
/*
* Copyright (C) 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;
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.ListIterator;
/**
* A list iterator that does not support {@link #remove}, {@link #add}, or
* {@link #set}.
*
* @since 7.0
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class UnmodifiableListIterator<E>
extends UnmodifiableIterator<E> implements ListIterator<E> {
/** Constructor for use by subclasses. */
protected UnmodifiableListIterator() {}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
* @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();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
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.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
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) {
return new UnmodifiableSortedMultiset<E>(checkNotNull(sortedMultiset));
}
private static final class UnmodifiableSortedMultiset<E>
extends UnmodifiableMultiset<E> implements SortedMultiset<E> {
private UnmodifiableSortedMultiset(SortedMultiset<E> delegate) {
super(delegate);
}
@Override
protected SortedMultiset<E> delegate() {
return (SortedMultiset<E>) super.delegate();
}
@Override
public Comparator<? super E> comparator() {
return delegate().comparator();
}
@Override
SortedSet<E> createElementSet() {
return Collections.unmodifiableSortedSet(delegate().elementSet());
}
@Override
public SortedSet<E> elementSet() {
return (SortedSet<E>) super.elementSet();
}
private transient UnmodifiableSortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
UnmodifiableSortedMultiset<E> result = descendingMultiset;
if (result == null) {
result = new UnmodifiableSortedMultiset<E>(
delegate().descendingMultiset());
result.descendingMultiset = this;
return descendingMultiset = result;
}
return result;
}
@Override
public Entry<E> firstEntry() {
return delegate().firstEntry();
}
@Override
public Entry<E> lastEntry() {
return delegate().lastEntry();
}
@Override
public Entry<E> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<E> pollLastEntry() {
throw new UnsupportedOperationException();
}
@Override
public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
return unmodifiableSortedMultiset(
delegate().headMultiset(upperBound, boundType));
}
@Override
public SortedMultiset<E> subMultiset(
E lowerBound, BoundType lowerBoundType,
E upperBound, BoundType upperBoundType) {
return unmodifiableSortedMultiset(delegate().subMultiset(
lowerBound, lowerBoundType, upperBound, upperBoundType));
}
@Override
public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
return unmodifiableSortedMultiset(
delegate().tailMultiset(lowerBound, boundType));
}
private static final long serialVersionUID = 0;
}
/**
* 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;
checkArgument(count >= 0);
}
@Override
@Nullable public E getElement() {
return element;
}
@Override
public int getCount() {
return count;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a multiset view of the specified set. The multiset is backed by the
* set, so changes to the set are reflected in the multiset, and vice versa.
* If the set is modified while an iteration over the multiset is in progress
* (except through the iterator's own {@code remove} operation) the results of
* the iteration are undefined.
*
* <p>The multiset supports element removal, which removes the corresponding
* element from the set. It does not support the {@code add} or {@code addAll}
* operations, nor does it support the use of {@code setCount} to add
* elements.
*
* <p>The returned multiset will be serializable if the specified set is
* serializable. The multiset is threadsafe if the set is threadsafe.
*
* @param set the backing set for the returned multiset view
*/
static <E> Multiset<E> forSet(Set<E> set) {
return new SetMultiset<E>(set);
}
/** @see Multisets#forSet */
private static class SetMultiset<E> extends ForwardingCollection<E>
implements Multiset<E>, Serializable {
final Set<E> delegate;
SetMultiset(Set<E> set) {
delegate = checkNotNull(set);
}
@Override protected Set<E> delegate() {
return delegate;
}
@Override
public int count(Object element) {
return delegate.contains(element) ? 1 : 0;
}
@Override
public int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
@Override
public int remove(Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0);
return delegate.remove(element) ? 1 : 0;
}
transient Set<E> elementSet;
@Override
public Set<E> elementSet() {
Set<E> es = elementSet;
return (es == null) ? elementSet = new ElementSet() : es;
}
transient Set<Entry<E>> entrySet;
@Override public Set<Entry<E>> entrySet() {
Set<Entry<E>> es = entrySet;
if (es == null) {
es = entrySet = new EntrySet<E>() {
@Override Multiset<E> multiset() {
return SetMultiset.this;
}
@Override public Iterator<Entry<E>> iterator() {
return new TransformedIterator<E, Entry<E>>(delegate.iterator()) {
@Override
Entry<E> transform(E e) {
return Multisets.immutableEntry(e, 1);
}
};
}
@Override public int size() {
return delegate.size();
}
};
}
return es;
}
@Override public boolean add(E o) {
throw new UnsupportedOperationException();
}
@Override public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public int setCount(E element, int count) {
checkNonnegative(count, "count");
if (count == count(element)) {
return count;
} else if (count == 0) {
remove(element);
return 1;
} else {
throw new UnsupportedOperationException();
}
}
@Override
public boolean setCount(E element, int oldCount, int newCount) {
return setCountImpl(this, element, oldCount, newCount);
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Multiset) {
Multiset<?> that = (Multiset<?>) object;
return this.size() == that.size() && delegate.equals(that.elementSet());
}
return false;
}
@Override public int hashCode() {
int sum = 0;
for (E e : this) {
sum += ((e == null) ? 0 : e.hashCode()) ^ 1;
}
return sum;
}
/** @see SetMultiset#elementSet */
class ElementSet extends ForwardingSet<E> {
@Override protected Set<E> delegate() {
return delegate;
}
@Override public boolean add(E o) {
throw new UnsupportedOperationException();
}
@Override public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
}
private static final long serialVersionUID = 0;
}
/**
* 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 <b>view</b> of the intersection of two multisets.
* An element's count in the multiset is the smaller of its counts in the two
* backing multisets. The iteration order of the returned multiset matches 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();
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 Multisets.immutableEntry(element, count);
}
}
return endOfData();
}
};
}
@Override
int distinctElements() {
return elementSet().size();
}
};
}
/**
* 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) {
@SuppressWarnings("cast")
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = multiset().count(entry.getElement());
return count == entry.getCount();
}
return false;
}
@SuppressWarnings("cast")
@Override public boolean remove(Object o) {
return contains(o)
&& multiset().elementSet().remove(((Entry<?>) o).getElement());
}
@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() {
Iterators.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);
}
static void checkNonnegative(int count, String name) {
checkArgument(count >= 0, "%s cannot be negative: %s", name, count);
}
/**
* 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.sortedCopy(multiset.entrySet());
return ImmutableMultiset.copyFromEntries(sortedEntries);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.keyOrNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
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,
Collection<? extends Entry<? extends K, ? extends V>> entries) {
if (entries.isEmpty()) {
return emptyMap(comparator);
}
ImmutableList.Builder<K> keyBuilder = ImmutableList.builder();
ImmutableList.Builder<V> valueBuilder = ImmutableList.builder();
for (Entry<? extends K, ? extends V> entry : entries) {
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
*/
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).build();
}
/**
* 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
*/
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 new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).build();
}
/**
* 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
*/
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 new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).build();
}
/**
* 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
*/
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 new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).put(k5, v5).build();
}
/**
* 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]);
for (int i = 0; i < entries.length; i++) {
Entry<K, V> entry = entries[i];
entries[i] = entryOf(entry.getKey(), entry.getValue());
}
List<Entry<K, V>> list = Arrays.asList(entries);
if (!sameComparator) {
sortEntries(list, comparator);
validateEntries(list, comparator);
}
return fromSortedEntries(comparator, list);
}
private static <K, V> void sortEntries(
List<Entry<K, V>> entries, final Comparator<? super K> comparator) {
Comparator<Entry<K, V>> entryComparator = new Comparator<Entry<K, V>>() {
@Override public int compare(Entry<K, V> entry1, Entry<K, V> entry2) {
return comparator.compare(entry1.getKey(), entry2.getKey());
}
};
Collections.sort(entries, entryComparator);
}
private static <K, V> void validateEntries(List<Entry<K, V>> entries,
Comparator<? super K> comparator) {
for (int i = 1; i < entries.size(); i++) {
if (comparator.compare(
entries.get(i - 1).getKey(), entries.get(i).getKey()) == 0) {
throw new IllegalArgumentException(
"Duplicate keys in mappings " + entries.get(i - 1) + " and "
+ entries.get(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.
*
* <p>Note: the type parameter {@code K} extends {@code Comparable<K>} rather
* than {@code Comparable<? super K>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <K extends Comparable<K>, 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.
*
* <p>Note: the type parameter {@code K} extends {@code Comparable<K>} rather
* than {@code Comparable<? super K>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <K extends Comparable<K>, 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>
*
* 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}.
*/
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) {
entries.add(entryOf(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) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
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() {
sortEntries(entries, comparator);
validateEntries(entries, comparator);
return fromSortedEntries(comparator, 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;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
/**
* "Overrides" the {@link ImmutableMap} static methods that lack
* {@link ImmutableSortedMap} equivalents with deprecated, exception-throwing
* versions. See {@link ImmutableSortedSetFauxverideShim} for details.
*
* @author Chris Povirk
*/
@GwtCompatible
abstract class ImmutableSortedMapFauxverideShim<K, V>
extends ImmutableMap<K, V> {
/**
* Not supported. Use {@link ImmutableSortedMap#naturalOrder}, which offers
* better type-safety, instead. This method exists only to hide
* {@link ImmutableMap#builder} from consumers of {@code ImmutableSortedMap}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedMap#naturalOrder}, which offers
* better type-safety.
*/
@Deprecated public static <K, V> ImmutableSortedMap.Builder<K, V> builder() {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain a
* non-{@code Comparable} key.</b> Proper calls will resolve to the version in
* {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass a key of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls will resolve to the version
* in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls to will resolve to the
* version in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object,
* Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls will resolve to the version
* in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object,
* Comparable, Object, Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a map that may contain
* non-{@code Comparable} keys.</b> Proper calls will resolve to the version
* in {@code ImmutableSortedMap}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass keys of type {@code Comparable} to use {@link
* ImmutableSortedMap#of(Comparable, Object, Comparable, Object,
* Comparable, Object, Comparable, Object, Comparable, Object)}.</b>
*/
@Deprecated public static <K, V> ImmutableSortedMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
throw new UnsupportedOperationException();
}
// No copyOf() fauxveride; see ImmutableSortedSetFauxverideShim.
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import 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>
*
* 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();
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An implementation of {@link ImmutableTable} that holds a single cell.
*
* @author Gregory Kick
*/
@GwtCompatible
final class SingletonImmutableTable<R, C, V> extends ImmutableTable<R, C, V> {
private final R singleRowKey;
private final C singleColumnKey;
private 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 ImmutableSet<Cell<R, C, V>> cellSet() {
return ImmutableSet.of(
Tables.immutableCell(singleRowKey, singleColumnKey, singleValue));
}
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
return containsColumn(columnKey)
? ImmutableMap.of(singleRowKey, singleValue)
: ImmutableMap.<R, V>of();
}
@Override public ImmutableSet<C> columnKeySet() {
return ImmutableSet.of(singleColumnKey);
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
return ImmutableMap.of(singleColumnKey,
(Map<R, V>) ImmutableMap.of(singleRowKey, singleValue));
}
@Override public boolean contains(@Nullable Object rowKey,
@Nullable Object columnKey) {
return containsRow(rowKey) && containsColumn(columnKey);
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return Objects.equal(this.singleColumnKey, columnKey);
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return Objects.equal(this.singleRowKey, rowKey);
}
@Override public boolean containsValue(@Nullable Object value) {
return Objects.equal(this.singleValue, value);
}
@Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
return contains(rowKey, columnKey) ? singleValue : null;
}
@Override public boolean isEmpty() {
return false;
}
@Override public ImmutableMap<C, V> row(R rowKey) {
checkNotNull(rowKey);
return containsRow(rowKey)
? ImmutableMap.of(singleColumnKey, singleValue)
: ImmutableMap.<C, V>of();
}
@Override public ImmutableSet<R> rowKeySet() {
return ImmutableSet.of(singleRowKey);
}
@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 public ImmutableCollection<V> values() {
return ImmutableSet.of(singleValue);
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Table) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
if (that.size() == 1) {
Cell<?, ?, ?> thatCell = that.cellSet().iterator().next();
return Objects.equal(this.singleRowKey, thatCell.getRowKey()) &&
Objects.equal(this.singleColumnKey, thatCell.getColumnKey()) &&
Objects.equal(this.singleValue, thatCell.getValue());
}
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(singleRowKey, singleColumnKey, singleValue);
}
@Override public String toString() {
return new StringBuilder()
.append('{')
.append(singleRowKey)
.append("={")
.append(singleColumnKey)
.append('=')
.append(singleValue)
.append("}}")
.toString();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2.TransformedCollection;
import com.google.common.collect.Maps.EntryTransformer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static methods acting on or generating a {@code Multimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multimaps">
* {@code Multimaps}</a>.
*
* @author Jared Levy
* @author Robert Konigsberg
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Multimaps {
private Multimaps() {}
/**
* Creates a new {@code Multimap} that uses the provided map and factory. It
* can generate a multimap based on arbitrary {@link Map} and
* {@link Collection} classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* collections generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link ArrayListMultimap#create()}, {@link HashMultimap#create()},
* {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()},
* {@link TreeMultimap#create()}, and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the collections returned by {@code factory}. Those objects should not be
* manually updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty collections that will each hold all
* values for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> Multimap<K, V> newMultimap(Map<K, Collection<V>> map,
final Supplier<? extends Collection<V>> factory) {
return new CustomMultimap<K, V>(map, factory);
}
private static class CustomMultimap<K, V> extends AbstractMultimap<K, V> {
transient Supplier<? extends Collection<V>> factory;
CustomMultimap(Map<K, Collection<V>> map,
Supplier<? extends Collection<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected Collection<V> createCollection() {
return factory.get();
}
// can't use Serialization writeMultimap and populateMultimap methods since
// there's no way to generate the empty backing map.
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends Collection<V>>) stream.readObject();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("java serialization not supported")
private static final long serialVersionUID = 0;
}
/**
* Creates a new {@code ListMultimap} that uses the provided map and factory.
* It can generate a multimap based on arbitrary {@link Map} and {@link List}
* classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. The multimap's {@code get}, {@code
* removeAll}, and {@code replaceValues} methods return {@code RandomAccess}
* lists if the factory does. However, the multimap's {@code get} method
* returns instances of a different class than does {@code factory.get()}.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* lists generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedListMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link ArrayListMultimap#create()} and {@link LinkedListMultimap#create()}
* won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the lists returned by {@code factory}. Those objects should not be manually
* updated, they should be empty when provided, and they should not use soft,
* weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty lists that will each hold all values
* for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> ListMultimap<K, V> newListMultimap(
Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) {
return new CustomListMultimap<K, V>(map, factory);
}
private static class CustomListMultimap<K, V>
extends AbstractListMultimap<K, V> {
transient Supplier<? extends List<V>> factory;
CustomListMultimap(Map<K, Collection<V>> map,
Supplier<? extends List<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected List<V> createCollection() {
return factory.get();
}
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends List<V>>) stream.readObject();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("java serialization not supported")
private static final long serialVersionUID = 0;
}
/**
* Creates a new {@code SetMultimap} that uses the provided map and factory.
* It can generate a multimap based on arbitrary {@link Map} and {@link Set}
* classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* sets generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedSetMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link HashMultimap#create()}, {@link LinkedHashMultimap#create()},
* {@link TreeMultimap#create()}, and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the sets returned by {@code factory}. Those objects should not be manually
* updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty sets that will each hold all values
* for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> SetMultimap<K, V> newSetMultimap(
Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) {
return new CustomSetMultimap<K, V>(map, factory);
}
private static class CustomSetMultimap<K, V>
extends AbstractSetMultimap<K, V> {
transient Supplier<? extends Set<V>> factory;
CustomSetMultimap(Map<K, Collection<V>> map,
Supplier<? extends Set<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected Set<V> createCollection() {
return factory.get();
}
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends Set<V>>) stream.readObject();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
/**
* Creates a new {@code SortedSetMultimap} that uses the provided map and
* factory. It can generate a multimap based on arbitrary {@link Map} and
* {@link SortedSet} classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* sets generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedSortedSetMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link TreeMultimap#create()} and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the sets returned by {@code factory}. Those objects should not be manually
* updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty sorted sets that will each hold
* all values for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> SortedSetMultimap<K, V> newSortedSetMultimap(
Map<K, Collection<V>> map,
final Supplier<? extends SortedSet<V>> factory) {
return new CustomSortedSetMultimap<K, V>(map, factory);
}
private static class CustomSortedSetMultimap<K, V>
extends AbstractSortedSetMultimap<K, V> {
transient Supplier<? extends SortedSet<V>> factory;
transient Comparator<? super V> valueComparator;
CustomSortedSetMultimap(Map<K, Collection<V>> map,
Supplier<? extends SortedSet<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
valueComparator = factory.get().comparator();
}
@Override protected SortedSet<V> createCollection() {
return factory.get();
}
@Override public Comparator<? super V> valueComparator() {
return valueComparator;
}
/** @serialData the factory and the backing map */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends SortedSet<V>>) stream.readObject();
valueComparator = factory.get().comparator();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
@GwtIncompatible("not needed in emulated source")
private static final long serialVersionUID = 0;
}
/**
* Copies each key-value mapping in {@code source} into {@code dest}, with
* its key and value reversed.
*
* <p>If {@code source} is an {@link ImmutableMultimap}, consider using
* {@link ImmutableMultimap#inverse} instead.
*
* @param source any multimap
* @param dest the multimap to copy into; usually empty
* @return {@code dest}
*/
public static <K, V, M extends Multimap<K, V>> M invertFrom(
Multimap<? extends V, ? extends K> source, M dest) {
checkNotNull(dest);
for (Map.Entry<? extends V, ? extends K> entry : source.entries()) {
dest.put(entry.getValue(), entry.getKey());
}
return dest;
}
/**
* Returns a synchronized (thread-safe) multimap backed by the specified
* multimap. In order to guarantee serial access, it is critical that
* <b>all</b> access to the backing multimap is accomplished through the
* returned multimap.
*
* <p>It is imperative that the user manually synchronize on the returned
* multimap when accessing any of its collection views: <pre> {@code
*
* Multimap<K, V> 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>
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that aren't
* synchronized.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped in a synchronized view
* @return a synchronized view of the specified multimap
*/
public static <K, V> Multimap<K, V> synchronizedMultimap(
Multimap<K, V> multimap) {
return Synchronized.multimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified multimap. Query operations on
* the returned multimap "read through" to the specified multimap, and
* attempts to modify the returned multimap, either directly or through the
* multimap's views, result in an {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> Multimap<K, V> unmodifiableMultimap(
Multimap<K, V> delegate) {
if (delegate instanceof UnmodifiableMultimap ||
delegate instanceof ImmutableMultimap) {
return delegate;
}
return new UnmodifiableMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap(
ImmutableMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
private static class UnmodifiableMultimap<K, V>
extends ForwardingMultimap<K, V> implements Serializable {
final Multimap<K, V> delegate;
transient Collection<Entry<K, V>> entries;
transient Multiset<K> keys;
transient Set<K> keySet;
transient Collection<V> values;
transient Map<K, Collection<V>> map;
UnmodifiableMultimap(final Multimap<K, V> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override protected Multimap<K, V> delegate() {
return delegate;
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = map;
if (result == null) {
final Map<K, Collection<V>> unmodifiableMap
= Collections.unmodifiableMap(delegate.asMap());
map = result = new ForwardingMap<K, Collection<V>>() {
@Override protected Map<K, Collection<V>> delegate() {
return unmodifiableMap;
}
Set<Entry<K, Collection<V>>> entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
Set<Entry<K, Collection<V>>> result = entrySet;
return (result == null)
? entrySet
= unmodifiableAsMapEntries(unmodifiableMap.entrySet())
: result;
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = unmodifiableMap.get(key);
return (collection == null)
? null : unmodifiableValueCollection(collection);
}
Collection<Collection<V>> asMapValues;
@Override public Collection<Collection<V>> values() {
Collection<Collection<V>> result = asMapValues;
return (result == null)
? asMapValues
= new UnmodifiableAsMapValues<V>(unmodifiableMap.values())
: result;
}
@Override public boolean containsValue(Object o) {
return values().contains(o);
}
};
}
return result;
}
@Override public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
if (result == null) {
entries = result = unmodifiableEntries(delegate.entries());
}
return result;
}
@Override public Collection<V> get(K key) {
return unmodifiableValueCollection(delegate.get(key));
}
@Override public Multiset<K> keys() {
Multiset<K> result = keys;
if (result == null) {
keys = result = Multisets.unmodifiableMultiset(delegate.keys());
}
return result;
}
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
keySet = result = Collections.unmodifiableSet(delegate.keySet());
}
return result;
}
@Override public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
values = result = Collections.unmodifiableCollection(delegate.values());
}
return result;
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableAsMapValues<V>
extends ForwardingCollection<Collection<V>> {
final Collection<Collection<V>> delegate;
UnmodifiableAsMapValues(Collection<Collection<V>> delegate) {
this.delegate = Collections.unmodifiableCollection(delegate);
}
@Override protected Collection<Collection<V>> delegate() {
return delegate;
}
@Override public Iterator<Collection<V>> iterator() {
final Iterator<Collection<V>> iterator = delegate.iterator();
return new UnmodifiableIterator<Collection<V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Collection<V> next() {
return unmodifiableValueCollection(iterator.next());
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return standardContains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
}
private static class UnmodifiableListMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> {
UnmodifiableListMultimap(ListMultimap<K, V> delegate) {
super(delegate);
}
@Override public ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
return Collections.unmodifiableList(delegate().get(key));
}
@Override public List<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSetMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> {
UnmodifiableSetMultimap(SetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
/*
* Note that this doesn't return a SortedSet when delegate is a
* SortedSetMultiset, unlike (SortedSet<V>) super.get().
*/
return Collections.unmodifiableSet(delegate().get(key));
}
@Override public Set<Map.Entry<K, V>> entries() {
return Maps.unmodifiableEntrySet(delegate().entries());
}
@Override public Set<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSortedSetMultimap<K, V>
extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> {
UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
return Collections.unmodifiableSortedSet(delegate().get(key));
}
@Override public SortedSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super V> valueComparator() {
return delegate().valueComparator();
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) {@code SetMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> synchronizedSetMultimap(
SetMultimap<K, V> multimap) {
return Synchronized.setMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SetMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
SetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSetMultimap ||
delegate instanceof ImmutableSetMultimap) {
return delegate;
}
return new UnmodifiableSetMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
ImmutableSetMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by
* the specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V>
synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) {
return Synchronized.sortedSetMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SortedSetMultimap}.
* Query operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(
SortedSetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSortedSetMultimap) {
return delegate;
}
return new UnmodifiableSortedSetMultimap<K, V>(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code ListMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> synchronizedListMultimap(
ListMultimap<K, V> multimap) {
return Synchronized.listMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code ListMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ListMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableListMultimap ||
delegate instanceof ImmutableListMultimap) {
return delegate;
}
return new UnmodifiableListMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ImmutableListMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns an unmodifiable view of the specified collection, preserving the
* interface for instances of {@code SortedSet}, {@code Set}, {@code List} and
* {@code Collection}, in that order of preference.
*
* @param collection the collection for which to return an unmodifiable view
* @return an unmodifiable view of the collection
*/
private static <V> Collection<V> unmodifiableValueCollection(
Collection<V> collection) {
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
}
return Collections.unmodifiableCollection(collection);
}
/**
* Returns an unmodifiable view of the specified multimap {@code asMap} entry.
* The {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}, and the collection returned by {@code
* getValue} is also an unmodifiable (type-preserving) view. This also has the
* side-effect of redefining equals to comply with the Map.Entry contract, and
* to avoid a possible nefarious implementation of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
private static <K, V> Map.Entry<K, Collection<V>> unmodifiableAsMapEntry(
final Map.Entry<K, Collection<V>> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, Collection<V>>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public Collection<V> getValue() {
return unmodifiableValueCollection(entry.getValue());
}
};
}
/**
* Returns an unmodifiable view of the specified collection of entries. The
* {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}. If the specified collection is a {@code
* Set}, the returned collection is also a {@code Set}.
*
* @param entries the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
private static <K, V> Collection<Entry<K, V>> unmodifiableEntries(
Collection<Entry<K, V>> entries) {
if (entries instanceof Set) {
return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries);
}
return new Maps.UnmodifiableEntries<K, V>(
Collections.unmodifiableCollection(entries));
}
/**
* Returns an unmodifiable view of the specified set of {@code asMap} entries.
* The {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}, as do any operations that attempt to modify
* the returned collection.
*
* @param asMapEntries the {@code asMap} entries for which to return an
* unmodifiable view
* @return an unmodifiable view of the collection entries
*/
private static <K, V> Set<Entry<K, Collection<V>>> unmodifiableAsMapEntries(
Set<Entry<K, Collection<V>>> asMapEntries) {
return new UnmodifiableAsMapEntries<K, V>(
Collections.unmodifiableSet(asMapEntries));
}
/** @see Multimaps#unmodifiableAsMapEntries */
static class UnmodifiableAsMapEntries<K, V>
extends ForwardingSet<Entry<K, Collection<V>>> {
private final Set<Entry<K, Collection<V>>> delegate;
UnmodifiableAsMapEntries(Set<Entry<K, Collection<V>>> delegate) {
this.delegate = delegate;
}
@Override protected Set<Entry<K, Collection<V>>> delegate() {
return delegate;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = delegate.iterator();
return new ForwardingIterator<Entry<K, Collection<V>>>() {
@Override protected Iterator<Entry<K, Collection<V>>> delegate() {
return iterator;
}
@Override public Entry<K, Collection<V>> next() {
return unmodifiableAsMapEntry(iterator.next());
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
}
/**
* Returns a multimap view of the specified map. The multimap is backed by the
* map, so changes to the map are reflected in the multimap, and vice versa.
* If the map is modified while an iteration over one of the multimap's
* collection views is in progress (except through the iterator's own {@code
* remove} operation, or through the {@code setValue} operation on a map entry
* returned by the iterator), the results of the iteration are undefined.
*
* <p>The multimap supports mapping removal, which removes the corresponding
* mapping from the map. It does not support any operations which might add
* mappings, such as {@code put}, {@code putAll} or {@code replaceValues}.
*
* <p>The returned multimap will be serializable if the specified map is
* serializable.
*
* @param map the backing map for the returned multimap view
*/
public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) {
return new MapMultimap<K, V>(map);
}
/** @see Multimaps#forMap */
private static class MapMultimap<K, V>
implements SetMultimap<K, V>, Serializable {
final Map<K, V> map;
transient Map<K, Collection<V>> asMap;
MapMultimap(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public boolean containsEntry(Object key, Object value) {
return map.entrySet().contains(Maps.immutableEntry(key, value));
}
@Override
public Set<V> get(final K key) {
return new 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() {
checkState(i == 1);
i = -1;
map.remove(key);
}
};
}
@Override public int size() {
return map.containsKey(key) ? 1 : 0;
}
};
}
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object key, Object value) {
return map.entrySet().remove(Maps.immutableEntry(key, value));
}
@Override
public Set<V> removeAll(Object key) {
Set<V> values = new HashSet<V>(2);
if (!map.containsKey(key)) {
return values;
}
values.add(map.remove(key));
return values;
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<K> keySet() {
return map.keySet();
}
@Override
public Multiset<K> keys() {
return Multisets.forSet(map.keySet());
}
@Override
public Collection<V> values() {
return map.values();
}
@Override
public Set<Entry<K, V>> entries() {
return map.entrySet();
}
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
if (result == null) {
asMap = result = new AsMap();
}
return result;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return this.size() == that.size() && asMap().equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
private static final MapJoiner JOINER
= Joiner.on("], ").withKeyValueSeparator("=[").useForNull("null");
@Override public String toString() {
if (map.isEmpty()) {
return "{}";
}
StringBuilder builder
= Collections2.newStringBuilderForCollection(map.size()).append('{');
JOINER.appendTo(builder, map);
return builder.append("]}").toString();
}
/** @see MapMultimap#asMap */
class AsMapEntries extends Sets.ImprovedAbstractSet<Entry<K, Collection<V>>> {
@Override public int size() {
return map.size();
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return new TransformedIterator<K, Entry<K, Collection<V>>>(map.keySet().iterator()) {
@Override
Entry<K, Collection<V>> transform(final K key) {
return new AbstractMapEntry<K, Collection<V>>() {
@Override
public K getKey() {
return key;
}
@Override
public Collection<V> getValue() {
return get(key);
}
};
}
};
}
@Override public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
if (!(entry.getValue() instanceof Set)) {
return false;
}
Set<?> set = (Set<?>) entry.getValue();
return (set.size() == 1)
&& containsEntry(entry.getKey(), set.iterator().next());
}
@Override public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
if (!(entry.getValue() instanceof Set)) {
return false;
}
Set<?> set = (Set<?>) entry.getValue();
return (set.size() == 1)
&& map.entrySet().remove(
Maps.immutableEntry(entry.getKey(), set.iterator().next()));
}
}
/** @see MapMultimap#asMap */
class AsMap extends Maps.ImprovedAbstractMap<K, Collection<V>> {
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new AsMapEntries();
}
// The following methods are included for performance.
@Override public boolean containsKey(Object key) {
return map.containsKey(key);
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
Collection<V> collection = MapMultimap.this.get((K) key);
return collection.isEmpty() ? null : collection;
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = removeAll(key);
return collection.isEmpty() ? null : collection;
}
}
private static final long serialVersionUID = 7845222491160860175L;
}
/**
* Returns a view of a multimap where each value is transformed by a function.
* All other properties of the multimap, such as iteration order, are left
* intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
* Function<Integer, String> square = new Function<Integer, String>() {
* public String apply(Integer in) {
* return Integer.toString(in * in);
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformValues(multimap, square);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[4, 16], b=[9, 9], c=[6]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
public static <K, V1, V2> Multimap<K, V2> transformValues(
Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a multimap whose values are derived from the original
* multimap's entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* SetMultimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return (value >= 0) ? key : "no" + key;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[a, a], b=[nob]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
public static <K, V1, V2> Multimap<K, V2> transformEntries(
Multimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesMultimap<K, V1, V2>(fromMap, transformer);
}
private static class TransformedEntriesMultimap<K, V1, V2>
implements Multimap<K, V2> {
final Multimap<K, V1> fromMultimap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMultimap(Multimap<K, V1> fromMultimap,
final EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMultimap = checkNotNull(fromMultimap);
this.transformer = checkNotNull(transformer);
}
Collection<V2> transform(final K key, Collection<V1> values) {
return Collections2.transform(values, new Function<V1, V2>() {
@Override public V2 apply(V1 value) {
return transformer.transformEntry(key, value);
}
});
}
private transient Map<K, Collection<V2>> asMap;
@Override public Map<K, Collection<V2>> asMap() {
if (asMap == null) {
Map<K, Collection<V2>> aM = Maps.transformEntries(fromMultimap.asMap(),
new EntryTransformer<K, Collection<V1>, Collection<V2>>() {
@Override public Collection<V2> transformEntry(
K key, Collection<V1> value) {
return transform(key, value);
}
});
asMap = aM;
return aM;
}
return asMap;
}
@Override public void clear() {
fromMultimap.clear();
}
@SuppressWarnings("unchecked")
@Override public boolean containsEntry(Object key, Object value) {
Collection<V2> values = get((K) key);
return values.contains(value);
}
@Override public boolean containsKey(Object key) {
return fromMultimap.containsKey(key);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
private transient Collection<Entry<K, V2>> entries;
@Override public Collection<Entry<K, V2>> entries() {
if (entries == null) {
Collection<Entry<K, V2>> es = new TransformedEntries(transformer);
entries = es;
return es;
}
return entries;
}
private class TransformedEntries
extends TransformedCollection<Entry<K, V1>, Entry<K, V2>> {
TransformedEntries(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap.entries(),
new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override public Entry<K, V2> apply(final Entry<K, V1> entry) {
return new AbstractMapEntry<K, V2>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V2 getValue() {
return transformer.transformEntry(
entry.getKey(), entry.getValue());
}
};
}
});
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Collection<V2> values = get((K) entry.getKey());
return values.remove(entry.getValue());
}
return false;
}
}
@Override public Collection<V2> get(final K key) {
return transform(key, fromMultimap.get(key));
}
@Override public boolean isEmpty() {
return fromMultimap.isEmpty();
}
@Override public Set<K> keySet() {
return fromMultimap.keySet();
}
@Override public Multiset<K> keys() {
return fromMultimap.keys();
}
@Override public boolean put(K key, V2 value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(
Multimap<? extends K, ? extends V2> multimap) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object key, Object value) {
return get((K) key).remove(value);
}
@SuppressWarnings("unchecked")
@Override public Collection<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public Collection<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public int size() {
return fromMultimap.size();
}
private transient Collection<V2> values;
@Override public Collection<V2> values() {
if (values == null) {
Collection<V2> vs = Collections2.transform(
fromMultimap.entries(), new Function<Entry<K, V1>, V2>() {
@Override public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(
entry.getKey(), entry.getValue());
}
});
values = vs;
return vs;
}
return values;
}
@Override public boolean equals(Object obj) {
if (obj instanceof Multimap) {
Multimap<?, ?> other = (Multimap<?, ?>) obj;
return asMap().equals(other.asMap());
}
return false;
}
@Override public int hashCode() {
return asMap().hashCode();
}
@Override public String toString() {
return asMap().toString();
}
}
/**
* Returns a view of a {@code ListMultimap} where each value is transformed by
* a function. All other properties of the multimap, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* ListMultimap<String, Integer> multimap
* = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* ListMultimap<String, Double> transformed = Multimaps.transformValues(map,
* sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[2.0, 4.0], b=[3.0]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
public static <K, V1, V2> ListMultimap<K, V2> transformValues(
ListMultimap<K, V1> fromMultimap,
final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a {@code ListMultimap} whose values are derived from the
* original multimap's entries. In contrast to
* {@link #transformValues(ListMultimap, Function)}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return key + value;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
public static <K, V1, V2> ListMultimap<K, V2> transformEntries(
ListMultimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesListMultimap<K, V1, V2>(fromMap, transformer);
}
private static final class TransformedEntriesListMultimap<K, V1, V2>
extends TransformedEntriesMultimap<K, V1, V2>
implements ListMultimap<K, V2> {
TransformedEntriesListMultimap(ListMultimap<K, V1> fromMultimap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap, transformer);
}
@Override List<V2> transform(final K key, Collection<V1> values) {
return Lists.transform((List<V1>) values, new Function<V1, V2>() {
@Override public V2 apply(V1 value) {
return transformer.transformEntry(key, value);
}
});
}
@Override public List<V2> get(K key) {
return transform(key, fromMultimap.get(key));
}
@SuppressWarnings("unchecked")
@Override public List<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public List<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterable} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterable. The key used
* to store that value in the multimap will be the result of calling the
* function on that value. The resulting multimap is created as an immutable
* snapshot. In the returned multimap, keys appear in the order they are first
* encountered, and the values corresponding to each key appear in the same
* order as they are encountered.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys, stringLengthFunction);
* System.out.println(index);}</pre>
*
* prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterable<V> values, Function<? super V, K> keyFunction) {
return index(values.iterator(), keyFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterator} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterator. The key used
* to store that value in the multimap will be the result of calling the
* function on that value. The resulting multimap is created as an immutable
* snapshot. In the returned multimap, keys appear in the order they are first
* encountered, and the values corresponding to each key appear in the same
* order as they are encountered.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys.iterator(), stringLengthFunction);
* System.out.println(index);}</pre>
*
* prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
* @since 10.0
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
while (values.hasNext()) {
V value = values.next();
checkNotNull(value, values);
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
static abstract class Keys<K, V> extends AbstractMultiset<K> {
abstract Multimap<K, V> multimap();
@Override Iterator<Multiset.Entry<K>> entryIterator() {
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) {
try {
if (multimap().containsKey(element)) {
Collection<V> values = multimap().asMap().get(element);
return (values == null) ? 0 : values.size();
}
return 0;
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
@Override public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0);
if (occurrences == 0) {
return count(element);
}
Collection<V> values;
try {
values = multimap().asMap().get(element);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
if (values == null) {
return 0;
}
int oldCount = values.size();
if (occurrences >= oldCount) {
values.clear();
} else {
Iterator<V> iterator = values.iterator();
for (int i = 0; i < occurrences; i++) {
iterator.next();
iterator.remove();
}
}
return oldCount;
}
@Override public void clear() {
multimap().clear();
}
@Override public Set<K> elementSet() {
return multimap().keySet();
}
}
static abstract class Values<K, V> extends AbstractCollection<V> {
abstract Multimap<K, V> multimap();
@Override public Iterator<V> iterator() {
return Maps.valueIterator(multimap().entries().iterator());
}
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
return multimap().containsValue(o);
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link Multimap#entries()}.
*/
static abstract class Entries<K, V> extends
AbstractCollection<Map.Entry<K, V>> {
abstract Multimap<K, V> multimap();
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link SetMultimap#entries()}.
*/
static abstract class EntrySet<K, V> extends Entries<K, V> implements
Set<Map.Entry<K, V>> {
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override public boolean equals(@Nullable Object obj) {
return Sets.equalsImpl(this, obj);
}
}
/**
* A skeleton implementation of {@link Multimap#asMap()}.
*/
static abstract class AsMap<K, V> extends
Maps.ImprovedAbstractMap<K, Collection<V>> {
abstract Multimap<K, V> multimap();
@Override public abstract int size();
abstract Iterator<Entry<K, Collection<V>>> entryIterator();
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new EntrySet();
}
void removeValuesForKey(Object key){
multimap().removeAll(key);
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return entryIterator();
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
return containsKey(key) ? multimap().get((K) key) : null;
}
@Override public Collection<V> remove(Object key) {
return containsKey(key) ? multimap().removeAll(key) : null;
}
@Override public Set<K> keySet() {
return multimap().keySet();
}
@Override public boolean isEmpty() {
return multimap().isEmpty();
}
@Override public boolean containsKey(Object key) {
return multimap().containsKey(key);
}
@Override public void clear() {
multimap().clear();
}
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@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
*/
@GwtIncompatible(value = "untested")
public static <K, V> Multimap<K, V> filterKeys(
Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a value that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@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
*/
@GwtIncompatible(value = "untested")
public static <K, V> Multimap<K, V> filterValues(
Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key/value pair that doesn't satisfy the predicate,
* multimap's {@code put()}, {@code putAll()}, and {@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
*/
@GwtIncompatible(value = "untested")
public static <K, V> Multimap<K, V> filterEntries(
Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredMultimap)
? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate)
: new FilteredMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Support removal operations when filtering a filtered multimap. Since a
* filtered multimap has iterators that don't support remove, passing one to
* the FilteredMultimap constructor would lead to a multimap whose removal
* operations would fail. This method combines the predicates to avoid that
* problem.
*/
private static <K, V> Multimap<K, V> filterFiltered(FilteredMultimap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredMultimap<K, V>(map.unfiltered, predicate);
}
private static class FilteredMultimap<K, V> implements Multimap<K, V> {
final Multimap<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
FilteredMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override public int size() {
return entries().size();
}
@Override public boolean isEmpty() {
return entries().isEmpty();
}
@Override public boolean containsKey(Object key) {
return asMap().containsKey(key);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
// This method should be called only when key is a K and value is a V.
@SuppressWarnings("unchecked")
boolean satisfiesPredicate(Object key, Object value) {
return predicate.apply(Maps.immutableEntry((K) key, (V) value));
}
@Override public boolean containsEntry(Object key, Object value) {
return unfiltered.containsEntry(key, value) && satisfiesPredicate(key, value);
}
@Override public boolean put(K key, V value) {
checkArgument(satisfiesPredicate(key, value));
return unfiltered.put(key, value);
}
@Override public boolean remove(Object key, Object value) {
return containsEntry(key, value) ? unfiltered.remove(key, value) : false;
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
for (V value : values) {
checkArgument(satisfiesPredicate(key, value));
}
return unfiltered.putAll(key, values);
}
@Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
checkArgument(satisfiesPredicate(entry.getKey(), entry.getValue()));
}
return unfiltered.putAll(multimap);
}
@Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
for (V value : values) {
checkArgument(satisfiesPredicate(key, value));
}
// Not calling unfiltered.replaceValues() since values that don't satisify
// the filter should remain in the multimap.
Collection<V> oldValues = removeAll(key);
unfiltered.putAll(key, values);
return oldValues;
}
@Override public Collection<V> removeAll(Object key) {
List<V> removed = Lists.newArrayList();
Collection<V> values = unfiltered.asMap().get(key);
if (values != null) {
Iterator<V> iterator = values.iterator();
while (iterator.hasNext()) {
V value = iterator.next();
if (satisfiesPredicate(key, value)) {
removed.add(value);
iterator.remove();
}
}
}
if (unfiltered instanceof SetMultimap) {
return Collections.unmodifiableSet(Sets.newLinkedHashSet(removed));
} else {
return Collections.unmodifiableList(removed);
}
}
@Override public void clear() {
entries().clear();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return asMap().equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return asMap().hashCode();
}
@Override public String toString() {
return asMap().toString();
}
class ValuePredicate implements Predicate<V> {
final K key;
ValuePredicate(K key) {
this.key = key;
}
@Override public boolean apply(V value) {
return satisfiesPredicate(key, value);
}
}
Collection<V> filterCollection(Collection<V> collection, Predicate<V> predicate) {
if (collection instanceof Set) {
return Sets.filter((Set<V>) collection, predicate);
} else {
return Collections2.filter(collection, predicate);
}
}
@Override public Collection<V> get(K key) {
return filterCollection(unfiltered.get(key), new ValuePredicate(key));
}
@Override public Set<K> keySet() {
return asMap().keySet();
}
Collection<V> values;
@Override public Collection<V> values() {
return (values == null) ? values = new Values() : values;
}
class Values extends Multimaps.Values<K, V> {
@Override Multimap<K, V> multimap() {
return FilteredMultimap.this;
}
@Override public boolean contains(@Nullable Object o) {
return Iterators.contains(iterator(), o);
}
// Override remove methods since iterator doesn't support remove.
@Override public boolean remove(Object o) {
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (c.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!c.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
}
Collection<Entry<K, V>> entries;
@Override public Collection<Entry<K, V>> entries() {
return (entries == null)
? entries = Collections2.filter(unfiltered.entries(), predicate)
: entries;
}
/**
* Remove all filtered asMap() entries that satisfy the predicate.
*/
boolean removeEntriesIf(Predicate<Map.Entry<K, Collection<V>>> removalPredicate) {
Iterator<Map.Entry<K, Collection<V>>> iterator = unfiltered.asMap().entrySet().iterator();
boolean changed = false;
while (iterator.hasNext()) {
// Determine whether to remove the filtered values with this key.
Map.Entry<K, Collection<V>> entry = iterator.next();
K key = entry.getKey();
Collection<V> collection = entry.getValue();
Predicate<V> valuePredicate = new ValuePredicate(key);
Collection<V> filteredCollection = filterCollection(collection, valuePredicate);
Map.Entry<K, Collection<V>> filteredEntry = Maps.immutableEntry(key, filteredCollection);
if (removalPredicate.apply(filteredEntry) && !filteredCollection.isEmpty()) {
changed = true;
if (Iterables.all(collection, valuePredicate)) {
iterator.remove(); // Remove all values for the key.
} else {
filteredCollection.clear(); // Remove the filtered values only.
}
}
}
return changed;
}
Map<K, Collection<V>> asMap;
@Override public Map<K, Collection<V>> asMap() {
return (asMap == null) ? asMap = createAsMap() : asMap;
}
static final Predicate<Collection<?>> NOT_EMPTY = new Predicate<Collection<?>>() {
@Override public boolean apply(Collection<?> input) {
return !input.isEmpty();
}
};
Map<K, Collection<V>> createAsMap() {
// Select the values that satisify the predicate.
EntryTransformer<K, Collection<V>, Collection<V>> transformer
= new EntryTransformer<K, Collection<V>, Collection<V>>() {
@Override public Collection<V> transformEntry(K key, Collection<V> collection) {
return filterCollection(collection, new ValuePredicate(key));
}
};
Map<K, Collection<V>> transformed
= Maps.transformEntries(unfiltered.asMap(), transformer);
// Select the keys that have at least one value remaining.
Map<K, Collection<V>> filtered = Maps.filterValues(transformed, NOT_EMPTY);
// Override the removal methods, since removing a map entry should not
// affect values that don't satisfy the filter.
return new AsMap(filtered);
}
class AsMap extends ForwardingMap<K, Collection<V>> {
final Map<K, Collection<V>> delegate;
AsMap(Map<K, Collection<V>> delegate) {
this.delegate = delegate;
}
@Override protected Map<K, Collection<V>> delegate() {
return delegate;
}
@Override public Collection<V> remove(Object o) {
Collection<V> output = FilteredMultimap.this.removeAll(o);
return output.isEmpty() ? null : output;
}
@Override public void clear() {
FilteredMultimap.this.clear();
}
Set<K> keySet;
@Override public Set<K> keySet() {
return (keySet == null) ? keySet = new KeySet() : keySet;
}
class KeySet extends Maps.KeySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public boolean remove(Object o) {
Collection<V> collection = delegate.get(o);
if (collection == null) {
return false;
}
collection.clear();
return true;
}
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c.iterator());
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry.getKey());
}
};
return removeEntriesIf(removalPredicate);
}
}
Values asMapValues;
@Override public Collection<Collection<V>> values() {
return (asMapValues == null) ? asMapValues = new Values() : asMapValues;
}
class Values extends Maps.Values<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public boolean remove(Object o) {
for (Collection<V> collection : this) {
if (collection.equals(o)) {
collection.clear();
return true;
}
}
return false;
}
@Override public boolean removeAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return c.contains(entry.getValue());
}
};
return removeEntriesIf(removalPredicate);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry.getValue());
}
};
return removeEntriesIf(removalPredicate);
}
}
EntrySet entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
return (entrySet == null) ? entrySet = new EntrySet(super.entrySet()) : entrySet;
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
Set<Map.Entry<K, Collection<V>>> delegateEntries;
public EntrySet(Set<Map.Entry<K, Collection<V>>> delegateEntries) {
this.delegateEntries = delegateEntries;
}
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return delegateEntries.iterator();
}
@Override public boolean remove(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Collection<V> collection = delegate.get(entry.getKey());
if (collection != null && collection.equals(entry.getValue())) {
collection.clear();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry);
}
};
return removeEntriesIf(removalPredicate);
}
}
}
AbstractMultiset<K> keys;
@Override public Multiset<K> keys() {
return (keys == null) ? keys = new Keys() : keys;
}
class Keys extends Multimaps.Keys<K, V> {
@Override Multimap<K, V> multimap() {
return FilteredMultimap.this;
}
@Override public int remove(Object o, int occurrences) {
checkArgument(occurrences >= 0);
Collection<V> values = unfiltered.asMap().get(o);
if (values == null) {
return 0;
}
int priorCount = 0;
int removed = 0;
Iterator<V> iterator = values.iterator();
while (iterator.hasNext()) {
if (satisfiesPredicate(o, iterator.next())) {
priorCount++;
if (removed < occurrences) {
iterator.remove();
removed++;
}
}
}
return priorCount;
}
@Override Set<Multiset.Entry<K>> createEntrySet() {
return new EntrySet();
}
class EntrySet extends Multimaps.Keys<K, V>.KeysEntrySet {
@Override
public boolean removeAll(final Collection<?> c) {
return Sets.removeAllImpl(this, c.iterator());
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
Multiset.Entry<K> multisetEntry
= Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
return !c.contains(multisetEntry);
}
};
return removeEntriesIf(removalPredicate);
}
}
}
}
// TODO(jlevy): Create methods that filter a SetMultimap or SortedSetMultimap.
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An empty immutable map.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
final class EmptyImmutableMap extends ImmutableMap<Object, Object> {
static final EmptyImmutableMap INSTANCE = new EmptyImmutableMap();
private EmptyImmutableMap() {}
@Override public Object get(@Nullable Object key) {
return null;
}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean containsKey(@Nullable Object key) {
return false;
}
@Override public boolean containsValue(@Nullable Object value) {
return false;
}
@Override ImmutableSet<Entry<Object, Object>> createEntrySet() {
throw new AssertionError("should never be called");
}
@Override public ImmutableSet<Entry<Object, Object>> entrySet() {
return ImmutableSet.of();
}
@Override public ImmutableSet<Object> keySet() {
return ImmutableSet.of();
}
@Override public ImmutableCollection<Object> values() {
return ImmutableCollection.EMPTY_IMMUTABLE_COLLECTION;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Map) {
Map<?, ?> that = (Map<?, ?>) object;
return that.isEmpty();
}
return false;
}
@Override boolean isPartialView() {
return false;
}
@Override public int hashCode() {
return 0;
}
@Override public String toString() {
return "{}";
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 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;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.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;
}
/**
* Returns an array containing all of the elements in the specified
* collection. This method returns the elements in the order they are returned
* by the collection's iterator. The returned array is "safe" in that no
* references to it are maintained by the collection. The caller is thus free
* to modify the returned array.
*
* <p>This method assumes that the collection size doesn't change while the
* method is running.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
*/
static Object[] toArrayImpl(Collection<?> c) {
return fillArray(c, new Object[c.size()]);
}
private static Object[] fillArray(Iterable<?> elements, Object[] array) {
int i = 0;
for (Object element : elements) {
array[i++] = element;
}
return array;
}
/**
* Swaps {@code array[i]} with {@code array[j]}.
*/
static void swap(Object[] array, int i, int j) {
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// 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;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.MapMaker.RemovalListener;
import com.google.common.collect.MapMaker.RemovalNotification;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* A class exactly like {@link MapMaker}, except restricted in the types of maps it can build.
* For the most part, you should probably just ignore the existence of this class.
*
* @param <K0> the base type for all key types of maps built by this map maker
* @param <V0> the base type for all value types of maps built by this map maker
* @author Kevin Bourrillion
* @since 7.0
*/
@Beta
@GwtCompatible(emulated = true)
public abstract class GenericMapMaker<K0, V0> {
@GwtIncompatible("To be supported")
enum NullListener implements RemovalListener<Object, Object> {
INSTANCE;
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {}
}
// Set by MapMaker, but sits in this class to preserve the type relationship
@GwtIncompatible("To be supported")
RemovalListener<K0, V0> removalListener;
// No subclasses but our own
GenericMapMaker() {}
/**
* See {@link MapMaker#keyEquivalence}.
*/
@GwtIncompatible("To be supported")
abstract GenericMapMaker<K0, V0> keyEquivalence(Equivalence<Object> equivalence);
/**
* See {@link MapMaker#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#softKeys}.
*/
@Deprecated
@GwtIncompatible("java.lang.ref.SoftReference")
public abstract GenericMapMaker<K0, V0> softKeys();
/**
* See {@link MapMaker#weakValues}.
*/
@GwtIncompatible("java.lang.ref.WeakReference")
public abstract GenericMapMaker<K0, V0> weakValues();
/**
* See {@link MapMaker#softValues}.
*/
@GwtIncompatible("java.lang.ref.SoftReference")
public abstract GenericMapMaker<K0, V0> softValues();
/**
* See {@link MapMaker#expireAfterWrite}.
*/
abstract GenericMapMaker<K0, V0> expireAfterWrite(long duration, TimeUnit unit);
/**
* See {@link MapMaker#expireAfterAccess}.
*/
@GwtIncompatible("To be supported")
abstract GenericMapMaker<K0, V0> expireAfterAccess(long duration, TimeUnit unit);
/*
* Note that MapMaker's removalListener() is not here, because once you're interacting with a
* GenericMapMaker you've already called that, and shouldn't be calling it again.
*/
@SuppressWarnings("unchecked") // safe covariant cast
@GwtIncompatible("To be supported")
<K extends K0, V extends V0> RemovalListener<K, V> getRemovalListener() {
return (RemovalListener<K, V>) Objects.firstNonNull(removalListener, NullListener.INSTANCE);
}
/**
* See {@link MapMaker#makeMap}.
*/
public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeMap();
/**
* See {@link MapMaker#makeCustomMap}.
*/
@GwtIncompatible("MapMakerInternalMap")
abstract <K, V> MapMakerInternalMap<K, V> makeCustomMap();
/**
* See {@link MapMaker#makeComputingMap}.
*/
@Deprecated
public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction);
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableSet} with exactly one element.
*
* @author Kevin Bourrillion
* @author Nick Kralevich
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class SingletonImmutableSet<E> extends ImmutableSet<E> {
final transient E element;
// This is transient because it will be recalculated on the first
// call to hashCode().
//
// A race condition is avoided since threads will either see that the value
// is zero and recalculate it themselves, or two threads will see it at
// the same time, and both recalculate it. If the cachedHashCode is 0,
// it will always be recalculated, unfortunately.
private transient int cachedHashCode;
SingletonImmutableSet(E element) {
this.element = Preconditions.checkNotNull(element);
}
SingletonImmutableSet(E element, int hashCode) {
// Guaranteed to be non-null by the presence of the pre-computed hash code.
this.element = element;
cachedHashCode = hashCode;
}
@Override
public int size() {
return 1;
}
@Override public boolean isEmpty() {
return false;
}
@Override public boolean contains(Object target) {
return element.equals(target);
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.singletonIterator(element);
}
@Override boolean isPartialView() {
return false;
}
@Override public Object[] toArray() {
return new Object[] { element };
}
@Override public <T> T[] toArray(T[] array) {
if (array.length == 0) {
array = ObjectArrays.newArray(array, 1);
} else if (array.length > 1) {
array[1] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires.
Object[] objectArray = array;
objectArray[0] = element;
return array;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.size() == 1 && element.equals(that.iterator().next());
}
return false;
}
@Override public final int hashCode() {
// Racy single-check.
int code = cachedHashCode;
if (code == 0) {
cachedHashCode = code = element.hashCode();
}
return code;
}
@Override boolean isHashCodeFast() {
return cachedHashCode != 0;
}
@Override public String toString() {
String elementToString = element.toString();
return new StringBuilder(elementToString.length() + 2)
.append('[')
.append(elementToString)
.append(']')
.toString();
}
}
| Java |
/*
* Copyright (C) 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;
/**
* 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
*/
@Beta
@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();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* 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);
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.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
*/
@Beta 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
*/
@Beta protected int standardHashCode() {
return Sets.hashCodeImpl(this);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import 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();
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.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();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Multisets.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.primitives.Ints;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.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() {
int count = mapEntry.getValue().get();
if (count == 0) {
Count frequency = backingMap.get(getElement());
if (frequency != null) {
count = frequency.get();
}
}
return count;
}
};
}
@Override
public void remove() {
Iterators.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, AtomicInteger> entry, which can then be used for
* a more efficient remove() call.
*/
private class MapBasedMultisetIterator implements Iterator<E> {
final Iterator<Map.Entry<E, Count>> entryIterator;
Map.Entry<E, Count> currentEntry;
int occurrencesLeft;
boolean canRemove;
MapBasedMultisetIterator() {
this.entryIterator = backingMap.entrySet().iterator();
}
@Override
public boolean hasNext() {
return occurrencesLeft > 0 || entryIterator.hasNext();
}
@Override
public E next() {
if (occurrencesLeft == 0) {
currentEntry = entryIterator.next();
occurrencesLeft = currentEntry.getValue().get();
}
occurrencesLeft--;
canRemove = true;
return currentEntry.getKey();
}
@Override
public void remove() {
checkState(canRemove,
"no calls to next() since the last call to remove()");
int frequency = currentEntry.getValue().get();
if (frequency <= 0) {
throw new ConcurrentModificationException();
}
if (currentEntry.getValue().addAndGet(-1) == 0) {
entryIterator.remove();
}
size--;
canRemove = false;
}
}
@Override public int count(@Nullable Object element) {
try {
Count frequency = backingMap.get(element);
return (frequency == null) ? 0 : frequency.get();
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
// Optional Operations - Modification Operations
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the call would result in more than
* {@link Integer#MAX_VALUE} occurrences of {@code element} in this
* multiset.
*/
@Override public int add(@Nullable E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
int oldCount;
if (frequency == null) {
oldCount = 0;
backingMap.put(element, new Count(occurrences));
} else {
oldCount = frequency.get();
long newCount = (long) oldCount + (long) occurrences;
checkArgument(newCount <= Integer.MAX_VALUE,
"too many occurrences: %s", newCount);
frequency.getAndAdd(occurrences);
}
size += occurrences;
return oldCount;
}
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
if (frequency == null) {
return 0;
}
int oldCount = frequency.get();
int numberRemoved;
if (oldCount > occurrences) {
numberRemoved = occurrences;
} else {
numberRemoved = oldCount;
backingMap.remove(element);
}
frequency.addAndGet(-numberRemoved);
size -= numberRemoved;
return oldCount;
}
// Roughly a 33% performance improvement over AbstractMultiset.setCount().
@Override public int setCount(@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);
}
// Views
@Override Set<E> createElementSet() {
return new MapBasedElementSet();
}
class MapBasedElementSet extends Multisets.ElementSet<E> {
@Override
Multiset<E> multiset() {
return AbstractMapBasedMultiset.this;
}
}
// Don't allow default serialization.
@GwtIncompatible("java.io.ObjectStreamException")
@SuppressWarnings("unused") // actually used during deserialization
private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("Stream data required");
}
@GwtIncompatible("not needed in emulated source.")
private static final long serialVersionUID = -2250766705698539974L;
}
| Java |
/*
* Copyright (C) 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 AbstractMultimap} 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 AbstractMultimap<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();
// 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;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Comparator;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* 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
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class TreeMultimap<K, V> extends AbstractSortedSetMultimap<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);
}
/**
* Returns the comparator that orders the multimap keys.
*/
public Comparator<? super K> keyComparator() {
return keyComparator;
}
@Override
public Comparator<? super V> valueComparator() {
return valueComparator;
}
/**
* {@inheritDoc}
*
* <p>Because a {@code TreeMultimap} has unique sorted keys, this method
* returns a {@link SortedSet}, instead of the {@link java.util.Set} specified
* in the {@link Multimap} interface.
*/
@Override public SortedSet<K> keySet() {
return (SortedSet<K>) super.keySet();
}
/**
* {@inheritDoc}
*
* <p>Because a {@code TreeMultimap} has unique sorted keys, this method
* returns a {@link SortedMap}, instead of the {@link java.util.Map} specified
* in the {@link Multimap} interface.
*/
@Override public SortedMap<K, Collection<V>> asMap() {
return (SortedMap<K, Collection<V>>) super.asMap();
}
/**
* @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;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@code Multimap} that can hold duplicate key-value pairs and that maintains
* the insertion ordering of values for a given key. 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>Though the method signature doesn't say so explicitly, the returned map
* has {@link List} values.
*/
@Override
Map<K, Collection<V>> asMap();
/**
* Compares the specified object to this multimap for equality.
*
* <p>Two {@code ListMultimap} instances are equal if, for each key, they
* contain the same values in the same order. If the value orderings disagree,
* the multimaps will not be considered equal.
*
* <p>An empty {@code ListMultimap} is equal to any other empty {@code
* Multimap}, including an empty {@code SetMultimap}.
*/
@Override
boolean equals(@Nullable Object obj);
}
| Java |
/*
* Copyright (C) 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(Object object) {
if (object == this) {
return true;
}
if (object instanceof List) {
List<?> that = (List<?>) object;
return that.size() == 1 && element.equals(that.get(0));
}
return false;
}
@Override public int hashCode() {
// not caching hash code since it could change if the element is mutable
// in a way that modifies its hash code.
return 31 + element.hashCode();
}
@Override public String toString() {
String elementToString = element.toString();
return new StringBuilder(elementToString.length() + 2)
.append('[')
.append(elementToString)
.append(']')
.toString();
}
@Override public boolean isEmpty() {
return false;
}
@Override boolean isPartialView() {
return false;
}
@Override public Object[] toArray() {
return new Object[] { element };
}
@Override public <T> T[] toArray(T[] array) {
if (array.length == 0) {
array = ObjectArrays.newArray(array, 1);
} else if (array.length > 1) {
array[1] = null;
}
// Writes will produce ArrayStoreException when the toArray() doc requires.
Object[] objectArray = array;
objectArray[0] = element;
return array;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedSet;
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;
try {
return collection.contains(element);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
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);
}
}
/**
* 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) {
return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
}
/**
* Returns a string representation of {@code iterable}, with the format
* {@code [e1, e2, ..., en]}.
*/
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, 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);
}
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.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b) {
checkNotNull(a);
checkNotNull(b);
return concat(Arrays.asList(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.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
return concat(Arrays.asList(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.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c,
Iterable<? extends T> d) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
checkNotNull(d);
return concat(Arrays.asList(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> UnmodifiableIterator<Iterator<? extends T>> iterators(
Iterable<? extends Iterable<? extends T>> iterables) {
final Iterator<? extends Iterable<? extends T>> iterableIterator =
iterables.iterator();
return new UnmodifiableIterator<Iterator<? extends T>>() {
@Override
public boolean hasNext() {
return iterableIterator.hasNext();
}
@Override
public Iterator<? extends T> next() {
return iterableIterator.next().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);
if (iterable instanceof List) {
return ((List<T>) iterable).get(position);
}
if (iterable instanceof Collection) {
// Can check both ends
Collection<T> collection = (Collection<T>) iterable;
Preconditions.checkElementIndex(position, collection.size());
} else {
// Can only check the lower end
checkNonnegativeIndex(position);
}
return Iterators.get(iterable.iterator(), position);
}
private static void checkNonnegativeIndex(int position) {
if (position < 0) {
throw new IndexOutOfBoundsException(
"position cannot be negative: " + 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);
checkNonnegativeIndex(position);
try {
return get(iterable, position);
} catch (IndexOutOfBoundsException e) {
return 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}.
*
* @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);
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<T> sortedSet = (SortedSet<T>) iterable;
return sortedSet.last();
}
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> collection = Collections2.cast(iterable);
if (collection.isEmpty()) {
return defaultValue;
}
}
if (iterable instanceof List) {
List<? extends T> list = Lists.cast(iterable);
return getLastInNonemptyList(list);
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<? extends T> sortedSet = Sets.cast(iterable);
return sortedSet.last();
}
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?
return (numberToSkip >= list.size())
? Iterators.<T>emptyIterator()
: list.subList(numberToSkip, 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() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return iterator.next();
} finally {
atStart = false;
}
}
@Override
public void remove() {
if (atStart) {
throw new IllegalStateException();
}
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 iterator 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 iterator
* @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);
}
};
}
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.consumingIterator(iterable.iterator());
}
};
}
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();
}
};
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset.Entry;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
/**
* Provides static utility methods for creating and working with
* {@link SortedMultiset} instances.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class SortedMultisets {
private SortedMultisets() {
}
/**
* A skeleton implementation for {@link SortedMultiset#elementSet}.
*/
static abstract class ElementSet<E> extends Multisets.ElementSet<E> implements
SortedSet<E> {
@Override abstract SortedMultiset<E> multiset();
@Override public Comparator<? super E> comparator() {
return multiset().comparator();
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return multiset().subMultiset(fromElement, BoundType.CLOSED, toElement,
BoundType.OPEN).elementSet();
}
@Override public SortedSet<E> headSet(E toElement) {
return multiset().headMultiset(toElement, BoundType.OPEN).elementSet();
}
@Override public SortedSet<E> tailSet(E fromElement) {
return multiset().tailMultiset(fromElement, BoundType.CLOSED)
.elementSet();
}
@Override public E first() {
return getElementOrThrow(multiset().firstEntry());
}
@Override public E last() {
return getElementOrThrow(multiset().lastEntry());
}
}
private static <E> E getElementOrThrow(Entry<E> entry) {
if (entry == null) {
throw new NoSuchElementException();
}
return entry.getElement();
}
/**
* A skeleton implementation of a descending multiset. Only needs
* {@code forwardMultiset()} and {@code entryIterator()}.
*/
static abstract class DescendingMultiset<E> extends ForwardingMultiset<E>
implements SortedMultiset<E> {
abstract SortedMultiset<E> forwardMultiset();
private transient Comparator<? super E> comparator;
@Override public Comparator<? super E> comparator() {
Comparator<? super E> result = comparator;
if (result == null) {
return comparator =
Ordering.from(forwardMultiset().comparator()).<E>reverse();
}
return result;
}
private transient SortedSet<E> elementSet;
@Override public SortedSet<E> elementSet() {
SortedSet<E> result = elementSet;
if (result == null) {
return elementSet = new SortedMultisets.ElementSet<E>() {
@Override SortedMultiset<E> multiset() {
return DescendingMultiset.this;
}
};
}
return result;
}
@Override public Entry<E> pollFirstEntry() {
return forwardMultiset().pollLastEntry();
}
@Override public Entry<E> pollLastEntry() {
return forwardMultiset().pollFirstEntry();
}
@Override public SortedMultiset<E> headMultiset(E toElement,
BoundType boundType) {
return forwardMultiset().tailMultiset(toElement, boundType)
.descendingMultiset();
}
@Override public SortedMultiset<E> subMultiset(E fromElement,
BoundType fromBoundType, E toElement, BoundType toBoundType) {
return forwardMultiset().subMultiset(toElement, toBoundType, fromElement,
fromBoundType).descendingMultiset();
}
@Override public SortedMultiset<E> tailMultiset(E fromElement,
BoundType boundType) {
return forwardMultiset().headMultiset(fromElement, boundType)
.descendingMultiset();
}
@Override protected Multiset<E> delegate() {
return forwardMultiset();
}
@Override public SortedMultiset<E> descendingMultiset() {
return forwardMultiset();
}
@Override public Entry<E> firstEntry() {
return forwardMultiset().lastEntry();
}
@Override public Entry<E> lastEntry() {
return forwardMultiset().firstEntry();
}
abstract Iterator<Entry<E>> entryIterator();
private transient Set<Entry<E>> entrySet;
@Override public Set<Entry<E>> entrySet() {
Set<Entry<E>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
Set<Entry<E>> createEntrySet() {
return new Multisets.EntrySet<E>() {
@Override Multiset<E> multiset() {
return DescendingMultiset.this;
}
@Override public Iterator<Entry<E>> iterator() {
return entryIterator();
}
@Override public int size() {
return forwardMultiset().entrySet().size();
}
};
}
@Override public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public String toString() {
return entrySet().toString();
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import 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 public Object[] toArray() {
return ObjectArrays.EMPTY_ARRAY;
}
@Override public <T> T[] toArray(T[] a) {
return asList().toArray(a);
}
@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;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.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 {
private final K key;
private final V value;
ImmutableEntry(@Nullable K key, @Nullable V value) {
this.key = key;
this.value = value;
}
@Nullable @Override public K getKey() {
return key;
}
@Nullable @Override public V getValue() {
return value;
}
@Override public final V setValue(V value){
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.Nullable;
/** An ordering that treats {@code null} as greater than all other values. */
@GwtCompatible(serializable = true)
final class NullsLastOrdering<T> extends Ordering<T> implements Serializable {
final Ordering<? super T> ordering;
NullsLastOrdering(Ordering<? super T> ordering) {
this.ordering = ordering;
}
@Override public int compare(@Nullable T left, @Nullable T right) {
if (left == right) {
return 0;
}
if (left == null) {
return LEFT_IS_GREATER;
}
if (right == null) {
return RIGHT_IS_GREATER;
}
return ordering.compare(left, right);
}
@Override public <S extends T> Ordering<S> reverse() {
// ordering.reverse() might be optimized, so let it do its thing
return ordering.reverse().nullsFirst();
}
@Override public <S extends T> Ordering<S> nullsFirst() {
return ordering.nullsFirst();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override public <S extends T> Ordering<S> nullsLast() {
return (Ordering<S>) this;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof NullsLastOrdering) {
NullsLastOrdering<?> that = (NullsLastOrdering<?>) object;
return this.ordering.equals(that.ordering);
}
return false;
}
@Override public int hashCode() {
return ordering.hashCode() ^ -921210296; // meaningless
}
@Override public String toString() {
return ordering + ".nullsLast()";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Iterator;
/**
* An {@code ImmutableSet} whose elements are derived by transforming another collection's elements,
* useful for {@code ImmutableMap.keySet()}.
*
* @author Jesse Wilson
*/
@GwtCompatible(emulated = true)
abstract class TransformedImmutableSet<D, E> extends ImmutableSet<E> {
/*
* TODO(cpovirk): using an abstract source() method instead of a field could simplify
* ImmutableMapKeySet, which currently has to pass in entrySet() manually
*/
final ImmutableCollection<D> source;
final int hashCode;
TransformedImmutableSet(ImmutableCollection<D> source) {
this.source = source;
this.hashCode = Sets.hashCodeImpl(this);
}
TransformedImmutableSet(ImmutableCollection<D> source, int hashCode) {
this.source = source;
this.hashCode = hashCode;
}
abstract E transform(D element);
@Override
public int size() {
return source.size();
}
@Override public boolean isEmpty() {
return false;
}
@Override public UnmodifiableIterator<E> iterator() {
final Iterator<D> backingIterator = source.iterator();
return new UnmodifiableIterator<E>() {
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public E next() {
return transform(backingIterator.next());
}
};
}
@Override public Object[] toArray() {
return toArray(new Object[size()]);
}
@Override public <T> T[] toArray(T[] array) {
return ObjectArrays.toArrayImpl(this, array);
}
@Override public final int hashCode() {
return hashCode;
}
@GwtIncompatible("unused")
@Override boolean isHashCodeFast() {
return true;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;
import java.util.AbstractQueue;
import java.util.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() {
checkState(canRemove,
"no calls to remove() since the last call to next()");
checkModCount();
canRemove = false;
expectedModCount++;
if (cursor < size()) {
MoveDesc<E> moved = removeAt(cursor);
if (moved != null) {
if (forgetMeNot == null) {
forgetMeNot = new 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
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.unmodifiableList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
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.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>
*
* 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>
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> {
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 String toString() {
return key + "=" + value;
}
}
private transient Node<K, V> head; // the head for all keys
private transient Node<K, V> tail; // the tail for all keys
private transient Multiset<K> keyCount; // the number of values for each key
private transient Map<K, Node<K, V>> keyToKeyHead; // the head for a given key
private transient Map<K, Node<K, V>> keyToKeyTail; // the tail for a given key
/**
* 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() {
keyCount = LinkedHashMultiset.create();
keyToKeyHead = Maps.newHashMap();
keyToKeyTail = Maps.newHashMap();
}
private LinkedListMultimap(int expectedKeys) {
keyCount = LinkedHashMultiset.create(expectedKeys);
keyToKeyHead = Maps.newHashMapWithExpectedSize(expectedKeys);
keyToKeyTail = Maps.newHashMapWithExpectedSize(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;
keyToKeyHead.put(key, node);
keyToKeyTail.put(key, node);
} else if (nextSibling == null) { // non-empty list, add to tail
tail.next = node;
node.previous = tail;
Node<K, V> keyTail = keyToKeyTail.get(key);
if (keyTail == null) { // first for this key
keyToKeyHead.put(key, node);
} else {
keyTail.nextSibling = node;
node.previousSibling = keyTail;
}
keyToKeyTail.put(key, node);
tail = node;
} else { // non-empty list, insert before nextSibling
node.previous = nextSibling.previous;
node.previousSibling = nextSibling.previousSibling;
node.next = nextSibling;
node.nextSibling = nextSibling;
if (nextSibling.previousSibling == null) { // nextSibling was key head
keyToKeyHead.put(key, 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;
}
keyCount.add(key);
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.previousSibling.nextSibling = node.nextSibling;
} else if (node.nextSibling != null) { // node was key head
keyToKeyHead.put(node.key, node.nextSibling);
} else {
keyToKeyHead.remove(node.key); // don't leak a key-null entry
}
if (node.nextSibling != null) {
node.nextSibling.previousSibling = node.previousSibling;
} else if (node.previousSibling != null) { // node was key tail
keyToKeyTail.put(node.key, node.previousSibling);
} else {
keyToKeyTail.remove(node.key); // don't leak a key-null entry
}
keyCount.remove(node.key);
}
/** Removes all nodes for the specified key. */
private void removeAllNodes(@Nullable Object key) {
for (Iterator<V> i = new ValueForKeyIterator(key); i.hasNext();) {
i.next();
i.remove();
}
}
/** 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<Node<K, V>> {
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
NodeIterator() {
next = head;
}
NodeIterator(int index) {
int size = size();
Preconditions.checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = head;
while (index-- > 0) {
next();
}
}
current = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Node<K, V> next() {
checkElement(next);
previous = current = next;
next = next.next;
nextIndex++;
return current;
}
@Override
public void remove() {
checkState(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;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@Override
public Node<K, V> previous() {
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(Node<K, V> e) {
throw new UnsupportedOperationException();
}
@Override
public void add(Node<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;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public K next() {
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() {
checkState(current != null);
removeAllNodes(current.key);
current = null;
}
}
/** 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;
next = keyToKeyHead.get(key);
}
/**
* 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) {
int size = keyCount.count(key);
Preconditions.checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = keyToKeyTail.get(key);
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = keyToKeyHead.get(key);
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() {
checkState(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 keyCount.size();
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public boolean containsKey(@Nullable Object key) {
return keyToKeyHead.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Iterator<Node<K, V>> i = new NodeIterator(); i.hasNext();) {
if (Objects.equal(i.next().value, value)) {
return true;
}
}
return false;
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
for (Iterator<V> i = new ValueForKeyIterator(key); i.hasNext();) {
if (Objects.equal(i.next(), value)) {
return true;
}
}
return false;
}
// 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;
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
Iterator<V> values = new ValueForKeyIterator(key);
while (values.hasNext()) {
if (Objects.equal(values.next(), value)) {
values.remove();
return true;
}
}
return false;
}
// Bulk Operations
@Override
public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
boolean changed = false;
for (V value : values) {
changed |= put(key, value);
}
return changed;
}
@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;
}
/**
* {@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;
keyCount.clear();
keyToKeyHead.clear();
keyToKeyTail.clear();
}
// 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() {
return keyCount.count(key);
}
@Override public ListIterator<V> listIterator(int index) {
return new ValueForKeyIterator(key, index);
}
@Override public boolean removeAll(Collection<?> c) {
return Iterators.removeAll(iterator(), c);
}
@Override public boolean retainAll(Collection<?> c) {
return Iterators.retainAll(iterator(), c);
}
};
}
private transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
keySet = result = new Sets.ImprovedAbstractSet<K>() {
@Override public int size() {
return keyCount.elementSet().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();
}
};
}
return result;
}
private transient Multiset<K> keys;
@Override
public Multiset<K> keys() {
Multiset<K> result = keys;
if (result == null) {
keys = result = new MultisetView();
}
return result;
}
private class MultisetView extends AbstractMultiset<K> {
@Override
public int size() {
return keyCount.size();
}
@Override
public int count(Object element) {
return keyCount.count(element);
}
@Override
Iterator<Entry<K>> entryIterator() {
return new TransformedIterator<K, Entry<K>>(new DistinctKeyIterator()) {
@Override
Entry<K> transform(final K key) {
return new Multisets.AbstractEntry<K>() {
@Override
public K getElement() {
return key;
}
@Override
public int getCount() {
return keyCount.count(key);
}
};
}
};
}
@Override
int distinctElements() {
return elementSet().size();
}
@Override public Iterator<K> iterator() {
return new TransformedIterator<Node<K, V>, K>(new NodeIterator()) {
@Override
K transform(Node<K, V> node) {
return node.key;
}
};
}
@Override
public int remove(@Nullable Object key, int occurrences) {
checkArgument(occurrences >= 0);
int oldCount = count(key);
Iterator<V> values = new ValueForKeyIterator(key);
while ((occurrences-- > 0) && values.hasNext()) {
values.next();
values.remove();
}
return oldCount;
}
@Override
public Set<K> elementSet() {
return keySet();
}
@Override public boolean equals(@Nullable Object object) {
return keyCount.equals(object);
}
@Override public int hashCode() {
return keyCount.hashCode();
}
@Override public String toString() {
return keyCount.toString(); // XXX observe order?
}
}
private transient List<V> valuesList;
/**
* {@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() {
List<V> result = valuesList;
if (result == null) {
valuesList = result = new AbstractSequentialList<V>() {
@Override public int size() {
return keyCount.size();
}
@Override
public ListIterator<V> listIterator(int index) {
final NodeIterator nodes = new NodeIterator(index);
return new TransformedListIterator<Node<K, V>, V>(nodes) {
@Override
V transform(Node<K, V> node) {
return node.value;
}
@Override
public void set(V value) {
nodes.setValue(value);
}
};
}
};
}
return result;
}
private static <K, V> Entry<K, V> createEntry(final Node<K, V> node) {
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return node.key;
}
@Override public V getValue() {
return node.value;
}
@Override public V setValue(V value) {
V oldValue = node.value;
node.value = value;
return oldValue;
}
};
}
private transient List<Entry<K, V>> entries;
/**
* {@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() {
List<Entry<K, V>> result = entries;
if (result == null) {
entries = result = new AbstractSequentialList<Entry<K, V>>() {
@Override public int size() {
return keyCount.size();
}
@Override public ListIterator<Entry<K, V>> listIterator(int index) {
return new TransformedListIterator<Node<K, V>, Entry<K, V>>(new NodeIterator(index)) {
@Override
Entry<K, V> transform(Node<K, V> node) {
return createEntry(node);
}
};
}
};
}
return result;
}
private transient Map<K, Collection<V>> map;
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = map;
if (result == null) {
map = result = new Multimaps.AsMap<K, V>() {
@Override
public int size() {
return keyCount.elementSet().size();
}
@Override
Multimap<K, V> multimap() {
return LinkedListMultimap.this;
}
@Override
Iterator<Entry<K, Collection<V>>> entryIterator() {
return new TransformedIterator<K, Entry<K, Collection<V>>>(new DistinctKeyIterator()) {
@Override
Entry<K, Collection<V>> transform(final K key) {
return new AbstractMapEntry<K, Collection<V>>() {
@Override public K getKey() {
return key;
}
@Override public Collection<V> getValue() {
return LinkedListMultimap.this.get(key);
}
};
}
};
}
};
}
return result;
}
// Comparison and hashing
/**
* 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 other) {
if (other == this) {
return true;
}
if (other instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) other;
return this.asMap().equals(that.asMap());
}
return false;
}
/**
* Returns the hash code for this multimap.
*
* <p>The hash code of a multimap is defined as the hash code of the map view,
* as returned by {@link Multimap#asMap}.
*/
@Override public int hashCode() {
return asMap().hashCode();
}
/**
* Returns a string representation of the multimap, generated by calling
* {@code toString} on the map returned by {@link Multimap#asMap}.
*
* @return a string representation of the multimap
*/
@Override public String toString() {
return asMap().toString();
}
/**
* @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();
keyCount = LinkedHashMultiset.create();
keyToKeyHead = Maps.newHashMap();
keyToKeyTail = Maps.newHashMap();
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;
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import 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;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Implementation of {@link ImmutableMap} with two or more entries.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Gregory Kick
*/
@GwtCompatible(serializable = true, emulated = true)
final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// entries in insertion order
private final transient LinkedEntry<K, V>[] entries;
// array of linked lists of entries
private final transient LinkedEntry<K, V>[] table;
// 'and' with an int to get a table index
private final transient int mask;
private final transient int keySetHashCode;
// TODO(gak): investigate avoiding the creation of ImmutableEntries since we
// re-copy them anyway.
RegularImmutableMap(Entry<?, ?>... immutableEntries) {
int size = immutableEntries.length;
entries = createEntryArray(size);
int tableSize = chooseTableSize(size);
table = createEntryArray(tableSize);
mask = tableSize - 1;
int keySetHashCodeMutable = 0;
for (int entryIndex = 0; entryIndex < size; entryIndex++) {
// each of our 6 callers carefully put only Entry<K, V>s into the array!
@SuppressWarnings("unchecked")
Entry<K, V> entry = (Entry<K, V>) immutableEntries[entryIndex];
K key = entry.getKey();
int keyHashCode = key.hashCode();
keySetHashCodeMutable += keyHashCode;
int tableIndex = Hashing.smear(keyHashCode) & mask;
@Nullable LinkedEntry<K, V> existing = table[tableIndex];
// prepend, not append, so the entries can be immutable
LinkedEntry<K, V> linkedEntry =
newLinkedEntry(key, entry.getValue(), existing);
table[tableIndex] = linkedEntry;
entries[entryIndex] = linkedEntry;
while (existing != null) {
checkArgument(!key.equals(existing.getKey()), "duplicate key: %s", key);
existing = existing.next();
}
}
keySetHashCode = keySetHashCodeMutable;
}
/**
* 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;
/**
* Give a good hash table size for the given number of keys.
*
* @param size The number of keys to be inserted. Must be greater than or equal to 2.
*/
private static int chooseTableSize(int size) {
// Get the recommended table size.
// Round down to the nearest power of 2.
int tableSize = Integer.highestOneBit(size);
// Check to make sure that we will not exceed the maximum load factor.
if ((double) size / tableSize > MAX_LOAD_FACTOR) {
tableSize <<= 1;
checkArgument(tableSize > 0, "table too large: %s", size);
}
return tableSize;
}
/**
* Creates a {@link LinkedEntry} array to hold parameterized entries. The
* result must never be upcast back to LinkedEntry[] (or Object[], etc.), or
* allowed to escape the class.
*/
@SuppressWarnings("unchecked") // Safe as long as the javadocs are followed
private LinkedEntry<K, V>[] createEntryArray(int size) {
return new LinkedEntry[size];
}
private static <K, V> LinkedEntry<K, V> newLinkedEntry(K key, V value,
@Nullable LinkedEntry<K, V> next) {
return (next == null)
? new TerminalEntry<K, V>(key, value)
: new NonTerminalEntry<K, V>(key, value, next);
}
private interface LinkedEntry<K, V> extends Entry<K, V> {
/** Returns the next entry in the list or {@code null} if none exists. */
@Nullable LinkedEntry<K, V> next();
}
/** {@code LinkedEntry} implementation that has a next value. */
@Immutable
@SuppressWarnings("serial") // this class is never serialized
private static final class NonTerminalEntry<K, V>
extends ImmutableEntry<K, V> implements LinkedEntry<K, V> {
final LinkedEntry<K, V> next;
NonTerminalEntry(K key, V value, LinkedEntry<K, V> next) {
super(key, value);
this.next = next;
}
@Override public LinkedEntry<K, V> next() {
return next;
}
}
/**
* {@code LinkedEntry} implementation that serves as the last entry in the
* list. I.e. no next entry
*/
@Immutable
@SuppressWarnings("serial") // this class is never serialized
private static final class TerminalEntry<K, V> extends ImmutableEntry<K, V>
implements LinkedEntry<K, V> {
TerminalEntry(K key, V value) {
super(key, value);
}
@Nullable @Override public LinkedEntry<K, V> next() {
return null;
}
}
@Override public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int index = Hashing.smear(key.hashCode()) & mask;
for (LinkedEntry<K, V> entry = table[index];
entry != null;
entry = entry.next()) {
K candidateKey = entry.getKey();
/*
* Assume that equals uses the == optimization when appropriate, and that
* it would check hash codes as an optimization when appropriate. If we
* did these things, it would just make things worse for the most
* performance-conscious users.
*/
if (key.equals(candidateKey)) {
return entry.getValue();
}
}
return null;
}
@Override
public int size() {
return entries.length;
}
@Override public boolean isEmpty() {
return false;
}
@Override public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
for (Entry<K, V> entry : entries) {
if (entry.getValue().equals(value)) {
return true;
}
}
return false;
}
@Override boolean isPartialView() {
return false;
}
@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);
}
}
@Override
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<K, V>(entrySet(), keySetHashCode) {
@Override ImmutableMap<K, V> map() {
return RegularImmutableMap.this;
}
};
}
@Override public String toString() {
StringBuilder result
= Collections2.newStringBuilderForCollection(size()).append('{');
Collections2.STANDARD_JOINER.appendTo(result, entries);
return result.append('}').toString();
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 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;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* An empty implementation of {@link ImmutableTable}.
*
* @author Gregory Kick
*/
@GwtCompatible
@Immutable
final class EmptyImmutableTable extends ImmutableTable<Object, Object, Object> {
static final EmptyImmutableTable INSTANCE = new EmptyImmutableTable();
private EmptyImmutableTable() {}
@Override public int size() {
return 0;
}
@Override public Object get(@Nullable Object rowKey,
@Nullable Object columnKey) {
return null;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Table) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
return that.isEmpty();
} else {
return false;
}
}
@Override public int hashCode() {
return 0;
}
@Override public ImmutableSet<Cell<Object, Object, Object>> cellSet() {
return ImmutableSet.of();
}
@Override public ImmutableMap<Object, Object> column(Object columnKey) {
checkNotNull(columnKey);
return ImmutableMap.of();
}
@Override public ImmutableSet<Object> columnKeySet() {
return ImmutableSet.of();
}
@Override public ImmutableMap<Object, Map<Object, Object>> columnMap() {
return ImmutableMap.of();
}
@Override public boolean contains(@Nullable Object rowKey,
@Nullable Object columnKey) {
return false;
}
@Override public boolean containsColumn(@Nullable Object columnKey) {
return false;
}
@Override public boolean containsRow(@Nullable Object rowKey) {
return false;
}
@Override public boolean containsValue(@Nullable Object value) {
return false;
}
@Override public ImmutableMap<Object, Object> row(Object rowKey) {
checkNotNull(rowKey);
return ImmutableMap.of();
}
@Override public ImmutableSet<Object> rowKeySet() {
return ImmutableSet.of();
}
@Override public ImmutableMap<Object, Map<Object, Object>> rowMap() {
return ImmutableMap.of();
}
@Override public String toString() {
return "{}";
}
@Override public ImmutableCollection<Object> values() {
return ImmutableSet.of();
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker.RemovalCause;
import com.google.common.collect.MapMaker.RemovalListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReferenceArray;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* Adds computing functionality to {@link MapMakerInternalMap}.
*
* @author Bob Lee
* @author Charles Fry
*/
class ComputingConcurrentHashMap<K, V> extends MapMakerInternalMap<K, V> {
final Function<? super K, ? extends V> computingFunction;
/**
* Creates a new, empty map with the specified strategy, initial capacity, load factor and
* concurrency level.
*/
ComputingConcurrentHashMap(MapMaker builder,
Function<? super K, ? extends V> computingFunction) {
super(builder);
this.computingFunction = checkNotNull(computingFunction);
}
@Override
Segment<K, V> createSegment(int initialCapacity, int maxSegmentSize) {
return new ComputingSegment<K, V>(this, initialCapacity, maxSegmentSize);
}
@Override
ComputingSegment<K, V> segmentFor(int hash) {
return (ComputingSegment<K, V>) super.segmentFor(hash);
}
V getOrCompute(K key) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).getOrCompute(key, hash, computingFunction);
}
@SuppressWarnings("serial") // This class is never serialized.
static final class ComputingSegment<K, V> extends Segment<K, V> {
ComputingSegment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) {
super(map, initialCapacity, maxSegmentSize);
}
V getOrCompute(K key, int hash, Function<? super K, ? extends V> computingFunction)
throws ExecutionException {
try {
outer: while (true) {
// don't call getLiveEntry, which would ignore computing values
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e != null) {
V value = getLiveValue(e);
if (value != null) {
recordRead(e);
return value;
}
}
// at this point e is either null, computing, or expired;
// avoid locking if it's already computing
if (e == null || !e.getValueReference().isComputingReference()) {
boolean createNewEntry = true;
ComputingValueReference<K, V> computingValueReference = null;
lock();
try {
preWriteCleanup();
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isComputingReference()) {
createNewEntry = false;
} else {
V value = e.getValueReference().get();
if (value == null) {
enqueueNotification(entryKey, hash, value, RemovalCause.COLLECTED);
} else if (map.expires() && map.isExpired(e)) {
// This is a duplicate check, as preWriteCleanup already purged expired
// entries, but let's accomodate an incorrect expiration queue.
enqueueNotification(entryKey, hash, value, RemovalCause.EXPIRED);
} else {
recordLockedRead(e);
return value;
}
// immediately reuse invalid entries
evictionQueue.remove(e);
expirationQueue.remove(e);
this.count = newCount; // write-volatile
}
break;
}
}
if (createNewEntry) {
computingValueReference = new ComputingValueReference<K, V>(computingFunction);
if (e == null) {
e = newEntry(key, hash, first);
e.setValueReference(computingValueReference);
table.set(index, e);
} else {
e.setValueReference(computingValueReference);
}
}
} finally {
unlock();
postWriteCleanup();
}
if (createNewEntry) {
// This thread solely created the entry.
return compute(key, hash, e, computingValueReference);
}
}
// The entry already exists. Wait for the computation.
checkState(!Thread.holdsLock(e), "Recursive computation");
// don't consider expiration as we're concurrent with computation
V value = e.getValueReference().waitForValue();
if (value != null) {
recordRead(e);
return value;
}
// else computing thread will clearValue
continue outer;
}
} finally {
postReadCleanup();
}
}
V compute(K key, int hash, ReferenceEntry<K, V> e,
ComputingValueReference<K, V> computingValueReference)
throws ExecutionException {
V value = null;
long start = System.nanoTime();
long end = 0;
try {
// Synchronizes on the entry to allow failing fast when a recursive computation is
// detected. This is not fool-proof since the entry may be copied when the segment
// is written to.
synchronized (e) {
value = computingValueReference.compute(key, hash);
end = System.nanoTime();
}
if (value != null) {
// putIfAbsent
V oldValue = put(key, hash, value, true);
if (oldValue != null) {
// the computed value was already clobbered
enqueueNotification(key, hash, value, RemovalCause.REPLACED);
}
}
return value;
} finally {
if (end == 0) {
end = System.nanoTime();
}
if (value == null) {
clearValue(key, hash, computingValueReference);
}
}
}
}
/**
* Used to provide computation exceptions to other threads.
*/
private static final class ComputationExceptionReference<K, V> implements ValueReference<K, V> {
final Throwable t;
ComputationExceptionReference(Throwable t) {
this.t = t;
}
@Override
public V get() {
return null;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() throws ExecutionException {
throw new ExecutionException(t);
}
@Override
public void clear(ValueReference<K, V> newValue) {}
}
/**
* Used to provide computation result to other threads.
*/
private static final class ComputedReference<K, V> implements ValueReference<K, V> {
final V value;
ComputedReference(@Nullable V value) {
this.value = value;
}
@Override
public V get() {
return value;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void clear(ValueReference<K, V> newValue) {}
}
private static final class ComputingValueReference<K, V> implements ValueReference<K, V> {
final Function<? super K, ? extends V> computingFunction;
@GuardedBy("ComputingValueReference.this") // writes
volatile ValueReference<K, V> computedReference = unset();
public ComputingValueReference(Function<? super K, ? extends V> computingFunction) {
this.computingFunction = computingFunction;
}
@Override
public V get() {
// All computation lookups go through waitForValue. This method thus is
// only used by put, to whom we always want to appear absent.
return null;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return true;
}
/**
* Waits for a computation to complete. Returns the result of the computation.
*/
@Override
public V waitForValue() throws ExecutionException {
if (computedReference == UNSET) {
boolean interrupted = false;
try {
synchronized (this) {
while (computedReference == UNSET) {
try {
wait();
} catch (InterruptedException ie) {
interrupted = true;
}
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
return computedReference.waitForValue();
}
@Override
public void clear(ValueReference<K, V> newValue) {
// The pending computation was clobbered by a manual write. Unblock all
// pending gets, and have them return the new value.
setValueReference(newValue);
// TODO(fry): could also cancel computation if we had a thread handle
}
V compute(K key, int hash) throws ExecutionException {
V value;
try {
value = computingFunction.apply(key);
} catch (Throwable t) {
setValueReference(new ComputationExceptionReference<K, V>(t));
throw new ExecutionException(t);
}
setValueReference(new ComputedReference<K, V>(value));
return value;
}
void setValueReference(ValueReference<K, V> valueReference) {
synchronized (this) {
if (computedReference == UNSET) {
computedReference = valueReference;
notifyAll();
}
}
}
}
// Serialization Support
private static final long serialVersionUID = 4;
@Override
Object writeReplace() {
return new ComputingSerializationProxy<K, V>(keyStrength, valueStrength, keyEquivalence,
valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize,
concurrencyLevel, removalListener, this, computingFunction);
}
static final class ComputingSerializationProxy<K, V> extends AbstractSerializationProxy<K, V> {
final Function<? super K, ? extends V> computingFunction;
ComputingSerializationProxy(Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
ConcurrentMap<K, V> delegate, Function<? super K, ? extends V> computingFunction) {
super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos,
expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate);
this.computingFunction = computingFunction;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
writeMapTo(out);
}
@SuppressWarnings("deprecation") // self-use
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MapMaker mapMaker = readMapMaker(in);
delegate = mapMaker.makeComputingMap(computingFunction);
readEntries(in);
}
Object readResolve() {
return delegate;
}
private static final long serialVersionUID = 4;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link SetMultimap} interface. It's a wrapper
* around {@link AbstractMultimap} that converts the returned collections into
* {@code Sets}. The {@link #createCollection} method must return a {@code Set}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractSetMultimap<K, V>
extends AbstractMultimap<K, V> implements SetMultimap<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 AbstractSetMultimap(Map<K, Collection<V>> map) {
super(map);
}
@Override abstract Set<V> createCollection();
// Following Javadoc copied from SetMultimap.
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*/
@Override public Set<V> get(@Nullable K key) {
return (Set<V>) super.get(key);
}
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*/
@Override public Set<Map.Entry<K, V>> entries() {
return (Set<Map.Entry<K, V>>) super.entries();
}
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*/
@Override public Set<V> removeAll(@Nullable Object key) {
return (Set<V>) super.removeAll(key);
}
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override public Set<V> replaceValues(
@Nullable K key, Iterable<? extends V> values) {
return (Set<V>) super.replaceValues(key, values);
}
/**
* {@inheritDoc}
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link Set} values.
*/
@Override public Map<K, Collection<V>> asMap() {
return super.asMap();
}
/**
* 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} if the method increased the size of the multimap, or
* {@code false} if the multimap already contained the key-value pair
*/
@Override public boolean put(K key, V value) {
return super.put(key, value);
}
/**
* 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.
*/
@Override public boolean equals(@Nullable Object object) {
return super.equals(object);
}
private static final long serialVersionUID = 7431625294878419160L;
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A sorted set multimap which forwards all its method calls to another sorted
* set multimap. Subclasses should override one or more methods to modify the
* behavior of the backing multimap as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Kurt Alfred Kluever
* @since 3.0
*/
@GwtCompatible
public abstract class ForwardingSortedSetMultimap<K, V>
extends ForwardingSetMultimap<K, V> implements SortedSetMultimap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingSortedSetMultimap() {}
@Override protected abstract SortedSetMultimap<K, V> delegate();
@Override public SortedSet<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override public SortedSet<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
@Override public Comparator<? super V> valueComparator() {
return delegate().valueComparator();
}
}
| Java |
/*
* Copyright (C) 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.Deque;
import java.util.Iterator;
/**
* A deque which forwards all its method calls to another deque. Subclasses
* should override one or more methods to modify the behavior of the backing
* deque as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingDeque} forward
* <b>indiscriminately</b> to the methods of the delegate. For example,
* overriding {@link #add} alone <b>will not</b> change the behavior of {@link
* #offer} which can lead to unexpected behavior. In this case, you should
* override {@code offer} as well, either providing your own implementation, or
* delegating to the provided {@code standardOffer} method.
*
* <p>The {@code standard} methods are not guaranteed to be thread-safe, even
* when all of the methods that they depend on are thread-safe.
*
* @author Kurt Alfred Kluever
* @since 12.0
*/
@Beta
public abstract class ForwardingDeque<E> extends ForwardingQueue<E>
implements Deque<E> {
/** Constructor for use by subclasses. */
protected ForwardingDeque() {}
@Override protected abstract Deque<E> delegate();
@Override
public void addFirst(E e) {
delegate().addFirst(e);
}
@Override
public void addLast(E e) {
delegate().addLast(e);
}
@Override
public Iterator<E> descendingIterator() {
return delegate().descendingIterator();
}
@Override
public E getFirst() {
return delegate().getFirst();
}
@Override
public E getLast() {
return delegate().getLast();
}
@Override
public boolean offerFirst(E e) {
return delegate().offerFirst(e);
}
@Override
public boolean offerLast(E e) {
return delegate().offerLast(e);
}
@Override
public E peekFirst() {
return delegate().peekFirst();
}
@Override
public E peekLast() {
return delegate().peekLast();
}
@Override
public E pollFirst() {
return delegate().pollFirst();
}
@Override
public E pollLast() {
return delegate().pollLast();
}
@Override
public E pop() {
return delegate().pop();
}
@Override
public void push(E e) {
delegate().push(e);
}
@Override
public E removeFirst() {
return delegate().removeFirst();
}
@Override
public E removeLast() {
return delegate().removeLast();
}
@Override
public boolean removeFirstOccurrence(Object o) {
return delegate().removeFirstOccurrence(o);
}
@Override
public boolean removeLastOccurrence(Object o) {
return delegate().removeLastOccurrence(o);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@link BiMap} backed by two {@link HashMap} instances. This implementation
* allows null keys and values. A {@code HashBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class HashBiMap<K, V> extends AbstractBiMap<K, V> {
/**
* Returns a new, empty {@code HashBiMap} with the default initial capacity
* (16).
*/
public static <K, V> HashBiMap<K, V> create() {
return new HashBiMap<K, V>();
}
/**
* Constructs a new, empty bimap with the specified expected size.
*
* @param expectedSize the expected number of entries
* @throws IllegalArgumentException if the specified expected size is
* negative
*/
public static <K, V> HashBiMap<K, V> create(int expectedSize) {
return new HashBiMap<K, V>(expectedSize);
}
/**
* Constructs a new bimap containing initial values from {@code map}. The
* bimap is created with an initial capacity sufficient to hold the mappings
* in the specified map.
*/
public static <K, V> HashBiMap<K, V> create(
Map<? extends K, ? extends V> map) {
HashBiMap<K, V> bimap = create(map.size());
bimap.putAll(map);
return bimap;
}
private HashBiMap() {
super(new HashMap<K, V>(), new HashMap<V, K>());
}
private HashBiMap(int expectedSize) {
super(
Maps.<K, V>newHashMapWithExpectedSize(expectedSize),
Maps.<V, K>newHashMapWithExpectedSize(expectedSize));
}
// Override these two methods to show that keys and values may be null
@Override public V put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(@Nullable K key, @Nullable V value) {
return super.forcePut(key, value);
}
/**
* @serialData the number of entries, first key, first value, second key,
* second value, and so on.
*/
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMap(this, stream);
}
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int size = Serialization.readCount(stream);
setDelegates(Maps.<K, V>newHashMapWithExpectedSize(size),
Maps.<V, K>newHashMapWithExpectedSize(size));
Serialization.populateMap(this, stream, size);
}
@GwtIncompatible("Not needed in emulated source")
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 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.io.Serializable;
import java.math.BigInteger;
/**
* Factories for common {@link DiscreteDomain} instances.
*
* <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 Gregory Kick
* @since 10.0
*/
@GwtCompatible
@Beta
public final class DiscreteDomains {
private DiscreteDomains() {}
/**
* Returns the discrete domain for values of type {@code Integer}.
*/
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;
}
private static final long serialVersionUID = 0;
}
/**
* Returns the discrete domain for values of type {@code Long}.
*/
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;
}
private static final long serialVersionUID = 0;
}
/**
* Returns the discrete domain for values of type {@code BigInteger}.
*/
// TODO(kevinb): make sure it's tested, and make it 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 start.subtract(end).max(MIN_LONG).min(MAX_LONG).longValue();
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.annotation.Nullable;
/**
* A list which forwards all its method calls to another list. Subclasses should
* override one or more methods to modify the behavior of the backing list as
* desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p>This class does not implement {@link java.util.RandomAccess}. If the
* delegate supports random access, the {@code ForwardingList} subclass should
* implement the {@code RandomAccess} interface.
*
* <p><b>Warning:</b> The methods of {@code ForwardingList} forward
* <b>indiscriminately</b> to the methods of the delegate. For example,
* overriding {@link #add} alone <b>will not</b> change the behavior of {@link
* #addAll}, which can lead to unexpected behavior. In this case, you should
* override {@code addAll} as well, either providing your own implementation, or
* delegating to the provided {@code standardAddAll} method.
*
* <p>The {@code standard} methods and any collection views they return are not
* guaranteed to be thread-safe, even when all of the methods that they depend
* on are thread-safe.
*
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingList<E> extends ForwardingCollection<E>
implements List<E> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingList() {}
@Override protected abstract List<E> delegate();
@Override
public void add(int index, E element) {
delegate().add(index, element);
}
@Override
public boolean addAll(int index, Collection<? extends E> elements) {
return delegate().addAll(index, elements);
}
@Override
public E get(int index) {
return delegate().get(index);
}
@Override
public int indexOf(Object element) {
return delegate().indexOf(element);
}
@Override
public int lastIndexOf(Object element) {
return delegate().lastIndexOf(element);
}
@Override
public ListIterator<E> listIterator() {
return delegate().listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate().listIterator(index);
}
@Override
public E remove(int index) {
return delegate().remove(index);
}
@Override
public E set(int index, E element) {
return delegate().set(index, element);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return delegate().subList(fromIndex, toIndex);
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
/**
* A sensible default implementation of {@link #add(Object)}, in terms of
* {@link #add(int, Object)}. If you override {@link #add(int, Object)}, you
* may wish to override {@link #add(Object)} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected boolean standardAdd(E element){
add(size(), element);
return true;
}
/**
* A sensible default implementation of {@link #addAll(int, Collection)}, in
* terms of the {@code add} method of {@link #listIterator(int)}. If you
* override {@link #listIterator(int)}, you may wish to override {@link
* #addAll(int, Collection)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardAddAll(
int index, Iterable<? extends E> elements) {
return Lists.addAllImpl(this, index, elements);
}
/**
* A sensible default implementation of {@link #indexOf}, in terms of {@link
* #listIterator()}. If you override {@link #listIterator()}, you may wish to
* override {@link #indexOf} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardIndexOf(@Nullable Object element) {
return Lists.indexOfImpl(this, element);
}
/**
* A sensible default implementation of {@link #lastIndexOf}, in terms of
* {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you
* may wish to override {@link #lastIndexOf} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected int standardLastIndexOf(@Nullable Object element) {
return Lists.lastIndexOfImpl(this, element);
}
/**
* A sensible default implementation of {@link #iterator}, in terms of
* {@link #listIterator()}. If you override {@link #listIterator()}, you may
* wish to override {@link #iterator} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected Iterator<E> standardIterator() {
return listIterator();
}
/**
* A sensible default implementation of {@link #listIterator()}, in terms of
* {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you
* may wish to override {@link #listIterator()} to forward to this
* implementation.
*
* @since 7.0
*/
@Beta protected ListIterator<E> standardListIterator() {
return listIterator(0);
}
/**
* A sensible default implementation of {@link #listIterator(int)}, in terms
* of {@link #size}, {@link #get(int)}, {@link #set(int, Object)}, {@link
* #add(int, Object)}, and {@link #remove(int)}. If you override any of these
* methods, you may wish to override {@link #listIterator(int)} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta protected ListIterator<E> standardListIterator(int start) {
return Lists.listIteratorImpl(this, start);
}
/**
* A sensible default implementation of {@link #subList(int, int)}. If you
* override any other methods, you may wish to override {@link #subList(int,
* int)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected List<E> standardSubList(int fromIndex, int toIndex) {
return Lists.subListImpl(this, fromIndex, toIndex);
}
/**
* A sensible definition of {@link #equals(Object)} in terms of {@link #size}
* and {@link #iterator}. If you override either of those methods, you may
* wish to override {@link #equals(Object)} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardEquals(@Nullable Object object) {
return Lists.equalsImpl(this, object);
}
/**
* A sensible definition of {@link #hashCode} in terms of {@link #iterator}.
* If you override {@link #iterator}, you may wish to override {@link
* #hashCode} to forward to this implementation.
*
* @since 7.0
*/
@Beta protected int standardHashCode() {
return Lists.hashCodeImpl(this);
}
}
| Java |
/*
* Copyright (C) 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.primitives.Booleans;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* A utility for performing a "lazy" chained comparison statement, which
* performs comparisons only until it finds a nonzero result. For example:
* <pre> {@code
*
* public int compareTo(Foo that) {
* return ComparisonChain.start()
* .compare(this.aString, that.aString)
* .compare(this.anInt, that.anInt)
* .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
* .result();
* }}</pre>
*
* The value of this expression will have the same sign as the <i>first
* nonzero</i> comparison result in the chain, or will be zero if every
* comparison result was zero.
*
* <p>Once any comparison returns a nonzero value, remaining comparisons are
* "short-circuited".
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#compare/compareTo">
* {@code ComparisonChain}</a>.
*
* @author Mark Davis
* @author Kevin Bourrillion
* @since 2.0
*/
@GwtCompatible
public abstract class ComparisonChain {
private ComparisonChain() {}
/**
* Begins a new chained comparison statement. See example in the class
* documentation.
*/
public static ComparisonChain start() {
return ACTIVE;
}
private static final ComparisonChain ACTIVE = new ComparisonChain() {
@SuppressWarnings("unchecked")
@Override public ComparisonChain compare(
Comparable left, Comparable right) {
return classify(left.compareTo(right));
}
@Override public <T> ComparisonChain compare(
@Nullable T left, @Nullable T right, Comparator<T> comparator) {
return classify(comparator.compare(left, right));
}
@Override public ComparisonChain compare(int left, int right) {
return classify(Ints.compare(left, right));
}
@Override public ComparisonChain compare(long left, long right) {
return classify(Longs.compare(left, right));
}
@Override public ComparisonChain compare(float left, float right) {
return classify(Float.compare(left, right));
}
@Override public ComparisonChain compare(double left, double right) {
return classify(Double.compare(left, right));
}
@Override public ComparisonChain compareTrueFirst(boolean left, boolean right) {
return classify(Booleans.compare(right, left)); // reversed
}
@Override public ComparisonChain compareFalseFirst(boolean left, boolean right) {
return classify(Booleans.compare(left, right));
}
ComparisonChain classify(int result) {
return (result < 0) ? LESS : (result > 0) ? GREATER : ACTIVE;
}
@Override public int result() {
return 0;
}
};
private static final ComparisonChain LESS = new InactiveComparisonChain(-1);
private static final ComparisonChain GREATER = new InactiveComparisonChain(1);
private static final class InactiveComparisonChain extends ComparisonChain {
final int result;
InactiveComparisonChain(int result) {
this.result = result;
}
@Override public ComparisonChain compare(
@Nullable Comparable left, @Nullable Comparable right) {
return this;
}
@Override public <T> ComparisonChain compare(@Nullable T left,
@Nullable T right, @Nullable Comparator<T> comparator) {
return this;
}
@Override public ComparisonChain compare(int left, int right) {
return this;
}
@Override public ComparisonChain compare(long left, long right) {
return this;
}
@Override public ComparisonChain compare(float left, float right) {
return this;
}
@Override public ComparisonChain compare(double left, double right) {
return this;
}
@Override public ComparisonChain compareTrueFirst(boolean left, boolean right) {
return this;
}
@Override public ComparisonChain compareFalseFirst(boolean left, boolean right) {
return this;
}
@Override public int result() {
return result;
}
}
/**
* Compares two comparable objects as specified by {@link
* Comparable#compareTo}, <i>if</i> the result of this comparison chain
* has not already been determined.
*/
public abstract ComparisonChain compare(
Comparable<?> left, Comparable<?> right);
/**
* Compares two objects using a comparator, <i>if</i> the result of this
* comparison chain has not already been determined.
*/
public abstract <T> ComparisonChain compare(
@Nullable T left, @Nullable T right, Comparator<T> comparator);
/**
* Compares two {@code int} values as specified by {@link Ints#compare},
* <i>if</i> the result of this comparison chain has not already been
* determined.
*/
public abstract ComparisonChain compare(int left, int right);
/**
* Compares two {@code long} values as specified by {@link Longs#compare},
* <i>if</i> the result of this comparison chain has not already been
* determined.
*/
public abstract ComparisonChain compare(long left, long right);
/**
* Compares two {@code float} values as specified by {@link
* Float#compare}, <i>if</i> the result of this comparison chain has not
* already been determined.
*/
public abstract ComparisonChain compare(float left, float right);
/**
* Compares two {@code double} values as specified by {@link
* Double#compare}, <i>if</i> the result of this comparison chain has not
* already been determined.
*/
public abstract ComparisonChain compare(double left, double right);
/**
* Compares two {@code boolean} values, considering {@code true} to be less
* than {@code false}, <i>if</i> the result of this comparison chain has not
* already been determined.
*
* @since 12.0
*/
public abstract ComparisonChain compareTrueFirst(boolean left, boolean right);
/**
* Compares two {@code boolean} values, considering {@code false} to be less
* than {@code true}, <i>if</i> the result of this comparison chain has not
* already been determined.
*
* @since 12.0 (present as {@code compare} since 2.0)
*/
public abstract ComparisonChain compareFalseFirst(boolean left, boolean right);
/**
* Old name of {@link #compareFalseFirst}.
*
* @deprecated Use {@link #compareFalseFirst}; or, if the parameters passed
* are being either negated or reversed, undo the negation or reversal and
* use {@link #compareTrueFirst}. <b>This method is scheduled for deletion
* in September 2013.</b>
*/
@Deprecated
public final ComparisonChain compare(boolean left, boolean right) {
return compareFalseFirst(left, right);
}
/**
* Ends this comparison chain and returns its result: a value having the
* same sign as the first nonzero comparison result in the chain, or zero if
* every result was zero.
*/
public abstract int result();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A collection that supports order-independent equality, like {@link Set}, but
* may have duplicate elements. A multiset is also sometimes called a
* <i>bag</i>.
*
* <p>Elements of a multiset that are equal to one another are referred to as
* <i>occurrences</i> of the same single element. The total number of
* occurrences of an element in a multiset is called the <i>count</i> of that
* element (the terms "frequency" and "multiplicity" are equivalent, but not
* used in this API). Since the count of an element is represented as an {@code
* int}, a multiset may never contain more than {@link Integer#MAX_VALUE}
* occurrences of any one element.
*
* <p>{@code Multiset} refines the specifications of several methods from
* {@code Collection}. It also defines an additional query operation, {@link
* #count}, which returns the count of an element. There are five new
* bulk-modification operations, for example {@link #add(Object, int)}, to add
* or remove multiple occurrences of an element at once, or to set the count of
* an element to a specific value. These modification operations are optional,
* but implementations which support the standard collection operations {@link
* #add(Object)} or {@link #remove(Object)} are encouraged to implement the
* related methods as well. Finally, two collection views are provided: {@link
* #elementSet} contains the distinct elements of the multiset "with duplicates
* collapsed", and {@link #entrySet} is similar but contains {@link Entry
* Multiset.Entry} instances, each providing both a distinct element and the
* count of that element.
*
* <p>In addition to these required methods, implementations of {@code
* Multiset} are expected to provide two {@code static} creation methods:
* {@code create()}, returning an empty multiset, and {@code
* create(Iterable<? extends E>)}, returning a multiset containing the
* given initial elements. This is simply a refinement of {@code Collection}'s
* constructor recommendations, reflecting the new developments of Java 5.
*
* <p>As with other collection types, the modification operations are optional,
* and should throw {@link UnsupportedOperationException} when they are not
* implemented. Most implementations should support either all add operations
* or none of them, all removal operations or none of them, and if and only if
* all of these are supported, the {@code setCount} methods as well.
*
* <p>A multiset uses {@link Object#equals} to determine whether two instances
* should be considered "the same," <i>unless specified otherwise</i> by the
* implementation.
*
* <p>Common implementations include {@link ImmutableMultiset}, {@link
* HashMultiset}, and {@link ConcurrentHashMultiset}.
*
* <p>If your values may be zero, negative, or outside the range of an int, you
* may wish to use {@link com.google.common.util.concurrent.AtomicLongMap}
* instead. Note, however, that unlike {@code Multiset}, {@code AtomicLongMap}
* does not automatically remove zeros.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface Multiset<E> extends Collection<E> {
// Query Operations
/**
* Returns the number of occurrences of an element in this multiset (the
* <i>count</i> of the element). Note that for an {@link Object#equals}-based
* multiset, this gives the same result as {@link Collections#frequency}
* (which would presumably perform more poorly).
*
* <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes
* this operation; it correctly delegates to this method when dealing with a
* multiset, but it can also accept any other iterable type.
*
* @param element the element to count occurrences of
* @return the number of occurrences of the element in this multiset; possibly
* zero but never negative
*/
int count(@Nullable Object element);
// Bulk Operations
/**
* Adds a number of occurrences of an element to this multiset. Note that if
* {@code occurrences == 1}, this method has the identical effect to {@link
* #add(Object)}. This method is functionally equivalent (except in the case
* of overflow) to the call {@code addAll(Collections.nCopies(element,
* occurrences))}, which would presumably perform much more poorly.
*
* @param element the element to add occurrences of; may be null only if
* explicitly allowed by the implementation
* @param occurrences the number of occurrences of the element to add. May be
* zero, in which case no change will be made.
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative, or if
* this operation would result in more than {@link Integer#MAX_VALUE}
* occurrences of the element
* @throws NullPointerException if {@code element} is null and this
* implementation does not permit null elements. Note that if {@code
* occurrences} is zero, the implementation may opt to return normally.
*/
int add(@Nullable E element, int occurrences);
/**
* Removes a number of occurrences of the specified element from this
* multiset. If the multiset contains fewer than this number of occurrences to
* begin with, all occurrences will be removed. Note that if
* {@code occurrences == 1}, this is functionally equivalent to the call
* {@code remove(element)}.
*
* @param element the element to conditionally remove occurrences of
* @param occurrences the number of occurrences of the element to remove. May
* be zero, in which case no change will be made.
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
int remove(@Nullable Object element, int occurrences);
/**
* Adds or removes the necessary occurrences of an element such that the
* element attains the desired count.
*
* @param element the element to add or remove occurrences of; may be null
* only if explicitly allowed by the implementation
* @param count the desired count of the element in this multiset
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code count} is negative
* @throws NullPointerException if {@code element} is null and this
* implementation does not permit null elements. Note that if {@code
* count} is zero, the implementor may optionally return zero instead.
*/
int setCount(E element, int count);
/**
* Conditionally sets the count of an element to a new value, as described in
* {@link #setCount(Object, int)}, provided that the element has the expected
* current count. If the current count is not {@code oldCount}, no change is
* made.
*
* @param element the element to conditionally set the count of; may be null
* only if explicitly allowed by the implementation
* @param oldCount the expected present count of the element in this multiset
* @param newCount the desired count of the element in this multiset
* @return {@code true} if the condition for modification was met. This
* implies that the multiset was indeed modified, unless
* {@code oldCount == newCount}.
* @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is
* negative
* @throws NullPointerException if {@code element} is null and the
* implementation does not permit null elements. Note that if {@code
* oldCount} and {@code newCount} are both zero, the implementor may
* optionally return {@code true} instead.
*/
boolean setCount(E element, int oldCount, int newCount);
// Views
/**
* Returns the set of distinct elements contained in this multiset. The
* element set is backed by the same data as the multiset, so any change to
* either is immediately reflected in the other. The order of the elements in
* the element set is unspecified.
*
* <p>If the element set supports any removal operations, these necessarily
* cause <b>all</b> occurrences of the removed element(s) to be removed from
* the multiset. Implementations are not expected to support the add
* operations, although this is possible.
*
* <p>A common use for the element set is to find the number of distinct
* elements in the multiset: {@code elementSet().size()}.
*
* @return a view of the set of distinct elements in this multiset
*/
Set<E> elementSet();
/**
* Returns a view of the contents of this multiset, grouped into {@code
* Multiset.Entry} instances, each providing an element of the multiset and
* the count of that element. This set contains exactly one entry for each
* distinct element in the multiset (thus it always has the same size as the
* {@link #elementSet}). The order of the elements in the element set is
* unspecified.
*
* <p>The entry set is backed by the same data as the multiset, so any change
* to either is immediately reflected in the other. However, multiset changes
* may or may not be reflected in any {@code Entry} instances already
* retrieved from the entry set (this is implementation-dependent).
* Furthermore, implementations are not required to support modifications to
* the entry set at all, and the {@code Entry} instances themselves don't
* even have methods for modification. See the specific implementation class
* for more details on how its entry set handles modifications.
*
* @return a set of entries representing the data of this multiset
*/
Set<Entry<E>> entrySet();
/**
* An unmodifiable element-count pair for a multiset. The {@link
* Multiset#entrySet} method returns a view of the multiset whose elements
* are of this class. A multiset implementation may return Entry instances
* that are either live "read-through" views to the Multiset, or immutable
* snapshots. Note that this type is unrelated to the similarly-named type
* {@code Map.Entry}.
*
* @since 2.0 (imported from Google Collections Library)
*/
interface Entry<E> {
/**
* Returns the multiset element corresponding to this entry. Multiple calls
* to this method always return the same instance.
*
* @return the element corresponding to this entry
*/
E getElement();
/**
* Returns the count of the associated element in the underlying multiset.
* This count may either be an unchanging snapshot of the count at the time
* the entry was retrieved, or a live view of the current count of the
* element in the multiset, depending on the implementation. Note that in
* the former case, this method can never return zero, while in the latter,
* it will return zero if all occurrences of the element were since removed
* from the multiset.
*
* @return the count of the element; never negative
*/
int getCount();
/**
* {@inheritDoc}
*
* <p>Returns {@code true} if the given object is also a multiset entry and
* the two entries represent the same element and count. That is, two
* entries {@code a} and {@code b} are equal if: <pre> {@code
*
* Objects.equal(a.getElement(), b.getElement())
* && a.getCount() == b.getCount()}</pre>
*/
@Override
// TODO(kevinb): check this wrt TreeMultiset?
boolean equals(Object o);
/**
* {@inheritDoc}
*
* <p>The hash code of a multiset entry for element {@code element} and
* count {@code count} is defined as: <pre> {@code
*
* ((element == null) ? 0 : element.hashCode()) ^ count}</pre>
*/
@Override
int hashCode();
/**
* Returns the canonical string representation of this entry, defined as
* follows. If the count for this entry is one, this is simply the string
* representation of the corresponding element. Otherwise, it is the string
* representation of the element, followed by the three characters {@code
* " x "} (space, letter x, space), followed by the count.
*/
@Override
String toString();
}
// Comparison and hashing
/**
* Compares the specified object with this multiset for equality. Returns
* {@code true} if the given object is also a multiset and contains equal
* elements with equal counts, regardless of order.
*/
@Override
// TODO(kevinb): caveats about equivalence-relation?
boolean equals(@Nullable Object object);
/**
* Returns the hash code for this multiset. This is defined as the sum of
* <pre> {@code
*
* ((element == null) ? 0 : element.hashCode()) ^ count(element)}</pre>
*
* over all distinct elements in the multiset. It follows that a multiset and
* its entry set always have the same hash code.
*/
@Override
int hashCode();
/**
* {@inheritDoc}
*
* <p>It is recommended, though not mandatory, that this method return the
* result of invoking {@link #toString} on the {@link #entrySet}, yielding a
* result such as {@code [a x 3, c, d x 2, e]}.
*/
@Override
String toString();
// Refined Collection Methods
/**
* {@inheritDoc}
*
* <p>Elements that occur multiple times in the multiset will appear
* multiple times in this iterator, though not necessarily sequentially.
*/
@Override
Iterator<E> iterator();
/**
* Determines whether this multiset contains the specified element.
*
* <p>This method refines {@link Collection#contains} to further specify that
* it <b>may not</b> throw an exception in response to {@code element} being
* null or of the wrong type.
*
* @param element the element to check for
* @return {@code true} if this multiset contains at least one occurrence of
* the element
*/
@Override
boolean contains(@Nullable Object element);
/**
* Returns {@code true} if this multiset contains at least one occurrence of
* each element in the specified collection.
*
* <p>This method refines {@link Collection#containsAll} to further specify
* that it <b>may not</b> throw an exception in response to any of {@code
* elements} being null or of the wrong type.
*
* <p><b>Note:</b> this method does not take into account the occurrence
* count of an element in the two collections; it may still return {@code
* true} even if {@code elements} contains several occurrences of an element
* and this multiset contains only one. This is no different than any other
* collection type like {@link List}, but it may be unexpected to the user of
* a multiset.
*
* @param elements the collection of elements to be checked for containment in
* this multiset
* @return {@code true} if this multiset contains at least one occurrence of
* each element contained in {@code elements}
* @throws NullPointerException if {@code elements} is null
*/
@Override
boolean containsAll(Collection<?> elements);
/**
* Adds a single occurrence of the specified element to this multiset.
*
* <p>This method refines {@link Collection#add}, which only <i>ensures</i>
* the presence of the element, to further specify that a successful call must
* always increment the count of the element, and the overall size of the
* collection, by one.
*
* @param element the element to add one occurrence of; may be null only if
* explicitly allowed by the implementation
* @return {@code true} always, since this call is required to modify the
* multiset, unlike other {@link Collection} types
* @throws NullPointerException if {@code element} is null and this
* implementation does not permit null elements
* @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences
* of {@code element} are already contained in this multiset
*/
@Override
boolean add(E element);
/**
* Removes a <i>single</i> occurrence of the specified element from this
* multiset, if present.
*
* <p>This method refines {@link Collection#remove} to further specify that it
* <b>may not</b> throw an exception in response to {@code element} being null
* or of the wrong type.
*
* @param element the element to remove one occurrence of
* @return {@code true} if an occurrence was found and removed
*/
@Override
boolean remove(@Nullable Object element);
/**
* {@inheritDoc}
*
* <p><b>Note:</b> This method ignores how often any element might appear in
* {@code c}, and only cares whether or not an element appears at all.
* If you wish to remove one occurrence in this multiset for every occurrence
* in {@code c}, see {@link Multisets#removeOccurrences(Multiset, Multiset)}.
*
* <p>This method refines {@link Collection#removeAll} to further specify that
* it <b>may not</b> throw an exception in response to any of {@code elements}
* being null or of the wrong type.
*/
@Override
boolean removeAll(Collection<?> c);
/**
* {@inheritDoc}
*
* <p><b>Note:</b> This method ignores how often any element might appear in
* {@code c}, and only cares whether or not an element appears at all.
* If you wish to remove one occurrence in this multiset for every occurrence
* in {@code c}, see {@link Multisets#retainOccurrences(Multiset, Multiset)}.
*
* <p>This method refines {@link Collection#retainAll} to further specify that
* it <b>may not</b> throw an exception in response to any of {@code elements}
* being null or of the wrong type.
*
* @see Multisets#retainOccurrences(Multiset, Multiset)
*/
@Override
boolean retainAll(Collection<?> c);
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.