code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.LinkedHashMap; /** * A {@code Multiset} implementation with predictable iteration order. Its * iterator orders elements according to when the first occurrence of the * element was added. When the multiset contains multiple instances of an * element, those instances are consecutive in the iteration order. If all * occurrences of an element are removed, after which that element is added to * the multiset, the element will appear at the end of the iteration. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code LinkedHashMultiset} using the default initial * capacity. */ public static <E> LinkedHashMultiset<E> create() { return new LinkedHashMultiset<E>(); } /** * Creates a new, empty {@code LinkedHashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> LinkedHashMultiset<E> create(int distinctElements) { return new LinkedHashMultiset<E>(distinctElements); } /** * Creates a new {@code LinkedHashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> LinkedHashMultiset<E> create( Iterable<? extends E> elements) { LinkedHashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private LinkedHashMultiset() { super(new LinkedHashMap<E, Count>()); } private LinkedHashMultiset(int distinctElements) { // Could use newLinkedHashMapWithExpectedSize() if it existed super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements))); } }
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 java.util.List; /** * GWT emulation of {@link ImmutableAsList}. * * @author Hayward Chan */ final class ImmutableAsList<E> extends RegularImmutableList<E> { ImmutableAsList(List<E> delegate) { super(delegate); } }
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 java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashMap; 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) { builderMultimap = new SortedKeyBuilderMultimap<K, V>( checkNotNull(keyComparator), builderMultimap); 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() { 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 */ @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 */ @Override public ImmutableSet<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @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; } }
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.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Arrays; import java.util.Collection; 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> implements Iterable<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 {@code element}; that is, * 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 */ public static <T> T getOnlyElement( Iterable<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 * @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 Iterable<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 IterableWithToString<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 IterableWithToString<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 IterableWithToString<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 IterableWithToString<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } }; } /** * Returns {@code true} if one or more elements in {@code iterable} satisfy * 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, T)} 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 */ public static <T> T find(Iterable<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 IterableWithToString<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 */ public static <T> T get(Iterable<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 */ public static <T> T getFirst(Iterable<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 */ public static <T> T getLast(Iterable<T> iterable, @Nullable T defaultValue) { if (iterable instanceof Collection) { Collection<T> collection = (Collection<T>) iterable; if (collection.isEmpty()) { return defaultValue; } } if (iterable instanceof List) { List<T> list = (List<T>) 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<T> sortedSet = (SortedSet<T>) 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 IterableWithToString<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 IterableWithToString<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); Iterators.skip(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 IterableWithToString<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 Iterable<T>() { @Override public Iterator<T> iterator() { return new ConsumingQueueIterator<T>((Queue<T>) iterable); } }; } checkNotNull(iterable); return new Iterable<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 /** * Adapts a list to an iterable with reversed iteration order. It is * especially useful in foreach-style loops: <pre> {@code * * List<String> mylist = ... * for (String str : Iterables.reverse(mylist)) { * ... * }}</pre> * * There is no corresponding method in {@link Iterators}, since {@link * Iterable#iterator} can simply be invoked on the result of calling this * method. * * @return an iterable with the same elements as the list, in reverse * * @deprecated use {@link Lists#reverse(List)} or {@link * ImmutableList#reverse()}. <b>This method is scheduled for deletion in * July 2012.</b> */ @Deprecated public static <T> Iterable<T> reverse(final List<T> list) { return Lists.reverse(list); } /** * 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(); } // Non-public /** * Removes the specified element from the specified iterable. * * <p>This method iterates over the iterable, checking each element returned * by the iterator in turn to see if it equals the object {@code o}. If they * are equal, it is removed from the iterable with the iterator's * {@code remove} method. At most one element is removed, even if the iterable * contains multiple members that equal {@code o}. * * <p><b>Warning:</b> Do not use this method for a collection, such as a * {@link HashSet}, that has a fast {@code remove} method. * * @param iterable the iterable from which to remove * @param o an element to remove from the collection * @return {@code true} if the iterable changed as a result * @throws UnsupportedOperationException if the iterator does not support the * {@code remove} method and the iterable contains the object */ static boolean remove(Iterable<?> iterable, @Nullable Object o) { Iterator<?> i = iterable.iterator(); while (i.hasNext()) { if (Objects.equal(i.next(), o)) { i.remove(); return true; } } return false; } abstract static class IterableWithToString<E> implements Iterable<E> { @Override public String toString() { return Iterables.toString(this); } } /** * 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 Iterable<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) 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.ArrayList; import java.util.List; /** * This class implements the client-side GWT serialization of * {@link ImmutableAsList}. * * @author Hayward Chan */ public class ImmutableAsList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableList<?> instance) { } public static ImmutableAsList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = new ArrayList<Object>(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); return new ImmutableAsList<Object>(elements); } public static void serialize(SerializationStreamWriter writer, ImmutableAsList<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
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.Function; 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.Collections2.FilteredCollection; import com.google.common.math.IntMath; 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.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link Set} instances. Also see this * class's counterparts {@link Lists} and {@link Maps}. * * <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() {} /** * 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 {@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 } /** * 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. */ 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 */ @Beta @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 UnmodifiableIterator<List<B>>() { int index; @Override public boolean hasNext() { return index < size; } @Override public List<B> next() { if (!hasNext()) { throw new NoSuchElementException(); } Object[] tuple = new Object[axes.size()]; for (int i = 0 ; i < tuple.length; i++) { tuple[i] = axes.get(i).getForIndex(index); } 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; } /** * Creates a view of Set<B> for a Set<A>, given a bijection between A and B. * (Modelled for now as InvertibleFunction<A, B>, can't be Converter<A, B> * because that's not in Guava, though both designs are less than optimal). * Note that the bijection is treated as undefined for values not in the * given Set<A> - it doesn't have to define a true bijection for those. * * <p>Note that the returned Set's contains method is unsafe - * you *must* pass an instance of B to it, since the bijection * can only invert B's (not any Object) back to A, so we can * then delegate the call to the original Set<A>. */ static <A, B> Set<B> transform( Set<A> set, InvertibleFunction<A, B> bijection) { return new TransformedSet<A, B>( Preconditions.checkNotNull(set, "set"), Preconditions.checkNotNull(bijection, "bijection") ); } /** * Stop-gap measure since there is no bijection related type in Guava. */ abstract static class InvertibleFunction<A, B> implements Function<A, B> { abstract A invert(B b); public InvertibleFunction<B, A> inverse() { return new InvertibleFunction<B, A>() { @Override public A apply(B b) { return InvertibleFunction.this.invert(b); } @Override B invert(A a) { return InvertibleFunction.this.apply(a); } // Not required per se, but just for good karma. @Override public InvertibleFunction<A, B> inverse() { return InvertibleFunction.this; } }; } } private static class TransformedSet<A, B> extends AbstractSet<B> { final Set<A> delegate; final InvertibleFunction<A, B> bijection; TransformedSet(Set<A> delegate, InvertibleFunction<A, B> bijection) { this.delegate = delegate; this.bijection = bijection; } @Override public Iterator<B> iterator() { return Iterators.transform(delegate.iterator(), bijection); } @Override public int size() { return delegate.size(); } @SuppressWarnings("unchecked") // unsafe, passed object *must* be B @Override public boolean contains(Object o) { B b = (B) o; A a = bijection.invert(b); /* * Mathematically, Converter<A, B> defines a bijection between ALL A's * on ALL B's. Here we concern ourselves with a subset * of this relation: we only want the part that is defined by a *subset* * of all A's (defined by that Set<A> delegate), and the image * of *that* on B (which is this set). We don't care whether * the converter is *not* a bijection for A's that are not in Set<A> * or B's not in this Set<B>. * * We only want to return true if and only f the user passes a B instance * that is contained in precisely in the image of Set<A>. * * The first test is whether the inverse image of this B is indeed * in Set<A>. But we don't know whether that B belongs in this Set<B> * or not; if not, the converter is free to return * anything it wants, even an element of Set<A> (and this relationship * is not part of the Set<A> <--> Set<B> bijection), and we must not * be confused by that. So we have to do a final check to see if the * image of that A is really equivalent to the passed B, which proves * that the given B belongs indeed in the image of Set<A>. */ return delegate.contains(a) && Objects.equal(bijection.apply(a), o); } @Override public boolean add(B b) { return delegate.add(bijection.invert(b)); } @SuppressWarnings("unchecked") // unsafe, passed object *must* be B @Override public boolean remove(Object o) { return contains(o) && delegate.remove(bijection.invert((B) o)); } @Override public void clear() { delegate.clear(); } } /** * Remove each element in an iterable from a set. */ static boolean removeAllImpl(Set<?> set, Iterable<?> iterable) { // TODO(jlevy): Have ForwardingSet.standardRemoveAll() call this method. boolean changed = false; for (Object o : iterable) { changed |= set.remove(o); } return changed; } }
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; /** * Minimal GWT emulation of {@code com.google.common.collect.Platform}. * * <p><strong>This .java file should never be consumed by javac.</strong> * * @author Hayward Chan */ class Platform { static <T> T[] clone(T[] array) { return GwtPlatform.clone(array); } // TODO: Fix System.arraycopy in GWT so that it isn't necessary. static void unsafeArrayCopy( Object[] src, int srcPos, Object[] dest, int destPos, int length) { for (int i = 0; i < length; i++) { dest[destPos + i] = src[srcPos + i]; } } static <T> T[] newArray(Class<T> type, int length) { throw new UnsupportedOperationException( "Platform.newArray is not supported in GWT yet."); } static <T> T[] newArray(T[] reference, int length) { return GwtPlatform.newArray(reference, length); } static MapMaker tryWeakKeys(MapMaker mapMaker) { return mapMaker; } }
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.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(); } }
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.setCountImpl; import static java.util.Collections.unmodifiableList; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSequentialList; import java.util.AbstractSet; 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 AbstractSet<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 keyCount.contains(key); } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); // eager for GWT return super.removeAll(c); } }; } 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 AbstractCollection<K> implements Multiset<K> { @Override public int size() { return keyCount.size(); } @Override public Iterator<K> iterator() { final Iterator<Node<K, V>> nodes = new NodeIterator(); return new Iterator<K>() { @Override public boolean hasNext() { return nodes.hasNext(); } @Override public K next() { return nodes.next().key; } @Override public void remove() { nodes.remove(); } }; } @Override public int count(@Nullable Object key) { return keyCount.count(key); } @Override public int add(@Nullable K key, int occurrences) { throw new UnsupportedOperationException(); } @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 int setCount(K element, int count) { return setCountImpl(this, element, count); } @Override public boolean setCount(K element, int oldCount, int newCount) { return setCountImpl(this, element, oldCount, newCount); } @Override public boolean removeAll(Collection<?> c) { return Iterators.removeAll(iterator(), c); } @Override public boolean retainAll(Collection<?> c) { return Iterators.retainAll(iterator(), c); } @Override public Set<K> elementSet() { return keySet(); } @Override public Set<Entry<K>> entrySet() { // TODO(jlevy): lazy init? return new AbstractSet<Entry<K>>() { @Override public int size() { return keyCount.elementSet().size(); } @Override public Iterator<Entry<K>> iterator() { final Iterator<K> keyIterator = new DistinctKeyIterator(); return new Iterator<Entry<K>>() { @Override public boolean hasNext() { return keyIterator.hasNext(); } @Override public Entry<K> next() { final K key = keyIterator.next(); return new Multisets.AbstractEntry<K>() { @Override public K getElement() { return key; } @Override public int getCount() { return keyCount.count(key); } }; } @Override public void remove() { keyIterator.remove(); } }; } }; } @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 ListIterator<V>() { @Override public boolean hasNext() { return nodes.hasNext(); } @Override public V next() { return nodes.next().value; } @Override public boolean hasPrevious() { return nodes.hasPrevious(); } @Override public V previous() { return nodes.previous().value; } @Override public int nextIndex() { return nodes.nextIndex(); } @Override public int previousIndex() { return nodes.previousIndex(); } @Override public void remove() { nodes.remove(); } @Override public void set(V e) { nodes.setValue(e); } @Override public void add(V e) { throw new UnsupportedOperationException(); } }; } }; } 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) { final ListIterator<Node<K, V>> nodes = new NodeIterator(index); return new ListIterator<Entry<K, V>>() { @Override public boolean hasNext() { return nodes.hasNext(); } @Override public Entry<K, V> next() { return createEntry(nodes.next()); } @Override public void remove() { nodes.remove(); } @Override public boolean hasPrevious() { return nodes.hasPrevious(); } @Override public Map.Entry<K, V> previous() { return createEntry(nodes.previous()); } @Override public int nextIndex() { return nodes.nextIndex(); } @Override public int previousIndex() { return nodes.previousIndex(); } @Override public void set(Map.Entry<K, V> e) { throw new UnsupportedOperationException(); } @Override public void add(Map.Entry<K, V> e) { throw new UnsupportedOperationException(); } }; } }; } return result; } private class AsMapEntries extends AbstractSet<Entry<K, Collection<V>>> { @Override public int size() { return keyCount.elementSet().size(); } @Override public Iterator<Entry<K, Collection<V>>> iterator() { final Iterator<K> keyIterator = new DistinctKeyIterator(); return new Iterator<Entry<K, Collection<V>>>() { @Override public boolean hasNext() { return keyIterator.hasNext(); } @Override public Entry<K, Collection<V>> next() { final K key = keyIterator.next(); return new AbstractMapEntry<K, Collection<V>>() { @Override public K getKey() { return key; } @Override public Collection<V> getValue() { return LinkedListMultimap.this.get(key); } }; } @Override public void remove() { keyIterator.remove(); } }; } // TODO(jlevy): Override contains() and remove() for better performance. } 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 AbstractMap<K, Collection<V>>() { Set<Entry<K, Collection<V>>> entrySet; @Override public Set<Entry<K, Collection<V>>> entrySet() { Set<Entry<K, Collection<V>>> result = entrySet; if (result == null) { entrySet = result = new AsMapEntries(); } return result; } // The following methods are included for performance. @Override public boolean containsKey(@Nullable Object key) { return LinkedListMultimap.this.containsKey(key); } @SuppressWarnings("unchecked") @Override public Collection<V> get(@Nullable Object key) { Collection<V> collection = LinkedListMultimap.this.get((K) key); return collection.isEmpty() ? null : collection; } @Override public Collection<V> remove(@Nullable Object key) { Collection<V> collection = removeAll(key); return collection.isEmpty() ? null : collection; } }; } 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(); } }
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; /** * GWT emulated version of EmptyImmutableList. * * @author Hayward Chan */ final class EmptyImmutableList extends ImmutableList<Object> { static final EmptyImmutableList INSTANCE = new EmptyImmutableList(); }
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.HashMap; /** * Multiset implementation backed by a {@link HashMap}. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code HashMultiset} using the default initial * capacity. */ public static <E> HashMultiset<E> create() { return new HashMultiset<E>(); } /** * Creates a new, empty {@code HashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> HashMultiset<E> create(int distinctElements) { return new HashMultiset<E>(distinctElements); } /** * Creates a new {@code HashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> HashMultiset<E> create(Iterable<? extends E> elements) { HashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private HashMultiset() { super(new HashMap<E, Count>()); } private HashMultiset(int distinctElements) { super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.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); } }
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 java.util.List; /** * GWT emulated version of {@link RegularImmutableList}. * * @author Hayward Chan */ class RegularImmutableList<E> extends ImmutableList<E> { RegularImmutableList(List<E> delegate) { super(delegate); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkArgument; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * GWT emulation of {@link ImmutableSortedSet}. * * @author Hayward Chan */ public abstract class ImmutableSortedSet<E> extends ImmutableSet<E> implements SortedSet<E>, SortedIterable<E> { // In the non-emulated source, this is in ImmutableSortedSetFauxverideShim, // which overrides ImmutableSet & which ImmutableSortedSet extends. // It is necessary here because otherwise the builder() method // would be inherited from the emulated ImmutableSet. @Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() { throw new UnsupportedOperationException(); } // TODO: Can we find a way to remove this @SuppressWarnings even for eclipse? @SuppressWarnings("unchecked") private static final Comparator NATURAL_ORDER = Ordering.natural(); @SuppressWarnings("unchecked") private static final ImmutableSortedSet<Object> NATURAL_EMPTY_SET = new EmptyImmutableSortedSet<Object>(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) { checkNotNull(comparator); if (NATURAL_ORDER.equals(comparator)) { return emptySet(); } else { return new EmptyImmutableSortedSet<E>(comparator); } } public static <E> ImmutableSortedSet<E> of() { return emptySet(); } public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E element) { return ofInternal(Ordering.natural(), element); } @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2) { return ofInternal(Ordering.natural(), e1, e2); } @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3) { return ofInternal(Ordering.natural(), e1, e2, e3); } @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3, E e4) { return ofInternal(Ordering.natural(), e1, e2, e3, e4); } @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3, E e4, E e5) { return ofInternal(Ordering.natural(), e1, e2, e3, e4, e5); } @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); // This is messed up. See TODO at top of file. return ofInternal(Ordering.natural(), (E[]) all.toArray(new Comparable[0])); } @Deprecated public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E[] elements) { return copyOf(elements); } private static <E> ImmutableSortedSet<E> ofInternal( Comparator<? super E> comparator, E... elements) { checkNotNull(elements); switch (elements.length) { case 0: return emptySet(comparator); default: SortedSet<E> delegate = new TreeSet<E>(comparator); for (E element : elements) { checkNotNull(element); delegate.add(element); } return new RegularImmutableSortedSet<E>(delegate, false); } } public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf( Collection<? extends E> elements) { return copyOfInternal(Ordering.natural(), elements, false); } public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf( Iterable<? extends E> elements) { return copyOfInternal(Ordering.natural(), elements, false); } public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf( Iterator<? extends E> elements) { return copyOfInternal(Ordering.natural(), elements); } public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf( E[] elements) { return ofInternal(Ordering.natural(), elements); } public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Iterable<? extends E> elements) { checkNotNull(comparator); return copyOfInternal(comparator, elements, false); } public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Collection<? extends E> elements) { checkNotNull(comparator); return copyOfInternal(comparator, elements, false); } public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Iterator<? extends E> elements) { checkNotNull(comparator); return copyOfInternal(comparator, elements); } @SuppressWarnings("unchecked") public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) { Comparator<? super E> comparator = sortedSet.comparator(); if (comparator == null) { comparator = NATURAL_ORDER; } return copyOfInternal(comparator, sortedSet.iterator()); } private static <E> ImmutableSortedSet<E> copyOfInternal( Comparator<? super E> comparator, Iterable<? extends E> elements, boolean fromSortedSet) { checkNotNull(comparator); boolean hasSameComparator = fromSortedSet || hasSameComparator(elements, comparator); if (hasSameComparator && (elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") ImmutableSortedSet<E> result = (ImmutableSortedSet<E>) elements; boolean isSubset = (result instanceof RegularImmutableSortedSet) && ((RegularImmutableSortedSet) result).isSubset; if (!isSubset) { // Only return the original copy if this immutable sorted set isn't // a subset of another, to avoid memory leak. return result; } } return copyOfInternal(comparator, elements.iterator()); } private static <E> ImmutableSortedSet<E> copyOfInternal( Comparator<? super E> comparator, Iterator<? extends E> elements) { checkNotNull(comparator); if (!elements.hasNext()) { return emptySet(comparator); } SortedSet<E> delegate = new TreeSet<E>(comparator); while (elements.hasNext()) { E element = elements.next(); checkNotNull(element); delegate.add(element); } return new RegularImmutableSortedSet<E>(delegate, false); } private static boolean hasSameComparator( Iterable<?> elements, Comparator<?> comparator) { if (elements instanceof SortedSet) { SortedSet<?> sortedSet = (SortedSet<?>) elements; Comparator<?> comparator2 = sortedSet.comparator(); return (comparator2 == null) ? comparator == Ordering.natural() : comparator.equals(comparator2); } return false; } // Assumes that delegate doesn't have null elements and comparator. static <E> ImmutableSortedSet<E> unsafeDelegateSortedSet( SortedSet<E> delegate, boolean isSubset) { return delegate.isEmpty() ? emptySet(delegate.comparator()) : new RegularImmutableSortedSet<E>(delegate, isSubset); } // This reference is only used by GWT compiler to infer the elements of the // set that needs to be serialized. private Comparator<E> unusedComparatorForSerialization; private E unusedElementForSerialization; private transient final SortedSet<E> sortedDelegate; ImmutableSortedSet(Comparator<? super E> comparator) { this(Sets.newTreeSet(comparator)); } ImmutableSortedSet(SortedSet<E> sortedDelegate) { super(sortedDelegate); this.sortedDelegate = Collections.unmodifiableSortedSet(sortedDelegate); } public Comparator<? super E> comparator() { return sortedDelegate.comparator(); } @Override // needed to unify SortedIterable and Collection iterator() methods public UnmodifiableIterator<E> iterator() { return super.iterator(); } @Override public boolean contains(@Nullable Object object) { try { // This set never contains null. We need to explicitly check here // because some comparator might throw NPE (e.g. the natural ordering). return object != null && sortedDelegate.contains(object); } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { for (Object target : targets) { if (target == null) { // This set never contains null. We need to explicitly check here // because some comparator might throw NPE (e.g. the natural ordering). return false; } } try { return sortedDelegate.containsAll(targets); } catch (ClassCastException e) { return false; } } public E first() { return sortedDelegate.first(); } public ImmutableSortedSet<E> headSet(E toElement) { checkNotNull(toElement); try { return unsafeDelegateSortedSet(sortedDelegate.headSet(toElement), true); } catch (IllegalArgumentException e) { return emptySet(comparator()); } } E higher(E e) { checkNotNull(e); Iterator<E> iterator = tailSet(e).iterator(); while (iterator.hasNext()) { E higher = iterator.next(); if (comparator().compare(e, higher) < 0) { return higher; } } return null; } ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) { checkNotNull(toElement); if (inclusive) { E tmp = higher(toElement); if (tmp == null) { return this; } toElement = tmp; } return headSet(toElement); } public E last() { return sortedDelegate.last(); } public ImmutableSortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } ImmutableSortedSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { checkNotNull(fromElement); checkNotNull(toElement); int cmp = comparator().compare(fromElement, toElement); checkArgument(cmp <= 0, "fromElement (%s) is less than toElement (%s)", fromElement, toElement); if (cmp == 0 && !(fromInclusive && toInclusive)) { return emptySet(comparator()); } return tailSet(fromElement, fromInclusive).headSet(toElement, toInclusive); } public ImmutableSortedSet<E> tailSet(E fromElement) { checkNotNull(fromElement); try { return unsafeDelegateSortedSet(sortedDelegate.tailSet(fromElement), true); } catch (IllegalArgumentException e) { return emptySet(comparator()); } } ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) { checkNotNull(fromElement); if (!inclusive) { E tmp = higher(fromElement); if (tmp == null) { return emptySet(comparator()); } fromElement = tmp; } return tailSet(fromElement); } public static <E> Builder<E> orderedBy(Comparator<E> comparator) { return new Builder<E>(comparator); } public static <E extends Comparable<E>> Builder<E> reverseOrder() { return new Builder<E>(Ordering.natural().reverse()); } public static <E extends Comparable<E>> Builder<E> naturalOrder() { return new Builder<E>(Ordering.natural()); } public static final class Builder<E> extends ImmutableSet.Builder<E> { private final Comparator<? super E> comparator; public Builder(Comparator<? super E> comparator) { this.comparator = checkNotNull(comparator); } @Override public Builder<E> add(E element) { super.add(element); return this; } @Override public Builder<E> add(E... elements) { super.add(elements); return this; } @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } @Override public ImmutableSortedSet<E> build() { return copyOfInternal(comparator, contents.iterator()); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.BstSide.LEFT; import static com.google.common.collect.BstSide.RIGHT; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import javax.annotation.Nullable; /** * A multiset which maintains the ordering of its elements, according to either * their natural order or an explicit {@link Comparator}. In all cases, this * implementation uses {@link Comparable#compareTo} or {@link * Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as * explained by the {@link Comparable} class specification. Otherwise, the * resulting multiset will violate the {@link java.util.Collection} contract, * which is specified in terms of {@link Object#equals}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Louis Wasserman * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class TreeMultiset<E> extends AbstractSortedMultiset<E> implements Serializable { /** * Creates a new, empty multiset, sorted according to the elements' natural * order. All elements inserted into the multiset must implement the * {@code Comparable} interface. Furthermore, all such elements must be * <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and {@code e2} in * the multiset. If the user attempts to add an element to the multiset that * violates this constraint (for example, the user attempts to add a string * element to a set whose elements are integers), the {@code add(Object)} * call will throw a {@code ClassCastException}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the * more specific {@code <E extends Comparable<? super E>>}, to support * classes defined without generics. */ public static <E extends Comparable> TreeMultiset<E> create() { return new TreeMultiset<E>(Ordering.natural()); } /** * Creates a new, empty multiset, sorted according to the specified * comparator. All elements inserted into the multiset must be <i>mutually * comparable</i> by the specified comparator: {@code comparator.compare(e1, * e2)} must not throw a {@code ClassCastException} for any elements {@code * e1} and {@code e2} in the multiset. If the user attempts to add an element * to the multiset that violates this constraint, the {@code add(Object)} call * will throw a {@code ClassCastException}. * * @param comparator the comparator that will be used to sort this multiset. A * null value indicates that the elements' <i>natural ordering</i> should * be used. */ @SuppressWarnings("unchecked") public static <E> TreeMultiset<E> create( @Nullable Comparator<? super E> comparator) { return (comparator == null) ? new TreeMultiset<E>((Comparator) Ordering.natural()) : new TreeMultiset<E>(comparator); } /** * Creates an empty multiset containing the given initial elements, sorted * according to the elements' natural order. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the * more specific {@code <E extends Comparable<? super E>>}, to support * classes defined without generics. */ public static <E extends Comparable> TreeMultiset<E> create( Iterable<? extends E> elements) { TreeMultiset<E> multiset = create(); Iterables.addAll(multiset, elements); return multiset; } /** * Returns an iterator over the elements contained in this collection. */ @Override public Iterator<E> iterator() { // Needed to avoid Javadoc bug. return super.iterator(); } private TreeMultiset(Comparator<? super E> comparator) { super(comparator); this.range = GeneralRange.all(comparator); this.rootReference = new Reference<Node<E>>(); } private TreeMultiset(GeneralRange<E> range, Reference<Node<E>> root) { super(range.comparator()); this.range = range; this.rootReference = root; } @SuppressWarnings("unchecked") E checkElement(Object o) { return (E) o; } private transient final GeneralRange<E> range; private transient final Reference<Node<E>> rootReference; static final class Reference<T> { T value; public Reference() {} public T get() { return value; } public boolean compareAndSet(T expected, T newValue) { if (value == expected) { value = newValue; return true; } return false; } } @Override int distinctElements() { Node<E> root = rootReference.get(); return Ints.checkedCast(BstRangeOps.totalInRange(distinctAggregate(), range, root)); } @Override public int size() { Node<E> root = rootReference.get(); return Ints.saturatedCast(BstRangeOps.totalInRange(sizeAggregate(), range, root)); } @Override public int count(@Nullable Object element) { try { E e = checkElement(element); if (range.contains(e)) { Node<E> node = BstOperations.seek(comparator(), rootReference.get(), e); return countOrZero(node); } return 0; } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } } private int mutate(@Nullable E e, MultisetModifier modifier) { BstMutationRule<E, Node<E>> mutationRule = BstMutationRule.createRule( modifier, BstCountBasedBalancePolicies. <E, Node<E>>singleRebalancePolicy(distinctAggregate()), nodeFactory()); BstMutationResult<E, Node<E>> mutationResult = BstOperations.mutate(comparator(), mutationRule, rootReference.get(), e); if (!rootReference.compareAndSet( mutationResult.getOriginalRoot(), mutationResult.getChangedRoot())) { throw new ConcurrentModificationException(); } Node<E> original = mutationResult.getOriginalTarget(); return countOrZero(original); } @Override public int add(E element, int occurrences) { checkElement(element); if (occurrences == 0) { return count(element); } checkArgument(range.contains(element)); return mutate(element, new AddModifier(occurrences)); } @Override public int remove(@Nullable Object element, int occurrences) { if (element == null) { return 0; } else if (occurrences == 0) { return count(element); } try { E e = checkElement(element); return range.contains(e) ? mutate(e, new RemoveModifier(occurrences)) : 0; } catch (ClassCastException e) { return 0; } } @Override public boolean setCount(E element, int oldCount, int newCount) { checkElement(element); checkArgument(range.contains(element)); return mutate(element, new ConditionalSetCountModifier(oldCount, newCount)) == oldCount; } @Override public int setCount(E element, int count) { checkElement(element); checkArgument(range.contains(element)); return mutate(element, new SetCountModifier(count)); } private BstPathFactory<Node<E>, BstInOrderPath<Node<E>>> pathFactory() { return BstInOrderPath.inOrderFactory(); } @Override Iterator<Entry<E>> entryIterator() { Node<E> root = rootReference.get(); final BstInOrderPath<Node<E>> startingPath = BstRangeOps.furthestPath(range, LEFT, pathFactory(), root); return iteratorInDirection(startingPath, RIGHT); } @Override Iterator<Entry<E>> descendingEntryIterator() { Node<E> root = rootReference.get(); final BstInOrderPath<Node<E>> startingPath = BstRangeOps.furthestPath(range, RIGHT, pathFactory(), root); return iteratorInDirection(startingPath, LEFT); } private Iterator<Entry<E>> iteratorInDirection( @Nullable BstInOrderPath<Node<E>> start, final BstSide direction) { final Iterator<BstInOrderPath<Node<E>>> pathIterator = new AbstractSequentialIterator<BstInOrderPath<Node<E>>>(start) { @Override protected BstInOrderPath<Node<E>> computeNext(BstInOrderPath<Node<E>> previous) { if (!previous.hasNext(direction)) { return null; } BstInOrderPath<Node<E>> next = previous.next(direction); // TODO(user): only check against one side return range.contains(next.getTip().getKey()) ? next : null; } }; return new Iterator<Entry<E>>() { E toRemove = null; @Override public boolean hasNext() { return pathIterator.hasNext(); } @Override public Entry<E> next() { BstInOrderPath<Node<E>> path = pathIterator.next(); return new LiveEntry( toRemove = path.getTip().getKey(), path.getTip().elemCount()); } @Override public void remove() { checkState(toRemove != null); setCount(toRemove, 0); toRemove = null; } }; } class LiveEntry extends Multisets.AbstractEntry<E> { private Node<E> expectedRoot; private final E element; private int count; private LiveEntry(E element, int count) { this.expectedRoot = rootReference.get(); this.element = element; this.count = count; } @Override public E getElement() { return element; } @Override public int getCount() { if (rootReference.get() == expectedRoot) { return count; } else { // check for updates expectedRoot = rootReference.get(); return count = TreeMultiset.this.count(element); } } } @Override public void clear() { Node<E> root = rootReference.get(); Node<E> cleared = BstRangeOps.minusRange(range, BstCountBasedBalancePolicies.<E, Node<E>>fullRebalancePolicy(distinctAggregate()), nodeFactory(), root); if (!rootReference.compareAndSet(root, cleared)) { throw new ConcurrentModificationException(); } } @Override public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { checkNotNull(upperBound); return new TreeMultiset<E>( range.intersect(GeneralRange.upTo(comparator, upperBound, boundType)), rootReference); } @Override public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { checkNotNull(lowerBound); return new TreeMultiset<E>( range.intersect(GeneralRange.downTo(comparator, lowerBound, boundType)), rootReference); } /** * {@inheritDoc} * * @since 11.0 */ @Override public Comparator<? super E> comparator() { return super.comparator(); } private static final class Node<E> extends BstNode<E, Node<E>> implements Serializable { private final long size; private final int distinct; private Node(E key, int elemCount, @Nullable Node<E> left, @Nullable Node<E> right) { super(key, left, right); checkArgument(elemCount > 0); this.size = (long) elemCount + sizeOrZero(left) + sizeOrZero(right); this.distinct = 1 + distinctOrZero(left) + distinctOrZero(right); } int elemCount() { long result = size - sizeOrZero(childOrNull(LEFT)) - sizeOrZero(childOrNull(RIGHT)); return Ints.checkedCast(result); } private Node(E key, int elemCount) { this(key, elemCount, null, null); } private static final long serialVersionUID = 0; } private static long sizeOrZero(@Nullable Node<?> node) { return (node == null) ? 0 : node.size; } private static int distinctOrZero(@Nullable Node<?> node) { return (node == null) ? 0 : node.distinct; } private static int countOrZero(@Nullable Node<?> entry) { return (entry == null) ? 0 : entry.elemCount(); } @SuppressWarnings("unchecked") private BstAggregate<Node<E>> distinctAggregate() { return (BstAggregate) DISTINCT_AGGREGATE; } private static final BstAggregate<Node<Object>> DISTINCT_AGGREGATE = new BstAggregate<Node<Object>>() { @Override public int entryValue(Node<Object> entry) { return 1; } @Override public long treeValue(@Nullable Node<Object> tree) { return distinctOrZero(tree); } }; @SuppressWarnings("unchecked") private BstAggregate<Node<E>> sizeAggregate() { return (BstAggregate) SIZE_AGGREGATE; } private static final BstAggregate<Node<Object>> SIZE_AGGREGATE = new BstAggregate<Node<Object>>() { @Override public int entryValue(Node<Object> entry) { return entry.elemCount(); } @Override public long treeValue(@Nullable Node<Object> tree) { return sizeOrZero(tree); } }; @SuppressWarnings("unchecked") private BstNodeFactory<Node<E>> nodeFactory() { return (BstNodeFactory) NODE_FACTORY; } private static final BstNodeFactory<Node<Object>> NODE_FACTORY = new BstNodeFactory<Node<Object>>() { @Override public Node<Object> createNode(Node<Object> source, @Nullable Node<Object> left, @Nullable Node<Object> right) { return new Node<Object>(source.getKey(), source.elemCount(), left, right); } }; private abstract class MultisetModifier implements BstModifier<E, Node<E>> { abstract int newCount(int oldCount); @Nullable @Override public BstModificationResult<Node<E>> modify(E key, @Nullable Node<E> originalEntry) { int oldCount = countOrZero(originalEntry); int newCount = newCount(oldCount); if (oldCount == newCount) { return BstModificationResult.identity(originalEntry); } else if (newCount == 0) { return BstModificationResult.rebalancingChange(originalEntry, null); } else if (oldCount == 0) { return BstModificationResult.rebalancingChange(null, new Node<E>(key, newCount)); } else { return BstModificationResult.rebuildingChange(originalEntry, new Node<E>(originalEntry.getKey(), newCount)); } } } private final class AddModifier extends MultisetModifier { private final int countToAdd; private AddModifier(int countToAdd) { checkArgument(countToAdd > 0); this.countToAdd = countToAdd; } @Override int newCount(int oldCount) { checkArgument(countToAdd <= Integer.MAX_VALUE - oldCount, "Cannot add this many elements"); return oldCount + countToAdd; } } private final class RemoveModifier extends MultisetModifier { private final int countToRemove; private RemoveModifier(int countToRemove) { checkArgument(countToRemove > 0); this.countToRemove = countToRemove; } @Override int newCount(int oldCount) { return Math.max(0, oldCount - countToRemove); } } private final class SetCountModifier extends MultisetModifier { private final int countToSet; private SetCountModifier(int countToSet) { checkArgument(countToSet >= 0); this.countToSet = countToSet; } @Override int newCount(int oldCount) { return countToSet; } } private final class ConditionalSetCountModifier extends MultisetModifier { private final int expectedCount; private final int setCount; private ConditionalSetCountModifier(int expectedCount, int setCount) { checkArgument(setCount >= 0 & expectedCount >= 0); this.expectedCount = expectedCount; this.setCount = setCount; } @Override int newCount(int oldCount) { return (oldCount == expectedCount) ? setCount : oldCount; } } /* * TODO(jlevy): Decide whether entrySet() should return entries with an * equals() method that calls the comparator to compare the two keys. If that * change is made, AbstractMultiset.equals() can simply check whether two * multisets have equal entry sets. */ }
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 java.util.Set; /** * GWT emulation of {@link RegularImmutableSet}. * * @author Hayward Chan */ final class RegularImmutableSet<E> extends ImmutableSet<E> { RegularImmutableSet(Set<E> delegate) { super(delegate); // Required for GWT deserialization because the server-side implementation // requires this. checkArgument(delegate.size() >= 2); } }
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 java.util.Map; /** * GWt emulation of {@link RegularImmutableMap}. * * @author Hayward Chan */ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> { RegularImmutableMap(Map<? extends K, ? extends V> delegate) { super(delegate); } RegularImmutableMap(Entry<? extends K, ? extends V>... entries) { super(entries); } }
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.Equivalence; import com.google.common.base.Equivalences; import com.google.common.base.Function; import com.google.common.base.Joiner.MapJoiner; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.MapDifference.ValueDifference; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.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.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link Map} instances (including instances of * {@link SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts * {@link Lists}, {@link Sets} and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Maps"> * {@code Maps}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Isaac Shum * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Maps { private Maps() {} /** * Creates a <i>mutable</i>, empty {@code HashMap} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#of()} instead. * * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link * #newEnumMap} instead. * * @return a new, empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } /** * Creates a {@code HashMap} instance, with a high enough "initial capacity" * that it <i>should</i> hold {@code expectedSize} elements without growth. * This behavior cannot be broadly guaranteed, but it is observed to be true * for OpenJDK 1.6. It also can't be guaranteed that the method isn't * inadvertently <i>oversizing</i> the returned map. * * @param expectedSize the number of elements you expect to add to the * returned map * @return a new, empty {@code HashMap} with enough capacity to hold {@code * expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <K, V> HashMap<K, V> newHashMapWithExpectedSize( int expectedSize) { return new HashMap<K, V>(capacity(expectedSize)); } /** * Returns a capacity that is sufficient to keep the map from being resized as * long as it grows no larger than expectedSize and the load factor is >= its * default (0.75). */ static int capacity(int expectedSize) { if (expectedSize < 3) { checkArgument(expectedSize >= 0); return expectedSize + 1; } if (expectedSize < Ints.MAX_POWER_OF_TWO) { return expectedSize + expectedSize / 3; } return Integer.MAX_VALUE; // any large value } /** * Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as * the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#copyOf(Map)} instead. * * <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link * #newEnumMap} instead. * * @param map the mappings to be placed in the new map * @return a new {@code HashMap} initialized with the mappings from {@code * map} */ public static <K, V> HashMap<K, V> newHashMap( Map<? extends K, ? extends V> map) { return new HashMap<K, V>(map); } /** * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} * instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#of()} instead. * * @return a new, empty {@code LinkedHashMap} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<K, V>(); } /** * Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance * with the same mappings as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#copyOf(Map)} instead. * * @param map the mappings to be placed in the new map * @return a new, {@code LinkedHashMap} initialized with the mappings from * {@code map} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap( Map<? extends K, ? extends V> map) { return new LinkedHashMap<K, V>(map); } /** * Returns a general-purpose instance of {@code ConcurrentMap}, which supports * all optional operations of the ConcurrentMap interface. It does not permit * null keys or values. It is serializable. * * <p>This is currently accomplished by calling {@link MapMaker#makeMap()}. * * <p>It is preferable to use {@code MapMaker} directly (rather than through * this method), as it presents numerous useful configuration options, * such as the concurrency level, load factor, key/value reference types, * and value computation. * * @return a new, empty {@code ConcurrentMap} * @since 3.0 */ public static <K, V> ConcurrentMap<K, V> newConcurrentMap() { return new MapMaker().<K, V>makeMap(); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural * ordering of its elements. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedMap#of()} instead. * * @return a new, empty {@code TreeMap} */ public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() { return new TreeMap<K, V>(); } /** * Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as * the specified map and using the same ordering as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedMap#copyOfSorted(SortedMap)} instead. * * @param map the sorted map whose mappings are to be placed in the new map * and whose comparator is to be used to sort the new map * @return a new {@code TreeMap} initialized with the mappings from {@code * map} and using the comparator of {@code map} */ public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) { return new TreeMap<K, V>(map); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given * comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedMap.orderedBy(comparator).build()} instead. * * @param comparator the comparator to sort the keys with * @return a new, empty {@code TreeMap} */ public static <C, K extends C, V> TreeMap<K, V> newTreeMap( @Nullable Comparator<C> comparator) { // Ideally, the extra type parameter "C" shouldn't be necessary. It is a // work-around of a compiler type inference quirk that prevents the // following code from being compiled: // Comparator<Class<?>> comparator = null; // Map<Class<? extends Throwable>, String> map = newTreeMap(comparator); return new TreeMap<K, V>(comparator); } /** * Creates an {@code EnumMap} instance. * * @param type the key type for this map * @return a new, empty {@code EnumMap} */ public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) { return new EnumMap<K, V>(checkNotNull(type)); } /** * Creates an {@code EnumMap} with the same mappings as the specified map. * * @param map the map from which to initialize this {@code EnumMap} * @return a new {@code EnumMap} initialized with the mappings from {@code * map} * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} * instance and contains no mappings */ public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap( Map<K, ? extends V> map) { return new EnumMap<K, V>(map); } /** * Creates an {@code IdentityHashMap} instance. * * @return a new, empty {@code IdentityHashMap} */ public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() { return new IdentityHashMap<K, V>(); } /** * Computes the difference between two maps. This difference is an immutable * snapshot of the state of the maps at the time this method is called. It * will never change, even if the maps change at a later time. * * <p>Since this method uses {@code HashMap} instances internally, the keys of * the supplied maps must be well-behaved with respect to * {@link Object#equals} and {@link Object#hashCode}. * * <p><b>Note:</b>If you only need to know whether two maps have the same * mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps */ @SuppressWarnings("unchecked") public static <K, V> MapDifference<K, V> difference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) { if (left instanceof SortedMap) { SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left; SortedMapDifference<K, V> result = difference(sortedLeft, right); return result; } return difference(left, right, Equivalences.equals()); } /** * Computes the difference between two maps. This difference is an immutable * snapshot of the state of the maps at the time this method is called. It * will never change, even if the maps change at a later time. * * <p>Values are compared using a provided equivalence, in the case of * equality, the value on the 'left' is returned in the difference. * * <p>Since this method uses {@code HashMap} instances internally, the keys of * the supplied maps must be well-behaved with respect to * {@link Object#equals} and {@link Object#hashCode}. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @param valueEquivalence the equivalence relationship to use to compare * values * @return the difference between the two maps * @since 10.0 */ @Beta public static <K, V> MapDifference<K, V> difference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence) { Preconditions.checkNotNull(valueEquivalence); Map<K, V> onlyOnLeft = newHashMap(); Map<K, V> onlyOnRight = new HashMap<K, V>(right); // will whittle it down Map<K, V> onBoth = newHashMap(); Map<K, MapDifference.ValueDifference<V>> differences = newHashMap(); boolean eq = true; for (Entry<? extends K, ? extends V> entry : left.entrySet()) { K leftKey = entry.getKey(); V leftValue = entry.getValue(); if (right.containsKey(leftKey)) { V rightValue = onlyOnRight.remove(leftKey); if (valueEquivalence.equivalent(leftValue, rightValue)) { onBoth.put(leftKey, leftValue); } else { eq = false; differences.put( leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); } } else { eq = false; onlyOnLeft.put(leftKey, leftValue); } } boolean areEqual = eq && onlyOnRight.isEmpty(); return mapDifference( areEqual, onlyOnLeft, onlyOnRight, onBoth, differences); } private static <K, V> MapDifference<K, V> mapDifference(boolean areEqual, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, ValueDifference<V>> differences) { return new MapDifferenceImpl<K, V>(areEqual, Collections.unmodifiableMap(onlyOnLeft), Collections.unmodifiableMap(onlyOnRight), Collections.unmodifiableMap(onBoth), Collections.unmodifiableMap(differences)); } static class MapDifferenceImpl<K, V> implements MapDifference<K, V> { final boolean areEqual; final Map<K, V> onlyOnLeft; final Map<K, V> onlyOnRight; final Map<K, V> onBoth; final Map<K, ValueDifference<V>> differences; MapDifferenceImpl(boolean areEqual, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, ValueDifference<V>> differences) { this.areEqual = areEqual; this.onlyOnLeft = onlyOnLeft; this.onlyOnRight = onlyOnRight; this.onBoth = onBoth; this.differences = differences; } @Override public boolean areEqual() { return areEqual; } @Override public Map<K, V> entriesOnlyOnLeft() { return onlyOnLeft; } @Override public Map<K, V> entriesOnlyOnRight() { return onlyOnRight; } @Override public Map<K, V> entriesInCommon() { return onBoth; } @Override public Map<K, ValueDifference<V>> entriesDiffering() { return differences; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof MapDifference) { MapDifference<?, ?> other = (MapDifference<?, ?>) object; return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft()) && entriesOnlyOnRight().equals(other.entriesOnlyOnRight()) && entriesInCommon().equals(other.entriesInCommon()) && entriesDiffering().equals(other.entriesDiffering()); } return false; } @Override public int hashCode() { return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering()); } @Override public String toString() { if (areEqual) { return "equal"; } StringBuilder result = new StringBuilder("not equal"); if (!onlyOnLeft.isEmpty()) { result.append(": only on left=").append(onlyOnLeft); } if (!onlyOnRight.isEmpty()) { result.append(": only on right=").append(onlyOnRight); } if (!differences.isEmpty()) { result.append(": value differences=").append(differences); } return result.toString(); } } static class ValueDifferenceImpl<V> implements MapDifference.ValueDifference<V> { private final V left; private final V right; static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) { return new ValueDifferenceImpl<V>(left, right); } private ValueDifferenceImpl(@Nullable V left, @Nullable V right) { this.left = left; this.right = right; } @Override public V leftValue() { return left; } @Override public V rightValue() { return right; } @Override public boolean equals(@Nullable Object object) { if (object instanceof MapDifference.ValueDifference<?>) { MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object; return Objects.equal(this.left, that.leftValue()) && Objects.equal(this.right, that.rightValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(left, right); } @Override public String toString() { return "(" + left + ", " + right + ")"; } } /** * Computes the difference between two sorted maps, using the comparator of * the left map, or {@code Ordering.natural()} if the left map uses the * natural ordering of its elements. This difference is an immutable snapshot * of the state of the maps at the time this method is called. It will never * change, even if the maps change at a later time. * * <p>Since this method uses {@code TreeMap} instances internally, the keys of * the right map must all compare as distinct according to the comparator * of the left map. * * <p><b>Note:</b>If you only need to know whether two sorted maps have the * same mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps * @since 11.0 */ @Beta public static <K, V> SortedMapDifference<K, V> difference( SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) { checkNotNull(left); checkNotNull(right); Comparator<? super K> comparator = orNaturalOrder(left.comparator()); SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator); SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator); onlyOnRight.putAll(right); // will whittle it down SortedMap<K, V> onBoth = Maps.newTreeMap(comparator); SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator); boolean eq = true; for (Entry<? extends K, ? extends V> entry : left.entrySet()) { K leftKey = entry.getKey(); V leftValue = entry.getValue(); if (right.containsKey(leftKey)) { V rightValue = onlyOnRight.remove(leftKey); if (Objects.equal(leftValue, rightValue)) { onBoth.put(leftKey, leftValue); } else { eq = false; differences.put( leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); } } else { eq = false; onlyOnLeft.put(leftKey, leftValue); } } boolean areEqual = eq && onlyOnRight.isEmpty(); return sortedMapDifference( areEqual, onlyOnLeft, onlyOnRight, onBoth, differences); } private static <K, V> SortedMapDifference<K, V> sortedMapDifference( boolean areEqual, SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) { return new SortedMapDifferenceImpl<K, V>(areEqual, Collections.unmodifiableSortedMap(onlyOnLeft), Collections.unmodifiableSortedMap(onlyOnRight), Collections.unmodifiableSortedMap(onBoth), Collections.unmodifiableSortedMap(differences)); } static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V> implements SortedMapDifference<K, V> { SortedMapDifferenceImpl(boolean areEqual, SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) { super(areEqual, onlyOnLeft, onlyOnRight, onBoth, differences); } @Override public SortedMap<K, ValueDifference<V>> entriesDiffering() { return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering(); } @Override public SortedMap<K, V> entriesInCommon() { return (SortedMap<K, V>) super.entriesInCommon(); } @Override public SortedMap<K, V> entriesOnlyOnLeft() { return (SortedMap<K, V>) super.entriesOnlyOnLeft(); } @Override public SortedMap<K, V> entriesOnlyOnRight() { return (SortedMap<K, V>) super.entriesOnlyOnRight(); } } /** * Returns the specified comparator if not null; otherwise returns {@code * Ordering.natural()}. This method is an abomination of generics; the only * purpose of this method is to contain the ugly type-casting in one place. */ @SuppressWarnings("unchecked") static <E> Comparator<? super E> orNaturalOrder( @Nullable Comparator<? super E> comparator) { if (comparator != null) { // can't use ? : because of javac bug 5080917 return comparator; } return (Comparator<E>) Ordering.natural(); } /** * Returns an immutable map for which the {@link Map#values} are the given * elements in the given order, and each key is the product of invoking a * supplied function on its corresponding value. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same * key for more than one value in the input collection * @throws NullPointerException if any elements of {@code values} is null, or * if {@code keyFunction} produces {@code null} for any value */ public static <K, V> ImmutableMap<K, V> uniqueIndex( Iterable<V> values, Function<? super V, K> keyFunction) { return uniqueIndex(values.iterator(), keyFunction); } /** * <b>Deprecated.</b> * * @since 10.0 * @deprecated use {@link #uniqueIndex(Iterator, Function)} by casting {@code * values} to {@code Iterator<V>}, or better yet, by implementing only * {@code Iterator} and not {@code Iterable}. <b>This method is scheduled * for deletion in March 2012.</b> */ @Beta @Deprecated public static <K, V, I extends Object & Iterable<V> & Iterator<V>> ImmutableMap<K, V> uniqueIndex( I values, Function<? super V, K> keyFunction) { Iterable<V> valuesIterable = checkNotNull(values); return uniqueIndex(valuesIterable, keyFunction); } /** * Returns an immutable map for which the {@link Map#values} are the given * elements in the given order, and each key is the product of invoking a * supplied function on its corresponding value. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same * key for more than one value in the input collection * @throws NullPointerException if any elements of {@code values} is null, or * if {@code keyFunction} produces {@code null} for any value * @since 10.0 */ public static <K, V> ImmutableMap<K, V> uniqueIndex( Iterator<V> values, Function<? super V, K> keyFunction) { checkNotNull(keyFunction); ImmutableMap.Builder<K, V> builder = ImmutableMap.builder(); while (values.hasNext()) { V value = values.next(); builder.put(keyFunction.apply(value), value); } return builder.build(); } /** * Returns an immutable map entry with the specified key and value. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}. * * <p>The returned entry is serializable. * * @param key the key to be associated with the returned entry * @param value the value to be associated with the returned entry */ @GwtCompatible(serializable = true) public static <K, V> Entry<K, V> immutableEntry( @Nullable K key, @Nullable V value) { return new ImmutableEntry<K, V>(key, value); } /** * Returns an unmodifiable view of the specified set of entries. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}, * as do any operations that would modify the returned set. * * @param entrySet the entries for which to return an unmodifiable view * @return an unmodifiable view of the entries */ static <K, V> Set<Entry<K, V>> unmodifiableEntrySet( Set<Entry<K, V>> entrySet) { return new UnmodifiableEntrySet<K, V>( Collections.unmodifiableSet(entrySet)); } /** * Returns an unmodifiable view of the specified map entry. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}. * This also has the side-effect of redefining {@code equals} to comply with * the Entry contract, to avoid a possible nefarious implementation of equals. * * @param entry the entry for which to return an unmodifiable view * @return an unmodifiable view of the entry */ static <K, V> Entry<K, V> unmodifiableEntry(final Entry<K, V> entry) { checkNotNull(entry); return new AbstractMapEntry<K, V>() { @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue(); } }; } /** @see Multimaps#unmodifiableEntries */ static class UnmodifiableEntries<K, V> extends ForwardingCollection<Entry<K, V>> { private final Collection<Entry<K, V>> entries; UnmodifiableEntries(Collection<Entry<K, V>> entries) { this.entries = entries; } @Override protected Collection<Entry<K, V>> delegate() { return entries; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> delegate = super.iterator(); return new ForwardingIterator<Entry<K, V>>() { @Override public Entry<K, V> next() { return unmodifiableEntry(super.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override protected Iterator<Entry<K, V>> delegate() { return delegate; } }; } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public boolean add(Entry<K, V> element) { throw new UnsupportedOperationException(); } @Override public boolean addAll( Collection<? extends Entry<K, V>> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } } /** @see Maps#unmodifiableEntrySet(Set) */ static class UnmodifiableEntrySet<K, V> extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> { UnmodifiableEntrySet(Set<Entry<K, V>> entries) { super(entries); } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public boolean equals(@Nullable Object object) { return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } } /** * Returns a synchronized (thread-safe) bimap backed by the specified bimap. * In order to guarantee serial access, it is critical that <b>all</b> access * to the backing bimap is accomplished through the returned bimap. * * <p>It is imperative that the user manually synchronize on the returned map * when accessing any of its collection views: <pre> {@code * * BiMap<Long, String> map = Maps.synchronizedBiMap( * HashBiMap.<Long, String>create()); * ... * Set<Long> set = map.keySet(); // Needn't be in synchronized block * ... * synchronized (map) { // Synchronizing on map, not set! * Iterator<Long> it = set.iterator(); // Must be in synchronized block * while (it.hasNext()) { * foo(it.next()); * } * }}</pre> * * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned bimap will be serializable if the specified bimap is * serializable. * * @param bimap the bimap to be wrapped in a synchronized view * @return a sychronized view of the specified bimap */ public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) { return Synchronized.biMap(bimap, null); } /** * Returns an unmodifiable view of the specified bimap. This method allows * modules to provide users with "read-only" access to internal bimaps. Query * operations on the returned bimap "read through" to the specified bimap, and * attempts to modify the returned map, whether direct or via its collection * views, result in an {@code UnsupportedOperationException}. * * <p>The returned bimap will be serializable if the specified bimap is * serializable. * * @param bimap the bimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified bimap */ public static <K, V> BiMap<K, V> unmodifiableBiMap( BiMap<? extends K, ? extends V> bimap) { return new UnmodifiableBiMap<K, V>(bimap, null); } /** @see Maps#unmodifiableBiMap(BiMap) */ private static class UnmodifiableBiMap<K, V> extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable { final Map<K, V> unmodifiableMap; final BiMap<? extends K, ? extends V> delegate; transient BiMap<V, K> inverse; transient Set<V> values; UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @Nullable BiMap<V, K> inverse) { unmodifiableMap = Collections.unmodifiableMap(delegate); this.delegate = delegate; this.inverse = inverse; } @Override protected Map<K, V> delegate() { return unmodifiableMap; } @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); } @Override public BiMap<V, K> inverse() { BiMap<V, K> result = inverse; return (result == null) ? inverse = new UnmodifiableBiMap<V, K>(delegate.inverse(), this) : result; } @Override public Set<V> values() { Set<V> result = values; return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result; } private static final long serialVersionUID = 0; } /** * Returns a view of a map where each value is transformed by a function. All * other properties of the map, such as iteration order, are left intact. For * example, the code: <pre> {@code * * Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * Map<String, Double> transformed = Maps.transformValues(map, sqrt); * System.out.println(transformed);}</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>It's acceptable for the underlying map to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed map might contain null values, if the function sometimes * gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned map to be a view, but it means that the function will be * applied many times for bulk operations like {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned map doesn't need to be * a view, copy the returned map into a new map of your choosing. */ public static <K, V1, V2> Map<K, V2> transformValues( Map<K, V1> fromMap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = new EntryTransformer<K, V1, V2>() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; return transformEntries(fromMap, transformer); } /** * Returns a view of a sorted map where each value is transformed by a * function. All other properties of the map, such as iteration order, are * left intact. For example, the code: <pre> {@code * * SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * SortedMap<String, Double> transformed = * Maps.transformSortedValues(map, sqrt); * System.out.println(transformed);}</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>It's acceptable for the underlying map to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed map might contain null values, if the function sometimes * gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned map to be a view, but it means that the function will be * applied many times for bulk operations like {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned map doesn't need to be * a view, copy the returned map into a new map of your choosing. * * @since 11.0 */ @Beta public static <K, V1, V2> SortedMap<K, V2> transformValues( SortedMap<K, V1> fromMap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = new EntryTransformer<K, V1, V2>() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; return transformEntries(fromMap, transformer); } /** * Returns a view of a map whose values are derived from the original map's * entries. In contrast to {@link #transformValues}, this method's * entry-transformation logic may depend on the key as well as the value. * * <p>All other properties of the transformed map, such as iteration order, * are left intact. For example, the code: <pre> {@code * * Map<String, Boolean> options = * ImmutableMap.of("verbose", true, "sort", false); * EntryTransformer<String, Boolean, String> flagPrefixer = * new EntryTransformer<String, Boolean, String>() { * public String transformEntry(String key, Boolean value) { * return value ? key : "no" + key; * } * }; * Map<String, String> transformed = * Maps.transformEntries(options, flagPrefixer); * System.out.println(transformed);}</pre> * * ... prints {@code {verbose=verbose, sort=nosort}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>It's acceptable for the underlying map to contain null keys and null * values provided that the transformer is capable of accepting null inputs. * The transformed map might contain null values if the transformer sometimes * gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned map to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code transformer} should be fast. To avoid lazy evaluation when the * returned map doesn't need to be a view, copy the returned map into a new * map of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed map. * * @since 7.0 */ public static <K, V1, V2> Map<K, V2> transformEntries( Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { if (fromMap instanceof SortedMap) { return transformEntries((SortedMap<K, V1>) fromMap, transformer); } return new TransformedEntriesMap<K, V1, V2>(fromMap, transformer); } /** * Returns a view of a sorted map whose values are derived from the original * sorted map's entries. In contrast to {@link #transformValues}, this * method's entry-transformation logic may depend on the key as well as the * value. * * <p>All other properties of the transformed map, such as iteration order, * are left intact. For example, the code: <pre> {@code * * Map<String, Boolean> options = * ImmutableSortedMap.of("verbose", true, "sort", false); * EntryTransformer<String, Boolean, String> flagPrefixer = * new EntryTransformer<String, Boolean, String>() { * public String transformEntry(String key, Boolean value) { * return value ? key : "yes" + key; * } * }; * SortedMap<String, String> transformed = * LabsMaps.transformSortedEntries(options, flagPrefixer); * System.out.println(transformed);}</pre> * * ... prints {@code {sort=yessort, verbose=verbose}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>It's acceptable for the underlying map to contain null keys and null * values provided that the transformer is capable of accepting null inputs. * The transformed map might contain null values if the transformer sometimes * gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned map to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code transformer} should be fast. To avoid lazy evaluation when the * returned map doesn't need to be a view, copy the returned map into a new * map of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed map. * * @since 11.0 */ @Beta public static <K, V1, V2> SortedMap<K, V2> transformEntries( final SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesSortedMap<K, V1, V2>(fromMap, transformer); } /** * A transformation of the value of a key-value pair, using both key and value * as inputs. To apply the transformation to a map, use * {@link Maps#transformEntries(Map, EntryTransformer)}. * * @param <K> the key type of the input and output entries * @param <V1> the value type of the input entry * @param <V2> the value type of the output entry * @since 7.0 */ public interface EntryTransformer<K, V1, V2> { /** * Determines an output value based on a key-value pair. This method is * <i>generally expected</i>, but not absolutely required, to have the * following properties: * * <ul> * <li>Its execution does not cause any observable side effects. * <li>The computation is <i>consistent with equals</i>; that is, * {@link Objects#equal Objects.equal}{@code (k1, k2) &&} * {@link Objects#equal}{@code (v1, v2)} implies that {@code * Objects.equal(transformer.transform(k1, v1), * transformer.transform(k2, v2))}. * </ul> * * @throws NullPointerException if the key or value is null and this * transformer does not accept null arguments */ V2 transformEntry(@Nullable K key, @Nullable V1 value); } static class TransformedEntriesMap<K, V1, V2> extends AbstractMap<K, V2> { final Map<K, V1> fromMap; final EntryTransformer<? super K, ? super V1, V2> transformer; TransformedEntriesMap( Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { this.fromMap = checkNotNull(fromMap); this.transformer = checkNotNull(transformer); } @Override public int size() { return fromMap.size(); } @Override public boolean containsKey(Object key) { return fromMap.containsKey(key); } // safe as long as the user followed the <b>Warning</b> in the javadoc @SuppressWarnings("unchecked") @Override public V2 get(Object key) { V1 value = fromMap.get(key); return (value != null || fromMap.containsKey(key)) ? transformer.transformEntry((K) key, value) : null; } // safe as long as the user followed the <b>Warning</b> in the javadoc @SuppressWarnings("unchecked") @Override public V2 remove(Object key) { return fromMap.containsKey(key) ? transformer.transformEntry((K) key, fromMap.remove(key)) : null; } @Override public void clear() { fromMap.clear(); } @Override public Set<K> keySet() { return fromMap.keySet(); } Set<Entry<K, V2>> entrySet; @Override public Set<Entry<K, V2>> entrySet() { Set<Entry<K, V2>> result = entrySet; if (result == null) { entrySet = result = new EntrySet<K, V2>() { @Override Map<K, V2> map() { return TransformedEntriesMap.this; } @Override public Iterator<Entry<K, V2>> iterator() { final Iterator<Entry<K, V1>> backingIterator = fromMap.entrySet().iterator(); return Iterators.transform(backingIterator, new Function<Entry<K, V1>, Entry<K, V2>>() { @Override public Entry<K, V2> apply(Entry<K, V1> entry) { return immutableEntry( entry.getKey(), transformer.transformEntry(entry.getKey(), entry.getValue())); } }); } }; } return result; } Collection<V2> values; @Override public Collection<V2> values() { Collection<V2> result = values; if (result == null) { return values = new Values<K, V2>() { @Override Map<K, V2> map() { return TransformedEntriesMap.this; } }; } return result; } } static class TransformedEntriesSortedMap<K, V1, V2> extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> { protected SortedMap<K, V1> fromMap() { return (SortedMap<K, V1>) fromMap; } TransformedEntriesSortedMap(SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMap, transformer); } @Override public Comparator<? super K> comparator() { return fromMap().comparator(); } @Override public K firstKey() { return fromMap().firstKey(); } @Override public SortedMap<K, V2> headMap(K toKey) { return transformEntries(fromMap().headMap(toKey), transformer); } @Override public K lastKey() { return fromMap().lastKey(); } @Override public SortedMap<K, V2> subMap(K fromKey, K toKey) { return transformEntries( fromMap().subMap(fromKey, toKey), transformer); } @Override public SortedMap<K, V2> tailMap(K fromKey) { return transformEntries(fromMap().tailMap(fromKey), transformer); } } /** * Returns a map containing the mappings in {@code unfiltered} whose keys * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ public static <K, V> Map<K, V> filterKeys( Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof SortedMap) { return filterKeys((SortedMap<K, V>) unfiltered, keyPredicate); } checkNotNull(keyPredicate); Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return keyPredicate.apply(input.getKey()); } }; return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) : new FilteredKeyMap<K, V>( checkNotNull(unfiltered), keyPredicate, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * keys satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 11.0 */ @Beta public static <K, V> SortedMap<K, V> filterKeys( SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO: Return a subclass of Maps.FilteredKeyMap for slightly better // performance. checkNotNull(keyPredicate); Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return keyPredicate.apply(input.getKey()); } }; return filterEntries(unfiltered, entryPredicate); } /** * Returns a map containing the mappings in {@code unfiltered} whose values * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ public static <K, V> Map<K, V> filterValues( Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) { if (unfiltered instanceof SortedMap) { return filterValues((SortedMap<K, V>) unfiltered, valuePredicate); } checkNotNull(valuePredicate); Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return valuePredicate.apply(input.getValue()); } }; return filterEntries(unfiltered, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * values satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 11.0 */ @Beta public static <K, V> SortedMap<K, V> filterValues( SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { checkNotNull(valuePredicate); Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return valuePredicate.apply(input.getValue()); } }; return filterEntries(unfiltered, entryPredicate); } /** * Returns a map containing the mappings in {@code unfiltered} that satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes * to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. */ public static <K, V> Map<K, V> filterEntries( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { if (unfiltered instanceof SortedMap) { return filterEntries((SortedMap<K, V>) unfiltered, entryPredicate); } checkNotNull(entryPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. * * @since 11.0 */ @Beta public static <K, V> SortedMap<K, V> filterEntries( SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntrySortedMap) ? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate) : new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered map. */ private static <K, V> Map<K, V> filterFiltered(AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntryMap<K, V>(map.unfiltered, predicate); } private abstract static class AbstractFilteredMap<K, V> extends AbstractMap<K, V> { final Map<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; AbstractFilteredMap( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } boolean apply(Object key, V value) { // This method is called only when the key is in the map, implying that // key is a K. @SuppressWarnings("unchecked") K k = (K) key; return predicate.apply(Maps.immutableEntry(k, value)); } @Override public V put(K key, V value) { checkArgument(apply(key, value)); return unfiltered.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { checkArgument(apply(entry.getKey(), entry.getValue())); } unfiltered.putAll(map); } @Override public boolean containsKey(Object key) { return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); } @Override public V get(Object key) { V value = unfiltered.get(key); return ((value != null) && apply(key, value)) ? value : null; } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public V remove(Object key) { return containsKey(key) ? unfiltered.remove(key) : null; } Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = new Values() : result; } class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { final Iterator<Entry<K, V>> entryIterator = entrySet().iterator(); return new UnmodifiableIterator<V>() { @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public V next() { return entryIterator.next().getValue(); } }; } @Override public int size() { return entrySet().size(); } @Override public void clear() { entrySet().clear(); } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public boolean remove(Object o) { Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) { iterator.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> collection) { checkNotNull(collection); boolean changed = false; Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (collection.contains(entry.getValue()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } @Override public boolean retainAll(Collection<?> collection) { checkNotNull(collection); boolean changed = false; Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (!collection.contains(entry.getValue()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public <T> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered sorted map. */ private static <K, V> SortedMap<K, V> filterFiltered( FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntrySortedMap<K, V>(map.sortedMap(), predicate); } private static class FilteredEntrySortedMap<K, V> extends FilteredEntryMap<K, V> implements SortedMap<K, V> { FilteredEntrySortedMap(SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); } SortedMap<K, V> sortedMap() { return (SortedMap<K, V>) unfiltered; } @Override public Comparator<? super K> comparator() { return sortedMap().comparator(); } @Override public K firstKey() { // correctly throws NoSuchElementException when filtered map is empty. return keySet().iterator().next(); } @Override public K lastKey() { SortedMap<K, V> headMap = sortedMap(); while (true) { // correctly throws NoSuchElementException when filtered map is empty. K key = headMap.lastKey(); if (apply(key, unfiltered.get(key))) { return key; } headMap = sortedMap().headMap(key); } } @Override public SortedMap<K, V> headMap(K toKey) { return new FilteredEntrySortedMap<K, V>(sortedMap().headMap(toKey), predicate); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return new FilteredEntrySortedMap<K, V>( sortedMap().subMap(fromKey, toKey), predicate); } @Override public SortedMap<K, V> tailMap(K fromKey) { return new FilteredEntrySortedMap<K, V>( sortedMap().tailMap(fromKey), predicate); } } private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> { Predicate<? super K> keyPredicate; FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate, Predicate<Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); this.keyPredicate = keyPredicate; } Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = Sets.filter(unfiltered.entrySet(), predicate) : result; } Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = Sets.filter(unfiltered.keySet(), keyPredicate) : result; } // The cast is called only when the key is in the unfiltered map, implying // that key is a K. @Override @SuppressWarnings("unchecked") public boolean containsKey(Object key) { return unfiltered.containsKey(key) && keyPredicate.apply((K) key); } } static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> { /** * Entries in this set satisfy the predicate, but they don't validate the * input to {@code Entry.setValue()}. */ final Set<Entry<K, V>> filteredEntrySet; FilteredEntryMap( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); } Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = new EntrySet() : result; } private class EntrySet extends ForwardingSet<Entry<K, V>> { @Override protected Set<Entry<K, V>> delegate() { return filteredEntrySet; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator(); return new UnmodifiableIterator<Entry<K, V>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<K, V> next() { final Entry<K, V> entry = iterator.next(); return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return entry; } @Override public V setValue(V value) { checkArgument(apply(entry.getKey(), value)); return super.setValue(value); } }; } }; } } Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = new KeySet() : result; } private class KeySet extends AbstractSet<K> { @Override public Iterator<K> iterator() { final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator(); return new UnmodifiableIterator<K>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public K next() { return iterator.next().getKey(); } }; } @Override public int size() { return filteredEntrySet.size(); } @Override public void clear() { filteredEntrySet.clear(); } @Override public boolean contains(Object o) { return containsKey(o); } @Override public boolean remove(Object o) { if (containsKey(o)) { unfiltered.remove(o); return true; } return false; } @Override public boolean removeAll(Collection<?> collection) { checkNotNull(collection); // for GWT boolean changed = false; for (Object obj : collection) { changed |= remove(obj); } return changed; } @Override public boolean retainAll(Collection<?> collection) { checkNotNull(collection); // for GWT boolean changed = false; Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (!collection.contains(entry.getKey()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public <T> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } } @Nullable private static <K, V> Entry<K, V> unmodifiableOrNull(@Nullable Entry<K, V> entry) { return (entry == null) ? null : Maps.unmodifiableEntry(entry); } /** * {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code * entrySet().isEmpty()} instead of {@code size() == 0} to speed up * implementations where {@code size()} is O(n), and it delegates the {@code * isEmpty()} methods of its key set and value collection to this * implementation. */ @GwtCompatible static abstract class ImprovedAbstractMap<K, V> extends AbstractMap<K, V> { /** * Creates the entry set to be returned by {@link #entrySet()}. This method * is invoked at most once on a given map, at the time when {@code entrySet} * is first called. */ protected abstract Set<Entry<K, V>> createEntrySet(); private Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; if (result == null) { entrySet = result = createEntrySet(); } return result; } private Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; if (result == null) { return keySet = new KeySet<K, V>() { @Override Map<K, V> map() { return ImprovedAbstractMap.this; } }; } return result; } private Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; if (result == null) { return values = new Values<K, V>(){ @Override Map<K, V> map() { return ImprovedAbstractMap.this; } }; } return result; } /** * Returns {@code true} if this map contains no key-value mappings. * * <p>The implementation returns {@code entrySet().isEmpty()}. * * @return {@code true} if this map contains no key-value mappings */ @Override public boolean isEmpty() { return entrySet().isEmpty(); } } static final MapJoiner STANDARD_JOINER = Collections2.STANDARD_JOINER.withKeyValueSeparator("="); /** * Delegates to {@link Map#get}. Returns {@code null} on {@code * ClassCastException}. */ static <V> V safeGet(Map<?, V> map, Object key) { try { return map.get(key); } catch (ClassCastException e) { return null; } } /** * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code * ClassCastException} */ static boolean safeContainsKey(Map<?, ?> map, Object key) { try { return map.containsKey(key); } catch (ClassCastException e) { return false; } } /** * Implements {@code Collection.contains} safely for forwarding collections of * map entries. If {@code o} is an instance of {@code Map.Entry}, it is * wrapped using {@link #unmodifiableEntry} to protect against a possible * nefarious equals method. * * <p>Note that {@code c} is the backing (delegate) collection, rather than * the forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object that might be contained in {@code c} * @return {@code true} if {@code c} contains {@code o} */ static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) { if (!(o instanceof Entry)) { return false; } return c.contains(unmodifiableEntry((Entry<?, ?>) o)); } /** * Implements {@code Collection.remove} safely for forwarding collections of * map entries. If {@code o} is an instance of {@code Map.Entry}, it is * wrapped using {@link #unmodifiableEntry} to protect against a possible * nefarious equals method. * * <p>Note that {@code c} is backing (delegate) collection, rather than the * forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object to remove from {@code c} * @return {@code true} if {@code c} was changed */ static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) { if (!(o instanceof Entry)) { return false; } return c.remove(unmodifiableEntry((Entry<?, ?>) o)); } /** * An implementation of {@link Map#equals}. */ static boolean equalsImpl(Map<?, ?> map, Object object) { if (map == object) { return true; } if (object instanceof Map) { Map<?, ?> o = (Map<?, ?>) object; return map.entrySet().equals(o.entrySet()); } return false; } /** * An implementation of {@link Map#hashCode}. */ static int hashCodeImpl(Map<?, ?> map) { return Sets.hashCodeImpl(map.entrySet()); } /** * An implementation of {@link Map#toString}. */ static String toStringImpl(Map<?, ?> map) { StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{'); STANDARD_JOINER.appendTo(sb, map); return sb.append('}').toString(); } /** * An implementation of {@link Map#putAll}. */ static <K, V> void putAllImpl( Map<K, V> self, Map<? extends K, ? extends V> map) { for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) { self.put(entry.getKey(), entry.getValue()); } } /** * An admittedly inefficient implementation of {@link Map#containsKey}. */ static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) { for (Entry<?, ?> entry : map.entrySet()) { if (Objects.equal(entry.getKey(), key)) { return true; } } return false; } /** * An implementation of {@link Map#containsValue}. */ static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) { for (Entry<?, ?> entry : map.entrySet()) { if (Objects.equal(entry.getValue(), value)) { return true; } } return false; } abstract static class KeySet<K, V> extends AbstractSet<K> { abstract Map<K, V> map(); @Override public Iterator<K> iterator() { return Iterators.transform(map().entrySet().iterator(), new Function<Map.Entry<K, V>, K>() { @Override public K apply(Entry<K, V> entry) { return entry.getKey(); } }); } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(Object o) { return map().containsKey(o); } @Override public boolean remove(Object o) { if (contains(o)) { map().remove(o); return true; } return false; } @Override public boolean removeAll(Collection<?> c) { // TODO(user): find out why this is necessary to make GWT tests pass. return super.removeAll(checkNotNull(c)); } @Override public void clear() { map().clear(); } } @Nullable static <K> K keyOrNull(@Nullable Entry<K, ?> entry) { return (entry == null) ? null : entry.getKey(); } abstract static class Values<K, V> extends AbstractCollection<V> { abstract Map<K, V> map(); @Override public Iterator<V> iterator() { return Iterators.transform(map().entrySet().iterator(), new Function<Entry<K, V>, V>() { @Override public V apply(Entry<K, V> entry) { return entry.getValue(); } }); } @Override public boolean remove(Object o) { try { return super.remove(o); } catch (UnsupportedOperationException e) { for (Entry<K, V> entry : map().entrySet()) { if (Objects.equal(o, entry.getValue())) { map().remove(entry.getKey()); return true; } } return false; } } @Override public boolean removeAll(Collection<?> c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set<K> toRemove = Sets.newHashSet(); for (Entry<K, V> entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRemove.add(entry.getKey()); } } return map().keySet().removeAll(toRemove); } } @Override public boolean retainAll(Collection<?> c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set<K> toRetain = Sets.newHashSet(); for (Entry<K, V> entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRetain.add(entry.getKey()); } } return map().keySet().retainAll(toRetain); } } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(@Nullable Object o) { return map().containsValue(o); } @Override public void clear() { map().clear(); } } abstract static class EntrySet<K, V> extends AbstractSet<Entry<K, V>> { abstract Map<K, V> map(); @Override public int size() { return map().size(); } @Override public void clear() { map().clear(); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; Object key = entry.getKey(); V value = map().get(key); return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); } return false; } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean remove(Object o) { if (contains(o)) { Entry<?, ?> entry = (Entry<?, ?>) o; return map().keySet().remove(entry.getKey()); } return false; } @Override public boolean removeAll(Collection<?> c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove boolean changed = true; for (Object o : c) { changed |= remove(o); } return changed; } } @Override public boolean retainAll(Collection<?> c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size()); for (Object o : c) { if (contains(o)) { Entry<?, ?> entry = (Entry<?, ?>) o; keys.add(entry.getKey()); } } return map().keySet().retainAll(keys); } } } }
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 javax.annotation.Nullable; /** * Static utility methods pertaining to object arrays. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class ObjectArrays { private ObjectArrays() {} /** * Returns a new array of the given length with the 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 prepends {@code element} to {@code array}. * * @param element the element to prepend to the front of {@code array} * @param array the array of elements to append * @return an array whose size is one larger than {@code array}, with * {@code element} occupying the first position, and the * elements of {@code array} occupying the remaining elements. */ public static <T> T[] concat(@Nullable T element, T[] array) { T[] result = newArray(array, array.length + 1); result[0] = element; Platform.unsafeArrayCopy(array, 0, result, 1, array.length); return result; } /** * Returns a new array that appends {@code element} to {@code array}. * * @param array the array of elements to prepend * @param element the element to append to the end * @return an array whose size is one larger than {@code array}, with * the same contents as {@code array}, plus {@code element} occupying the * last position. */ public static <T> T[] concat(T[] array, @Nullable T element) { T[] result = arraysCopyOf(array, array.length + 1); result[array.length] = element; return result; } /** GWT safe version of Arrays.copyOf. */ static <T> T[] arraysCopyOf(T[] original, int newLength) { T[] copy = newArray(original, newLength); Platform.unsafeArrayCopy( original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** * Returns an array containing all of the elements in the specified * collection; the runtime type of the returned array is that of the specified * array. If the collection fits in the specified array, it is returned * therein. Otherwise, a new array is allocated with the runtime type of the * specified array and the size of the specified collection. * * <p>If the collection fits in the specified array with room to spare (i.e., * the array has more elements than the collection), the element in the array * immediately following the end of the collection is set to {@code null}. * This is useful in determining the length of the collection <i>only</i> if * the caller knows that the collection does not contain any null elements. * * <p>This method returns the elements in the order they are returned by the * collection's iterator. * * <p>TODO(kevinb): support concurrently modified collections? * * @param c the collection for which to return an array of elements * @param array the array in which to place the collection elements * @throws ArrayStoreException if the runtime type of the specified array is * not a supertype of the runtime type of every element in the specified * collection */ static <T> T[] toArrayImpl(Collection<?> c, T[] array) { int size = c.size(); if (array.length < size) { array = newArray(array, size); } fillArray(c, array); if (array.length > size) { array[size] = null; } return array; } /** * Returns an array containing all of the elements in the specified * collection. This method returns the elements in the order they are returned * by the collection's iterator. The returned array is "safe" in that no * references to it are maintained by the collection. The caller is thus free * to modify the returned array. * * <p>This method assumes that the collection size doesn't change while the * method is running. * * <p>TODO(kevinb): support concurrently modified collections? * * @param c the collection for which to return an array of elements */ static Object[] toArrayImpl(Collection<?> c) { return fillArray(c, new Object[c.size()]); } private static Object[] fillArray(Iterable<?> elements, Object[] array) { int i = 0; for (Object element : elements) { array[i++] = element; } return array; } /** * Swaps {@code array[i]} with {@code array[j]}. */ static void swap(Object[] array, int i, int j) { Object temp = array[i]; array[i] = array[j]; array[j] = temp; } }
Java
/* * Copyright (C) 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.collect.Lists; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import javax.annotation.Nullable; /** * GWT emulated version of {@link ImmutableList}. * * @author Hayward Chan */ @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableList<E> extends ForwardingImmutableCollection<E> implements List<E>, RandomAccess { private transient final List<E> delegate; ImmutableList(List<E> delegate) { super(delegate); this.delegate = Collections.unmodifiableList(delegate); } ImmutableList() { this(Collections.<E>emptyList()); } // 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; } public static <E> ImmutableList<E> of(E element) { return new SingletonImmutableList<E>(element); } public static <E> ImmutableList<E> of(E e1, E e2) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7, e8)); } 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 new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7, e8, e9)); } 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 new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList( e1, e2, e3, e4, e5, e6, e7, e8, e9, e10)); } 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 new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList( e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11)); } 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) { final int paramCount = 12; Object[] array = new Object[paramCount + others.length]; arrayCopy(array, 0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12); arrayCopy(array, paramCount, others); return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(array)); } public static <E> ImmutableList<E> of(E[] elements) { checkNotNull(elements); // for GWT switch (elements.length) { case 0: return ImmutableList.of(); case 1: return new SingletonImmutableList<E>(elements[0]); default: return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(elements)); } } private static void arrayCopy(Object[] dest, int pos, Object... source) { System.arraycopy(source, 0, dest, pos, source.length); } public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) { checkNotNull(elements); // for GWT return (elements instanceof Collection) ? copyOf((Collection<? extends E>) elements) : copyOf(elements.iterator()); } public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) { return copyFromCollection(Lists.newArrayList(elements)); } public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) { if (elements instanceof ImmutableCollection) { /* * TODO: When given an ImmutableList that's a sublist, copy the referenced * portion of the array into a new array to save space? */ @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableCollection<E> list = (ImmutableCollection<E>) elements; return list.asList(); } return copyFromCollection(elements); } public static <E> ImmutableList<E> copyOf(E[] elements) { checkNotNull(elements); // eager for GWT return copyOf(Arrays.asList(elements)); } private static <E> ImmutableList<E> copyFromCollection( Collection<? extends E> collection) { Object[] elements = collection.toArray(); switch (elements.length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // collection had only Es in it ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]); return list; default: return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(elements)); } } // Factory method that skips the null checks. Used only when the elements // are guaranteed to be null. static <E> ImmutableList<E> unsafeDelegateList(List<? extends E> list) { switch (list.size()) { case 0: return of(); case 1: return new SingletonImmutableList<E>(list.iterator().next()); default: @SuppressWarnings("unchecked") List<E> castedList = (List<E>) list; return new RegularImmutableList<E>(castedList); } } static <E> ImmutableList<E> backedBy(E[] elements) { return unsafeDelegateList(Arrays.asList(elements)); } private static <E> List<E> nullCheckedList(Object... array) { for (int i = 0, len = array.length; i < len; i++) { if (array[i] == null) { throw new NullPointerException("at index " + i); } } @SuppressWarnings("unchecked") E[] castedArray = (E[]) array; return Arrays.asList(castedArray); } public int indexOf(@Nullable Object object) { return delegate.indexOf(object); } public int lastIndexOf(@Nullable Object object) { return delegate.lastIndexOf(object); } public final boolean addAll(int index, Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } public final E set(int index, E element) { throw new UnsupportedOperationException(); } public final void add(int index, E element) { throw new UnsupportedOperationException(); } public final E remove(int index) { throw new UnsupportedOperationException(); } public E get(int index) { return delegate.get(index); } public ImmutableList<E> subList(int fromIndex, int toIndex) { return unsafeDelegateList(delegate.subList(fromIndex, toIndex)); } public ListIterator<E> listIterator() { return delegate.listIterator(); } public ListIterator<E> listIterator(int index) { return delegate.listIterator(index); } @Override public ImmutableList<E> asList() { return this; } public ImmutableList<E> reverse(){ List<E> list = Lists.newArrayList(this); Collections.reverse(list); return unsafeDelegateList(list); } @Override public Object[] toArray() { // Note that ArrayList.toArray() doesn't work here because it returns E[] // instead of Object[]. return delegate.toArray(new Object[size()]); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public int hashCode() { return delegate.hashCode(); } public static <E> Builder<E> builder() { return new Builder<E>(); } public static final class Builder<E> extends ImmutableCollection.Builder<E> { private final ArrayList<E> contents = Lists.newArrayList(); public Builder() {} @Override public Builder<E> add(E element) { contents.add(checkNotNull(element)); return this; } @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } @Override public Builder<E> add(E... elements) { checkNotNull(elements); // for GWT super.add(elements); return this; } @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } @Override public ImmutableList<E> build() { return copyOf(contents); } } }
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 java.util.Collections; /** * GWT emulated version of {@link SingletonImmutableList}. * * @author Hayward Chan */ final class SingletonImmutableList<E> extends ImmutableList<E> { // This reference is used both by the custom field serializer, and by the // GWT compiler to infer the elements of the lists that needs to be // serialized. E element; SingletonImmutableList(E element) { super(Collections.singletonList(checkNotNull(element))); this.element = element; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@link Iterator}. Except as noted, each method has a corresponding * {@link Iterable}-based method in the {@link Iterables} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators * produced in this class are <i>lazy</i>, which means that they only advance * the backing iteration when absolutely necessary. * * <p>See the Guava User Guide section on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterators}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterators { private Iterators() {} static final UnmodifiableIterator<Object> EMPTY_ITERATOR = new UnmodifiableIterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } }; /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") public static <T> UnmodifiableIterator<T> emptyIterator() { return (UnmodifiableIterator<T>) EMPTY_ITERATOR; } private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } }; /** * Returns the empty {@code Iterator} that throws * {@link IllegalStateException} instead of * {@link UnsupportedOperationException} on a call to * {@link Iterator#remove()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> Iterator<T> emptyModifiableIterator() { return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR; } /** Returns an unmodifiable view of {@code iterator}. */ public static <T> UnmodifiableIterator<T> unmodifiableIterator( final Iterator<T> iterator) { checkNotNull(iterator); if (iterator instanceof UnmodifiableIterator) { return (UnmodifiableIterator<T>) iterator; } return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return iterator.next(); } }; } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator( UnmodifiableIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns the number of elements remaining in {@code iterator}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. */ public static int size(Iterator<?> iterator) { int count = 0; while (iterator.hasNext()) { iterator.next(); count++; } return count; } /** * Returns {@code true} if {@code iterator} contains {@code element}. */ public static boolean contains(Iterator<?> iterator, @Nullable Object element) { if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { return true; } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { return true; } } } return false; } /** * Traverses an iterator and removes every element that belongs to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterator} */ public static boolean removeAll( Iterator<?> removeFrom, Collection<?> elementsToRemove) { checkNotNull(elementsToRemove); boolean modified = false; while (removeFrom.hasNext()) { if (elementsToRemove.contains(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * Removes every element that satisfies the provided predicate from the * iterator. The iterator will be left exhausted: its {@code hasNext()} * method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterator * @since 2.0 */ public static <T> boolean removeIf( Iterator<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); boolean modified = false; while (removeFrom.hasNext()) { if (predicate.apply(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * Traverses an iterator and removes every element that does not belong to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterator} */ public static boolean retainAll( Iterator<?> removeFrom, Collection<?> elementsToRetain) { checkNotNull(elementsToRetain); boolean modified = false; while (removeFrom.hasNext()) { if (!elementsToRetain.contains(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * Determines whether two iterators contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterator1} * and {@code iterator2} contain the same number of elements and every element * of {@code iterator1} is equal to the corresponding element of * {@code iterator2}. * * <p>Note that this will modify the supplied iterators, since they will have * been advanced some number of elements forward. */ public static boolean elementsEqual( Iterator<?> iterator1, Iterator<?> iterator2) { while (iterator1.hasNext()) { if (!iterator2.hasNext()) { return false; } Object o1 = iterator1.next(); Object o2 = iterator2.next(); if (!Objects.equal(o1, o2)) { return false; } } return !iterator2.hasNext(); } /** * Returns a string representation of {@code iterator}, with the format * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. */ public static String toString(Iterator<?> iterator) { if (!iterator.hasNext()) { return "[]"; } StringBuilder builder = new StringBuilder(); builder.append('[').append(iterator.next()); while (iterator.hasNext()) { builder.append(", ").append(iterator.next()); } return builder.append(']').toString(); } /** * Returns the single element contained in {@code iterator}. * * @throws NoSuchElementException if the iterator is empty * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ public static <T> T getOnlyElement(Iterator<T> iterator) { T first = iterator.next(); if (!iterator.hasNext()) { return first; } StringBuilder sb = new StringBuilder(); sb.append("expected one element but was: <" + first); for (int i = 0; i < 4 && iterator.hasNext(); i++) { sb.append(", " + iterator.next()); } if (iterator.hasNext()) { sb.append(", ..."); } sb.append('>'); throw new IllegalArgumentException(sb.toString()); } /** * Returns the single element contained in {@code iterator}, or {@code * defaultValue} if the iterator is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ public static <T> T getOnlyElement( Iterator<T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; } /** * Adds all elements in {@code iterator} to {@code collection}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @return {@code true} if {@code collection} was modified as a result of this * operation */ public static <T> boolean addAll( Collection<T> addTo, Iterator<? extends T> iterator) { checkNotNull(addTo); boolean wasModified = false; while (iterator.hasNext()) { wasModified |= addTo.add(iterator.next()); } return wasModified; } /** * Returns the number of elements in the specified iterator that equal the * specified object. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @see Collections#frequency */ public static int frequency(Iterator<?> iterator, @Nullable Object element) { int result = 0; if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { result++; } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { result++; } } } return result; } /** * Returns an iterator that cycles indefinitely over the elements of {@code * iterable}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After {@code remove()} is called, subsequent cycles omit the removed * element, which is no longer in {@code iterable}. The iterator's * {@code hasNext()} method returns {@code true} until {@code iterable} is * empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. */ public static <T> Iterator<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new Iterator<T>() { Iterator<T> iterator = emptyIterator(); Iterator<T> removeFrom; @Override public boolean hasNext() { if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = iterator; return iterator.next(); } @Override public void remove() { checkState(removeFrom != null, "no calls to next() since last call to remove()"); removeFrom.remove(); removeFrom = null; } }; } /** * Returns an iterator that cycles indefinitely over the provided elements. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After {@code remove()} is called, subsequent cycles omit the removed * element, but {@code elements} does not change. The iterator's * {@code hasNext()} method returns {@code true} until all of the original * elements have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. */ public static <T> Iterator<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. */ @SuppressWarnings("unchecked") public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) { checkNotNull(a); checkNotNull(b); return concat(Arrays.asList(a, b).iterator()); } /** * Combines three iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}. The source iterators * are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. */ @SuppressWarnings("unchecked") public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) { checkNotNull(a); checkNotNull(b); checkNotNull(c); return concat(Arrays.asList(a, b, c).iterator()); } /** * Combines four iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}, followed by the elements * in {@code d}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. */ @SuppressWarnings("unchecked") public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) { checkNotNull(a); checkNotNull(b); checkNotNull(c); checkNotNull(d); return concat(Arrays.asList(a, b, c, d).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * @throws NullPointerException if any of the provided iterators is null */ public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. The methods of the returned iterator may throw * {@code NullPointerException} if any of the input iterators is null. */ public static <T> Iterator<T> concat( final Iterator<? extends Iterator<? extends T>> inputs) { checkNotNull(inputs); return new Iterator<T>() { Iterator<? extends T> current = emptyIterator(); Iterator<? extends T> removeFrom; @Override public boolean hasNext() { // http://code.google.com/p/google-collections/issues/detail?id=151 // current.hasNext() might be relatively expensive, worth minimizing. boolean currentHasNext; // checkNotNull eager for GWT // note: it must be here & not where 'current' is assigned, // because otherwise we'll have called inputs.next() before throwing // the first NPE, and the next time around we'll call inputs.next() // again, incorrectly moving beyond the error. while (!(currentHasNext = checkNotNull(current).hasNext()) && inputs.hasNext()) { current = inputs.next(); } return currentHasNext; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = current; return current.next(); } @Override public void remove() { checkState(removeFrom != null, "no calls to next() since last call to remove()"); removeFrom.remove(); removeFrom = null; } }; } /** * Divides an iterator into unmodifiable sublists of the given size (the final * list may be smaller). For example, partitioning an iterator containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of * three and two elements, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> partition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, false); } /** * Divides an iterator into unmodifiable sublists of the given size, padding * the final iterator with null values if necessary. For example, partitioning * an iterator containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing * two inner lists of three elements each, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> paddedPartition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, true); } private static <T> UnmodifiableIterator<List<T>> partitionImpl( final Iterator<T> iterator, final int size, final boolean pad) { checkNotNull(iterator); checkArgument(size > 0); return new UnmodifiableIterator<List<T>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public List<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } Object[] array = new Object[size]; int count = 0; for (; count < size && iterator.hasNext(); count++) { array[count] = iterator.next(); } for (int i = count; i < size; i++) { array[i] = null; // for GWT } @SuppressWarnings("unchecked") // we only put Ts in it List<T> list = Collections.unmodifiableList( (List<T>) Arrays.asList(array)); return (pad || count == size) ? list : list.subList(0, count); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. */ public static <T> UnmodifiableIterator<T> filter( final Iterator<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new AbstractIterator<T>() { @Override protected T computeNext() { while (unfiltered.hasNext()) { T element = unfiltered.next(); if (predicate.apply(element)) { return element; } } return endOfData(); } }; } /** * Returns {@code true} if one or more elements returned by {@code iterator} * satisfy the given predicate. */ public static <T> boolean any( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate); while (iterator.hasNext()) { T element = iterator.next(); if (predicate.apply(element)) { return true; } } return false; } /** * Returns {@code true} if every element returned by {@code iterator} * satisfies the given predicate. If {@code iterator} is empty, {@code true} * is returned. */ public static <T> boolean all( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate); while (iterator.hasNext()) { T element = iterator.next(); if (!predicate.apply(element)) { return false; } } return true; } /** * Returns the first element in {@code iterator} that satisfies the given * predicate; use this method only when such an element is known to exist. If * no such element is found, the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. If it is possible that * <i>no</i> element will match, use {@link #tryFind)} or {@link * #find(Iterator, Predicate, T)} instead. * * @throws NoSuchElementException if no element in {@code iterator} matches * the given predicate */ public static <T> T find( Iterator<T> iterator, Predicate<? super T> predicate) { return filter(iterator, predicate).next(); } /** * Returns the first element in {@code iterator} that satisfies the given * predicate. If no such element is found, {@code defaultValue} will be * returned from this method and the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Note that this can * usually be handled more naturally using {@code * tryFind(iterator, predicate).or(defaultValue)}. * * @since 7.0 */ public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? filteredIterator.next() : defaultValue; } /** * Returns an {@link Optional} containing the first element in {@code * iterator} that satisfies the given predicate, if such an element exists. If * no such element is found, an empty {@link Optional} will be returned from * this method and the the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code * null}. If {@code null} is matched in {@code iterator}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind( Iterator<T> iterator, Predicate<? super T> predicate) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.<T>absent(); } /** * Returns the index in {@code iterator} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterator has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true}, * or {@code -1} if there is no such index. * * <p>If -1 is returned, the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Otherwise, * the iterator will be set to the element which satisfies the * {@code predicate}. * * @since 2.0 */ public static <T> int indexOf( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate, "predicate"); int i = 0; while (iterator.hasNext()) { T current = iterator.next(); if (predicate.apply(current)) { return i; } i++; } return -1; } /** * Returns an iterator that applies {@code function} to each element of {@code * fromIterator}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After a successful {@code remove()} call, {@code fromIterator} no * longer contains the corresponding element. */ public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) { checkNotNull(fromIterator); checkNotNull(function); return new Iterator<T>() { @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public T next() { F from = fromIterator.next(); return function.apply(from); } @Override public void remove() { fromIterator.remove(); } }; } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position. * * @param position position of the element to return * @return the element at the specified position in {@code iterator} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the number of elements remaining in * {@code iterator} */ public static <T> T get(Iterator<T> iterator, int position) { checkNonnegative(position); int skipped = 0; while (iterator.hasNext()) { T t = iterator.next(); if (skipped++ == position) { return t; } } throw new IndexOutOfBoundsException("position (" + position + ") must be less than the number of elements that remained (" + skipped + ")"); } private static void checkNonnegative(int position) { if (position < 0) { throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); } } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position or {@code defaultValue} * otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if the iterator is empty * or if {@code position} is greater than the number of elements * remaining in {@code iterator} * @return the element at the specified position in {@code iterator} or * {@code defaultValue} if {@code iterator} produces fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ public static <T> T get(Iterator<T> iterator, int position, @Nullable T defaultValue) { checkNonnegative(position); try { return get(iterator, position); } catch (IndexOutOfBoundsException e) { return defaultValue; } } /** * Returns the next element in {@code iterator} or {@code defaultValue} if * the iterator is empty. The {@link Iterables} analog to this method is * {@link Iterables#getFirst}. * * @param defaultValue the default value to return if the iterator is empty * @return the next element of {@code iterator} or the default value * @since 7.0 */ public static <T> T getNext(Iterator<T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? iterator.next() : defaultValue; } /** * Advances {@code iterator} to the end, returning the last element. * * @return the last element of {@code iterator} * @throws NoSuchElementException if the iterator is empty */ public static <T> T getLast(Iterator<T> iterator) { while (true) { T current = iterator.next(); if (!iterator.hasNext()) { return current; } } } /** * Advances {@code iterator} to the end, returning the last element or * {@code defaultValue} if the iterator is empty. * * @param defaultValue the default value to return if the iterator is empty * @return the last element of {@code iterator} * @since 3.0 */ public static <T> T getLast(Iterator<T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getLast(iterator) : defaultValue; } /** * Calls {@code next()} on {@code iterator}, either {@code numberToSkip} times * or until {@code hasNext()} returns {@code false}, whichever comes first. * * @return the number of elements skipped * @since 3.0 */ @Beta public static <T> int skip(Iterator<T> iterator, int numberToSkip) { checkNotNull(iterator); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); int i; for (i = 0; i < numberToSkip && iterator.hasNext(); i++) { iterator.next(); } return i; } /** * Creates an iterator returning the first {@code limitSize} elements of the * given iterator. If the original iterator does not contain that many * elements, the returned iterator will have the same behavior as the original * iterator. The returned iterator supports {@code remove()} if the original * iterator does. * * @param iterator the iterator to limit * @param limitSize the maximum number of elements in the returned iterator * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterator<T> limit( final Iterator<T> iterator, final int limitSize) { checkNotNull(iterator); checkArgument(limitSize >= 0, "limit is negative"); return new Iterator<T>() { private int count; @Override public boolean hasNext() { return count < limitSize && iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } /** * Returns a view of the supplied {@code iterator} that removes each element * from the supplied {@code iterator} as it is returned. * * <p>The provided iterator must support {@link Iterator#remove()} or * else the returned iterator will fail on the first call to {@code * next}. * * @param iterator the iterator to remove and return elements from * @return an iterator that removes and returns elements from the * supplied iterator * @since 2.0 */ public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) { checkNotNull(iterator); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T next = iterator.next(); iterator.remove(); return next; } }; } // Methods only in Iterators, not in Iterables /** * Clears the iterator using its remove method. */ static void clear(Iterator<?> iterator) { checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } /** * Returns an iterator containing the elements of {@code array} in order. The * returned iterator is a view of the array; subsequent changes to the array * will be reflected in the iterator. * * <p><b>Note:</b> It is often preferable to represent your data using a * collection type, for example using {@link Arrays#asList(Object[])}, making * this method unnecessary. * * <p>The {@code Iterable} equivalent of this method is either {@link * Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}}, * or {@link ImmutableList#of}. */ public static <T> UnmodifiableIterator<T> forArray(final T... array) { // TODO(kevinb): compare performance with Arrays.asList(array).iterator(). checkNotNull(array); // eager for GWT. return new AbstractIndexedListIterator<T>(array.length) { @Override protected T get(int index) { return array[index]; } }; } /** * Returns an iterator containing the elements in the specified range of * {@code array} in order. The returned iterator is a view of the array; * subsequent changes to the array will be reflected in the iterator. * * <p>The {@code Iterable} equivalent of this method is {@code * Arrays.asList(array).subList(offset, offset + length)}. * * @param array array to read elements out of * @param offset index of first array element to retrieve * @param length number of elements in iteration * @throws IndexOutOfBoundsException if {@code offset} is negative, {@code * length} is negative, or {@code offset + length > array.length} */ static <T> UnmodifiableIterator<T> forArray( final T[] array, final int offset, int length) { checkArgument(length >= 0); int end = offset + length; // Technically we should give a slightly more descriptive error on overflow Preconditions.checkPositionIndexes(offset, end, array.length); /* * We can't use call the two-arg constructor with arguments (offset, end) * because the returned Iterator is a ListIterator that may be moved back * past the beginning of the iteration. */ return new AbstractIndexedListIterator<T>(length) { @Override protected T get(int index) { return array[offset + index]; } }; } /** * Returns an iterator containing only {@code value}. * * <p>The {@link Iterable} equivalent of this method is {@link * Collections#singleton}. */ public static <T> UnmodifiableIterator<T> singletonIterator( @Nullable final T value) { return new UnmodifiableIterator<T>() { boolean done; @Override public boolean hasNext() { return !done; } @Override public T next() { if (done) { throw new NoSuchElementException(); } done = true; return value; } }; } /** * Adapts an {@code Enumeration} to the {@code Iterator} interface. * * <p>This method has no equivalent in {@link Iterables} because viewing an * {@code Enumeration} as an {@code Iterable} is impossible. However, the * contents can be <i>copied</i> into a collection using {@link * Collections#list}. */ public static <T> UnmodifiableIterator<T> forEnumeration( final Enumeration<T> enumeration) { checkNotNull(enumeration); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public T next() { return enumeration.nextElement(); } }; } /** * Adapts an {@code Iterator} to the {@code Enumeration} interface. * * <p>The {@code Iterable} equivalent of this method is either {@link * Collections#enumeration} (if you have a {@link Collection}), or * {@code Iterators.asEnumeration(collection.iterator())}. */ public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) { checkNotNull(iterator); return new Enumeration<T>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public T nextElement() { return iterator.next(); } }; } /** * Implementation of PeekingIterator that avoids peeking unless necessary. */ private static class PeekingImpl<E> implements PeekingIterator<E> { private final Iterator<? extends E> iterator; private boolean hasPeeked; private E peekedElement; public PeekingImpl(Iterator<? extends E> iterator) { this.iterator = checkNotNull(iterator); } @Override public boolean hasNext() { return hasPeeked || iterator.hasNext(); } @Override public E next() { if (!hasPeeked) { return iterator.next(); } E result = peekedElement; hasPeeked = false; peekedElement = null; return result; } @Override public void remove() { checkState(!hasPeeked, "Can't remove after you've peeked at next"); iterator.remove(); } @Override public E peek() { if (!hasPeeked) { peekedElement = iterator.next(); hasPeeked = true; } return peekedElement; } } /** * Returns a {@code PeekingIterator} backed by the given iterator. * * <p>Calls to the {@code peek} method with no intervening calls to {@code * next} do not affect the iteration, and hence return the same object each * time. A subsequent call to {@code next} is guaranteed to return the same * object again. For example: <pre> {@code * * PeekingIterator<String> peekingIterator = * Iterators.peekingIterator(Iterators.forArray("a", "b")); * String a1 = peekingIterator.peek(); // returns "a" * String a2 = peekingIterator.peek(); // also returns "a" * String a3 = peekingIterator.next(); // also returns "a"}</pre> * * Any structural changes to the underlying iteration (aside from those * performed by the iterator's own {@link PeekingIterator#remove()} method) * will leave the iterator in an undefined state. * * <p>The returned iterator does not support removal after peeking, as * explained by {@link PeekingIterator#remove()}. * * <p>Note: If the given iterator is already a {@code PeekingIterator}, * it <i>might</i> be returned to the caller, although this is neither * guaranteed to occur nor required to be consistent. For example, this * method <i>might</i> choose to pass through recognized implementations of * {@code PeekingIterator} when the behavior of the implementation is * known to meet the contract guaranteed by this method. * * <p>There is no {@link Iterable} equivalent to this method, so use this * method to wrap each individual iterator as it is generated. * * @param iterator the backing iterator. The {@link PeekingIterator} assumes * ownership of this iterator, so users should cease making direct calls * to it after calling this method. * @return a peeking iterator backed by that iterator. Apart from the * additional {@link PeekingIterator#peek()} method, this iterator behaves * exactly the same as {@code iterator}. */ public static <T> PeekingIterator<T> peekingIterator( Iterator<? extends T> iterator) { if (iterator instanceof PeekingImpl) { // Safe to cast <? extends T> to <T> because PeekingImpl only uses T // covariantly (and cannot be subclassed to add non-covariant uses). @SuppressWarnings("unchecked") PeekingImpl<T> peeking = (PeekingImpl<T>) iterator; return peeking; } return new PeekingImpl<T>(iterator); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> PeekingIterator<T> peekingIterator( PeekingIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns an iterator over the merged contents of all given * {@code iterators}, traversing every element of the input iterators. * Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterators} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterators}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> UnmodifiableIterator<T> mergeSorted( Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) { checkNotNull(iterators, "iterators"); checkNotNull(comparator, "comparator"); return new MergingIterator<T>(iterators, comparator); } /** * An iterator that performs a lazy N-way merge, calculating the next value * each time the iterator is polled. This amortizes the sorting cost over the * iteration and requires less memory than sorting all elements at once. * * <p>Retrieving a single element takes approximately O(log(M)) time, where M * is the number of iterators. (Retrieving all elements takes approximately * O(N*log(M)) time, where N is the total number of elements.) */ private static class MergingIterator<T> extends AbstractIterator<T> { final Queue<PeekingIterator<T>> queue; final Comparator<? super T> comparator; public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> itemComparator) { this.comparator = itemComparator; // A comparator that's used by the heap, allowing the heap // to be sorted based on the top of each iterator. Comparator<PeekingIterator<T>> heapComparator = new Comparator<PeekingIterator<T>>() { @Override public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) { return comparator.compare(o1.peek(), o2.peek()); } }; queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator); for (Iterator<? extends T> iterator : iterators) { if (iterator.hasNext()) { queue.add(Iterators.peekingIterator(iterator)); } } } @Override protected T computeNext() { if (queue.isEmpty()) { return endOfData(); } PeekingIterator<T> nextIter = queue.poll(); T next = nextIter.next(); if (nextIter.hasNext()) { queue.add(nextIter); } return next; } } }
Java
/* * Copyright (C) 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 java.util.Collections; import java.util.Map; /** * GWT emulation of {@link ImmutableBiMap}. * * @author Hayward Chan */ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K,V> implements BiMap<K, V> { private static final ImmutableBiMap<Object, Object> EMPTY_IMMUTABLE_BIMAP = new EmptyBiMap(); // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableBiMap<K, V> of() { return (ImmutableBiMap<K, V>) EMPTY_IMMUTABLE_BIMAP; } public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of(k1, v1)); } public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of(k1, v1, k2, v2)); } public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of( k1, v1, k2, v2, k3, v3)); } public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of( k1, v1, k2, v2, k3, v3, k4, v4)); } public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of( k1, v1, k2, v2, k3, v3, k4, v4, k5, v5)); } public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { public Builder() {} @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } @Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { super.putAll(map); return this; } @Override public ImmutableBiMap<K, V> build() { ImmutableMap<K, V> map = super.build(); if (map.isEmpty()) { return of(); } return new RegularImmutableBiMap<K, V>(super.build()); } } public static <K, V> ImmutableBiMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if (map instanceof ImmutableBiMap) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; return bimap; } if (map.isEmpty()) { return of(); } ImmutableMap<K, V> immutableMap = ImmutableMap.copyOf(map); return new RegularImmutableBiMap<K, V>(immutableMap); } ImmutableBiMap(Map<K, V> delegate) { super(delegate); } public abstract ImmutableBiMap<V, K> inverse(); @Override public ImmutableSet<V> values() { return inverse().keySet(); } public final V forcePut(K key, V value) { throw new UnsupportedOperationException(); } @SuppressWarnings("serial") static class EmptyBiMap extends ImmutableBiMap<Object, Object> { EmptyBiMap() { super(Collections.emptyMap()); } @Override public ImmutableBiMap<Object, Object> inverse() { return 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 static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.getOnlyElement; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * GWT emulation of {@link ImmutableMap}. For non sorted maps, it is a thin * wrapper around {@link java.util.Collections#emptyMap()}, {@link * Collections#singletonMap(Object, Object)} and {@link java.util.LinkedHashMap} * for empty, singleton and regular maps respectively. For sorted maps, it's * a thin wrapper around {@link java.util.TreeMap}. * * @see ImmutableSortedMap * * @author Hayward Chan */ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable { private transient final Map<K, V> delegate; ImmutableMap() { this.delegate = Collections.emptyMap(); } ImmutableMap(Map<? extends K, ? extends V> delegate) { this.delegate = Collections.unmodifiableMap(delegate); } @SuppressWarnings("unchecked") ImmutableMap(Entry<? extends K, ? extends V>... entries) { Map<K, V> delegate = Maps.newLinkedHashMap(); for (Entry<? extends K, ? extends V> entry : entries) { K key = checkNotNull(entry.getKey()); V previous = delegate.put(key, checkNotNull(entry.getValue())); if (previous != null) { throw new IllegalArgumentException("duplicate key: " + key); } } this.delegate = Collections.unmodifiableMap(delegate); } // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableMap<K, V> of() { return (ImmutableMap<K, V>) EmptyImmutableMap.INSTANCE; } public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { return new SingletonImmutableMap<K, V>( checkNotNull(k1), checkNotNull(v1)); } public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2)); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } // looking for of() with > 5 entries? Use the builder instead. public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } static <K, V> Entry<K, V> entryOf(K key, V value) { return Maps.immutableEntry(checkNotNull(key), checkNotNull(value)); } public static class Builder<K, V> { final List<Entry<K, V>> entries = Lists.newArrayList(); public Builder() {} public Builder<K, V> put(K key, V value) { entries.add(entryOf(key, value)); return this; } public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { if (entry instanceof ImmutableEntry<?, ?>) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); @SuppressWarnings("unchecked") // all supported methods are covariant Entry<K, V> immutableEntry = (Entry<K, V>) entry; entries.add(immutableEntry); } else { entries.add(entryOf((K) entry.getKey(), (V) entry.getValue())); } return this; } 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; } public ImmutableMap<K, V> build() { return fromEntryList(entries); } private static <K, V> ImmutableMap<K, V> fromEntryList( List<Entry<K, V>> entries) { int size = entries.size(); switch (size) { case 0: return of(); case 1: Entry<K, V> entry = getOnlyElement(entries); return new SingletonImmutableMap<K, V>( entry.getKey(), entry.getValue()); default: @SuppressWarnings("unchecked") Entry<K, V>[] entryArray = entries.toArray(new Entry[entries.size()]); return new RegularImmutableMap<K, V>(entryArray); } } } public static <K, V> ImmutableMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map; return kvMap; } int size = map.size(); switch (size) { case 0: return of(); case 1: Entry<? extends K, ? extends V> entry = getOnlyElement(map.entrySet()); return ImmutableMap.<K, V>of(entry.getKey(), entry.getValue()); default: Map<K, V> orderPreservingCopy = Maps.newLinkedHashMap(); for (Entry<? extends K, ? extends V> e : map.entrySet()) { orderPreservingCopy.put( checkNotNull(e.getKey()), checkNotNull(e.getValue())); } return new RegularImmutableMap<K, V>(orderPreservingCopy); } } boolean isPartialView(){ return false; } public final V put(K k, V v) { throw new UnsupportedOperationException(); } public final V remove(Object o) { throw new UnsupportedOperationException(); } public final void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(); } public final void clear() { throw new UnsupportedOperationException(); } public final boolean isEmpty() { return delegate.isEmpty(); } public final boolean containsKey(@Nullable Object key) { return Maps.safeContainsKey(delegate, key); } public final boolean containsValue(@Nullable Object value) { return delegate.containsValue(value); } public final V get(@Nullable Object key) { return (key == null) ? null : Maps.safeGet(delegate, key); } private transient ImmutableSet<Entry<K, V>> cachedEntrySet = null; public final ImmutableSet<Entry<K, V>> entrySet() { if (cachedEntrySet != null) { return cachedEntrySet; } return cachedEntrySet = ImmutableSet.unsafeDelegate( new ForwardingSet<Entry<K, V>>() { @Override protected Set<Entry<K, V>> delegate() { return delegate.entrySet(); } @Override public boolean contains(Object object) { if (object instanceof Entry<?, ?> && ((Entry<?, ?>) object).getKey() == null) { return false; } try { return super.contains(object); } catch (ClassCastException e) { return false; } } @Override public <T> T[] toArray(T[] array) { T[] result = super.toArray(array); if (size() < result.length) { // It works around a GWT bug where elements after last is not // properly null'ed. result[size()] = null; } return result; } }); } private transient ImmutableSet<K> cachedKeySet = null; public ImmutableSet<K> keySet() { if (cachedKeySet != null) { return cachedKeySet; } return cachedKeySet = ImmutableSet.unsafeDelegate(delegate.keySet()); } private transient ImmutableCollection<V> cachedValues = null; public ImmutableCollection<V> values() { if (cachedValues != null) { return cachedValues; } return cachedValues = ImmutableCollection.unsafeDelegate(delegate.values()); } public int size() { return delegate.size(); } @Override public boolean equals(@Nullable Object object) { return delegate.equals(object); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.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 com.google.common.base.Function; import com.google.gwt.user.client.Timer; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; /** * MapMaker emulation. Since Javascript is single-threaded and have no references, this reduces to * the creation of expiring and computing maps. * * @author Charles Fry */ public class MapMaker extends GenericMapMaker<Object, Object> { // TODO(fry,user): ConcurrentHashMap never throws a CME when mutating the map during iteration, but // this implementation (based on a LHM) does. This will all be replaced soon anyways, so leaving // it as is for now. private static class ExpiringComputingMap<K, V> extends LinkedHashMap<K, V> implements ConcurrentMap<K, V> { private final long expirationMillis; private final Function<? super K, ? extends V> computer; private final int maximumSize; ExpiringComputingMap(long expirationMillis, int maximumSize, int initialCapacity, float loadFactor) { this(expirationMillis, null, maximumSize, initialCapacity, loadFactor); } ExpiringComputingMap(long expirationMillis, Function<? super K, ? extends V> computer, int maximumSize, int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor, (maximumSize != -1)); this.expirationMillis = expirationMillis; this.computer = computer; this.maximumSize = maximumSize; } @Override public V put(K key, V value) { V result = super.put(key, value); if (expirationMillis > 0) { scheduleRemoval(key, value); } return result; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> ignored) { return (maximumSize == -1) ? false : size() > maximumSize; } @Override public V putIfAbsent(K key, V value) { if (!containsKey(key)) { return put(key, value); } else { return get(key); } } @Override public boolean remove(Object key, Object value) { if (containsKey(key) && get(key).equals(value)) { remove(key); return true; } return false; } @Override public boolean replace(K key, V oldValue, V newValue) { if (containsKey(key) && get(key).equals(oldValue)) { put(key, newValue); return true; } return false; } @Override public V replace(K key, V value) { return containsKey(key) ? put(key, value) : null; } private void scheduleRemoval(final K key, final V value) { // from MapMaker /* * TODO: Keep weak reference to map, too. Build a priority queue out of the entries themselves * instead of creating a task per entry. Then, we could have one recurring task per map (which * would clean the entire map and then reschedule itself depending upon when the next * expiration comes). We also want to avoid removing an entry prematurely if the entry was set * to the same value again. */ Timer timer = new Timer() { @Override public void run() { remove(key, value); } }; timer.schedule((int) expirationMillis); } @Override public V get(Object k) { // from CustomConcurrentHashMap V result = super.get(k); if (result == null && computer != null) { /* * This cast isn't safe, but we can rely on the fact that K is almost always passed to * Map.get(), and tools like IDEs and Findbugs can catch situations where this isn't the * case. * * The alternative is to add an overloaded method, but the chances of a user calling get() * instead of the new API and the risks inherent in adding a new API outweigh this little * hole. */ @SuppressWarnings("unchecked") K key = (K) k; result = compute(key); } return result; } private V compute(K key) { // from MapMaker V value; try { value = computer.apply(key); } catch (Throwable t) { throw new ComputationException(t); } if (value == null) { String message = computer + " returned null for key " + key + "."; throw new NullPointerException(message); } put(key, value); return value; } } private int initialCapacity = 16; private float loadFactor = 0.75f; private long expirationMillis = 0; private int maximumSize = -1; private boolean useCustomMap; public MapMaker() {} @Override public MapMaker initialCapacity(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException(); } this.initialCapacity = initialCapacity; return this; } public MapMaker loadFactor(float loadFactor) { if (loadFactor <= 0) { throw new IllegalArgumentException(); } this.loadFactor = loadFactor; return this; } @Override public MapMaker expiration(long duration, TimeUnit unit) { return expireAfterWrite(duration, unit); } @Override MapMaker expireAfterWrite(long duration, TimeUnit unit) { if (expirationMillis != 0) { throw new IllegalStateException( "expiration time of " + expirationMillis + " ns was already set"); } if (duration <= 0) { throw new IllegalArgumentException("invalid duration: " + duration); } this.expirationMillis = unit.toMillis(duration); useCustomMap = true; return this; } @Override MapMaker maximumSize(int maximumSize) { if (this.maximumSize != -1) { throw new IllegalStateException("maximum size of " + maximumSize + " was already set"); } if (maximumSize < 0) { throw new IllegalArgumentException("invalid maximum size: " + maximumSize); } this.maximumSize = maximumSize; useCustomMap = true; return this; } @Override public MapMaker concurrencyLevel(int concurrencyLevel) { if (concurrencyLevel < 1) { throw new IllegalArgumentException("GWT only supports a concurrency level of 1"); } // GWT technically only supports concurrencyLevel == 1, but we silently // ignore other positive values. return this; } @Override MapMaker strongKeys() { return this; } @Override MapMaker strongValues() { return this; } @Override public <K, V> ConcurrentMap<K, V> makeMap() { return useCustomMap ? new ExpiringComputingMap<K, V>(expirationMillis, null, maximumSize, initialCapacity, loadFactor) : new ConcurrentHashMap<K, V>(initialCapacity, loadFactor); } @Override public <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computer) { return new ExpiringComputingMap<K, V>(expirationMillis, computer, maximumSize, initialCapacity, loadFactor); } }
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 java.util.Collection; import java.util.Comparator; import java.util.Map.Entry; import javax.annotation.Nullable; /** * An immutable {@link ListMultimap} with reliable user-specified key and value * iteration order. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableListMultimap(ListMultimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableListMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableListMultimap} is convenient for * {@code public static final} multimaps ("constant multimaps") and also lets * you easily make a "defensive copy" of a multimap provided to your class by * a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this class * are guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V> implements ListMultimap<K, V> { /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableListMultimap<K, V> of() { return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE; } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); builder.put(k5, v5); return builder.build(); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * A builder for creating immutable {@code ListMultimap} instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableListMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableListMultimap#builder}. */ public Builder() {} @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } /** * {@inheritDoc} * * @since 11.0 */ @Override public Builder<K, V> put( Entry<? extends K, ? extends V> entry) { super.put(entry); return this; } @Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) { super.putAll(key, values); return this; } @Override public Builder<K, V> putAll(K key, V... values) { super.putAll(key, values); return this; } @Override public Builder<K, V> putAll( Multimap<? extends K, ? extends V> multimap) { super.putAll(multimap); return this; } /** * {@inheritDoc} * * @since 8.0 */ @Beta @Override public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { super.orderKeysBy(keyComparator); return this; } /** * {@inheritDoc} * * @since 8.0 */ @Beta @Override public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { super.orderValuesBy(valueComparator); return this; } /** * Returns a newly-created immutable list multimap. */ @Override public ImmutableListMultimap<K, V> build() { return (ImmutableListMultimap<K, V>) super.build(); } } /** * Returns an immutable multimap containing the same mappings as {@code * multimap}. The generated multimap's key and value orderings correspond to * the iteration ordering of the {@code multimap.asMap()} view. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws NullPointerException if any key or value in {@code multimap} is * null */ public static <K, V> ImmutableListMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { if (multimap.isEmpty()) { return of(); } // TODO(user): copy ImmutableSetMultimap by using asList() on the sets if (multimap instanceof ImmutableListMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder(); int size = 0; for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { ImmutableList<V> list = ImmutableList.copyOf(entry.getValue()); if (!list.isEmpty()) { builder.put(entry.getKey(), list); size += list.size(); } } return new ImmutableListMultimap<K, V>(builder.build(), size); } ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) { super(map, size); } // views /** * Returns an immutable list of the values for the given key. If no mappings * in the multimap have the provided key, an empty immutable list is * returned. The values are in the same order as the parameters used to build * this multimap. */ @Override public ImmutableList<V> get(@Nullable K key) { // This cast is safe as its type is known in constructor. ImmutableList<V> list = (ImmutableList<V>) map.get(key); return (list == null) ? ImmutableList.<V>of() : list; } private transient ImmutableListMultimap<V, K> inverse; /** * {@inheritDoc} * * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and * value, this method returns an {@code ImmutableListMultimap} rather than the * {@code ImmutableMultimap} specified in the {@code ImmutableMultimap} class. * * @since 11 */ @Beta public ImmutableListMultimap<V, K> inverse() { ImmutableListMultimap<V, K> result = inverse; return (result == null) ? (inverse = invert()) : result; } private ImmutableListMultimap<V, K> invert() { Builder<V, K> builder = builder(); for (Entry<K, V> entry : entries()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableListMultimap<V, K> invertedMultimap = builder.build(); invertedMultimap.inverse = this; return invertedMultimap; } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public ImmutableList<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public ImmutableList<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } }
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.VisibleForTesting; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.Nullable; /** * Synchronized collection views. The returned synchronized collection views are * serializable if the backing collection and the mutex are serializable. * * <p>If {@code null} is passed as the {@code mutex} parameter to any of this * class's top-level methods or inner class constructors, the created object * uses itself as the synchronization mutex. * * <p>This class should be used by other collection classes only. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) final class Synchronized { private Synchronized() {} static class SynchronizedObject implements Serializable { final Object delegate; final Object mutex; SynchronizedObject(Object delegate, @Nullable Object mutex) { this.delegate = checkNotNull(delegate); this.mutex = (mutex == null) ? this : mutex; } Object delegate() { return delegate; } // No equals and hashCode; see ForwardingObject for details. @Override public String toString() { synchronized (mutex) { return delegate.toString(); } } // Serialization invokes writeObject only when it's private. // The SynchronizedObject subclasses don't need a writeObject method since // they don't contain any non-transient member variables, while the // following writeObject() handles the SynchronizedObject members. } private static <E> Collection<E> collection( Collection<E> collection, @Nullable Object mutex) { return new SynchronizedCollection<E>(collection, mutex); } @VisibleForTesting static class SynchronizedCollection<E> extends SynchronizedObject implements Collection<E> { private SynchronizedCollection( Collection<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Collection<E> delegate() { return (Collection<E>) super.delegate(); } @Override public boolean add(E e) { synchronized (mutex) { return delegate().add(e); } } @Override public boolean addAll(Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(c); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean contains(Object o) { synchronized (mutex) { return delegate().contains(o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return delegate().containsAll(c); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Iterator<E> iterator() { return delegate().iterator(); // manually synchronized } @Override public boolean remove(Object o) { synchronized (mutex) { return delegate().remove(o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return delegate().removeAll(c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return delegate().retainAll(c); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Object[] toArray() { synchronized (mutex) { return delegate().toArray(); } } @Override public <T> T[] toArray(T[] a) { synchronized (mutex) { return delegate().toArray(a); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) { return new SynchronizedSet<E>(set, mutex); } static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { SynchronizedSet(Set<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Set<E> delegate() { return (Set<E>) super.delegate(); } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static <E> SortedSet<E> sortedSet( SortedSet<E> set, @Nullable Object mutex) { return new SynchronizedSortedSet<E>(set, mutex); } static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSet<E> delegate() { return (SortedSet<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return sortedSet(delegate().subSet(fromElement, toElement), mutex); } } @Override public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return sortedSet(delegate().headSet(toElement), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return sortedSet(delegate().tailSet(fromElement), mutex); } } @Override public E first() { synchronized (mutex) { return delegate().first(); } } @Override public E last() { synchronized (mutex) { return delegate().last(); } } private static final long serialVersionUID = 0; } private static <E> List<E> list(List<E> list, @Nullable Object mutex) { return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList<E>(list, mutex) : new SynchronizedList<E>(list, mutex); } private static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { SynchronizedList(List<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override List<E> delegate() { return (List<E>) super.delegate(); } @Override public void add(int index, E element) { synchronized (mutex) { delegate().add(index, element); } } @Override public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(index, c); } } @Override public E get(int index) { synchronized (mutex) { return delegate().get(index); } } @Override public int indexOf(Object o) { synchronized (mutex) { return delegate().indexOf(o); } } @Override public int lastIndexOf(Object o) { synchronized (mutex) { return delegate().lastIndexOf(o); } } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); // manually synchronized } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); // manually synchronized } @Override public E remove(int index) { synchronized (mutex) { return delegate().remove(index); } } @Override public E set(int index, E element) { synchronized (mutex) { return delegate().set(index, element); } } @Override public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return list(delegate().subList(fromIndex, toIndex), mutex); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) { super(list, mutex); } private static final long serialVersionUID = 0; } static <E> Multiset<E> multiset( Multiset<E> multiset, @Nullable Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<E>(multiset, mutex); } private static class SynchronizedMultiset<E> extends SynchronizedCollection<E> implements Multiset<E> { transient Set<E> elementSet; transient Set<Entry<E>> entrySet; SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Multiset<E> delegate() { return (Multiset<E>) super.delegate(); } @Override public int count(Object o) { synchronized (mutex) { return delegate().count(o); } } @Override public int add(E e, int n) { synchronized (mutex) { return delegate().add(e, n); } } @Override public int remove(Object o, int n) { synchronized (mutex) { return delegate().remove(o, n); } } @Override public int setCount(E element, int count) { synchronized (mutex) { return delegate().setCount(element, count); } } @Override public boolean setCount(E element, int oldCount, int newCount) { synchronized (mutex) { return delegate().setCount(element, oldCount, newCount); } } @Override public Set<E> elementSet() { synchronized (mutex) { if (elementSet == null) { elementSet = typePreservingSet(delegate().elementSet(), mutex); } return elementSet; } } @Override public Set<Entry<E>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = typePreservingSet(delegate().entrySet(), mutex); } return entrySet; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> Multimap<K, V> multimap( Multimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedMultimap || multimap instanceof ImmutableMultimap) { return multimap; } return new SynchronizedMultimap<K, V>(multimap, mutex); } private static class SynchronizedMultimap<K, V> extends SynchronizedObject implements Multimap<K, V> { transient Set<K> keySet; transient Collection<V> valuesCollection; transient Collection<Map.Entry<K, V>> entries; transient Map<K, Collection<V>> asMap; transient Multiset<K> keys; @SuppressWarnings("unchecked") @Override Multimap<K, V> delegate() { return (Multimap<K, V>) super.delegate(); } SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public boolean containsEntry(Object key, Object value) { synchronized (mutex) { return delegate().containsEntry(key, value); } } @Override public Collection<V> get(K key) { synchronized (mutex) { return typePreservingCollection(delegate().get(key), mutex); } } @Override public boolean put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public boolean putAll(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().putAll(key, values); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { synchronized (mutex) { return delegate().putAll(multimap); } } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public boolean remove(Object key, Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public Collection<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = typePreservingSet(delegate().keySet(), mutex); } return keySet; } } @Override public Collection<V> values() { synchronized (mutex) { if (valuesCollection == null) { valuesCollection = collection(delegate().values(), mutex); } return valuesCollection; } } @Override public Collection<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entries == null) { entries = typePreservingCollection(delegate().entries(), mutex); } return entries; } } @Override public Map<K, Collection<V>> asMap() { synchronized (mutex) { if (asMap == null) { asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex); } return asMap; } } @Override public Multiset<K> keys() { synchronized (mutex) { if (keys == null) { keys = multiset(delegate().keys(), mutex); } return keys; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> ListMultimap<K, V> listMultimap( ListMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedListMultimap || multimap instanceof ImmutableListMultimap) { return multimap; } return new SynchronizedListMultimap<K, V>(multimap, mutex); } private static class SynchronizedListMultimap<K, V> extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> { SynchronizedListMultimap( ListMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { synchronized (mutex) { return list(delegate().get(key), mutex); } } @Override public List<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } private static final long serialVersionUID = 0; } static <K, V> SetMultimap<K, V> setMultimap( SetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSetMultimap || multimap instanceof ImmutableSetMultimap) { return multimap; } return new SynchronizedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSetMultimap<K, V> extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> { transient Set<Map.Entry<K, V>> entrySet; SynchronizedSetMultimap( SetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { synchronized (mutex) { return set(delegate().get(key), mutex); } } @Override public Set<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Set<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entries(), mutex); } return entrySet; } } private static final long serialVersionUID = 0; } static <K, V> SortedSetMultimap<K, V> sortedSetMultimap( SortedSetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSortedSetMultimap) { return multimap; } return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSortedSetMultimap<K, V> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap( SortedSetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } private static final long serialVersionUID = 0; } private static <E> Collection<E> typePreservingCollection( Collection<E> collection, @Nullable Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E> Set<E> typePreservingSet( Set<E> set, @Nullable Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } private static class SynchronizedAsMapEntries<K, V> extends SynchronizedSet<Map.Entry<K, Collection<V>>> { SynchronizedAsMapEntries( Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { // Must be manually synchronized. final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator(); return new ForwardingIterator<Map.Entry<K, Collection<V>>>() { @Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() { return iterator; } @Override public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = iterator.next(); return new ForwardingMapEntry<K, Collection<V>>() { @Override protected Map.Entry<K, Collection<V>> delegate() { return entry; } @Override public Collection<V> getValue() { return typePreservingCollection(entry.getValue(), mutex); } }; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate()); } } @Override public <T> T[] toArray(T[] array) { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate(), array); } } @Override public boolean contains(Object o) { synchronized (mutex) { return Maps.containsEntryImpl(delegate(), o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return Collections2.containsAllImpl(delegate(), c); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return Sets.equalsImpl(delegate(), o); } } @Override public boolean remove(Object o) { synchronized (mutex) { return Maps.removeEntryImpl(delegate(), o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return Iterators.removeAll(delegate().iterator(), c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return Iterators.retainAll(delegate().iterator(), c); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <K, V> Map<K, V> map(Map<K, V> map, @Nullable Object mutex) { return new SynchronizedMap<K, V>(map, mutex); } private static class SynchronizedMap<K, V> extends SynchronizedObject implements Map<K, V> { transient Set<K> keySet; transient Collection<V> values; transient Set<Map.Entry<K, V>> entrySet; SynchronizedMap(Map<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Map<K, V> delegate() { return (Map<K, V>) super.delegate(); } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public Set<Map.Entry<K, V>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entrySet(), mutex); } return entrySet; } } @Override public V get(Object key) { synchronized (mutex) { return delegate().get(key); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = set(delegate().keySet(), mutex); } return keySet; } } @Override public V put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) { delegate().putAll(map); } } @Override public V remove(Object key) { synchronized (mutex) { return delegate().remove(key); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Collection<V> values() { synchronized (mutex) { if (values == null) { values = collection(delegate().values(), mutex); } return values; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> SortedMap<K, V> sortedMap( SortedMap<K, V> sortedMap, @Nullable Object mutex) { return new SynchronizedSortedMap<K, V>(sortedMap, mutex); } static class SynchronizedSortedMap<K, V> extends SynchronizedMap<K, V> implements SortedMap<K, V> { SynchronizedSortedMap(SortedMap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedMap<K, V> delegate() { return (SortedMap<K, V>) super.delegate(); } @Override public Comparator<? super K> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public K firstKey() { synchronized (mutex) { return delegate().firstKey(); } } @Override public SortedMap<K, V> headMap(K toKey) { synchronized (mutex) { return sortedMap(delegate().headMap(toKey), mutex); } } @Override public K lastKey() { synchronized (mutex) { return delegate().lastKey(); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { synchronized (mutex) { return sortedMap(delegate().subMap(fromKey, toKey), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { synchronized (mutex) { return sortedMap(delegate().tailMap(fromKey), mutex); } } private static final long serialVersionUID = 0; } static <K, V> BiMap<K, V> biMap(BiMap<K, V> bimap, @Nullable Object mutex) { if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { return bimap; } return new SynchronizedBiMap<K, V>(bimap, mutex, null); } @VisibleForTesting static class SynchronizedBiMap<K, V> extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable { private transient Set<V> valueSet; private transient BiMap<V, K> inverse; private SynchronizedBiMap(BiMap<K, V> delegate, @Nullable Object mutex, @Nullable BiMap<V, K> inverse) { super(delegate, mutex); this.inverse = inverse; } @Override BiMap<K, V> delegate() { return (BiMap<K, V>) super.delegate(); } @Override public Set<V> values() { synchronized (mutex) { if (valueSet == null) { valueSet = set(delegate().values(), mutex); } return valueSet; } } @Override public V forcePut(K key, V value) { synchronized (mutex) { return delegate().forcePut(key, value); } } @Override public BiMap<V, K> inverse() { synchronized (mutex) { if (inverse == null) { inverse = new SynchronizedBiMap<V, K>(delegate().inverse(), mutex, this); } return inverse; } } private static final long serialVersionUID = 0; } private static class SynchronizedAsMap<K, V> extends SynchronizedMap<K, Collection<V>> { transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet; transient Collection<Collection<V>> asMapValues; SynchronizedAsMap(Map<K, Collection<V>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Collection<V> get(Object key) { synchronized (mutex) { Collection<V> collection = super.get(key); return (collection == null) ? null : typePreservingCollection(collection, mutex); } } @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { synchronized (mutex) { if (asMapEntrySet == null) { asMapEntrySet = new SynchronizedAsMapEntries<K, V>( delegate().entrySet(), mutex); } return asMapEntrySet; } } @Override public Collection<Collection<V>> values() { synchronized (mutex) { if (asMapValues == null) { asMapValues = new SynchronizedAsMapValues<V>(delegate().values(), mutex); } return asMapValues; } } @Override public boolean containsValue(Object o) { // values() and its contains() method are both synchronized. return values().contains(o); } private static final long serialVersionUID = 0; } private static class SynchronizedAsMapValues<V> extends SynchronizedCollection<Collection<V>> { SynchronizedAsMapValues( Collection<Collection<V>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Collection<V>> iterator() { // Must be manually synchronized. final Iterator<Collection<V>> iterator = super.iterator(); return new ForwardingIterator<Collection<V>>() { @Override protected Iterator<Collection<V>> delegate() { return iterator; } @Override public Collection<V> next() { return typePreservingCollection(iterator.next(), mutex); } }; } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 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; /** * GWT emulation of {@link EmptyImmutableMap}. In GWT, it is a thin wrapper * around {@link java.util.Collections#emptyMap()}. * * @author Hayward Chan */ final class EmptyImmutableMap extends ImmutableMap<Object, Object> { static final EmptyImmutableMap INSTANCE = new EmptyImmutableMap(); }
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.util.EnumMap; import java.util.Map; import javax.annotation.Nullable; /** * A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and * a {@code HashMap} instance for values-to-keys. Null keys are not permitted, * but null values are. An {@code EnumHashBiMap} and its inverse are both * serializable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap"> * {@code BiMap}</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumHashBiMap<K extends Enum<K>, V> extends AbstractBiMap<K, V> { private transient Class<K> keyType; /** * Returns a new, empty {@code EnumHashBiMap} using the specified key type. * * @param keyType the key type */ public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Class<K> keyType) { return new EnumHashBiMap<K, V>(keyType); } /** * Constructs a new bimap with the same mappings as the specified map. If the * specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new * bimap has the same key type as the input bimap. Otherwise, the specified * map must contain at least one mapping, in order to determine the key type. * * @param map the map whose mappings are to be placed in this map * @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an * {@code EnumHashBiMap} instance and contains no mappings */ public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Map<K, ? extends V> map) { EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map)); bimap.putAll(map); return bimap; } private EnumHashBiMap(Class<K> keyType) { super(WellBehavedMap.wrap( new EnumMap<K, V>(keyType)), Maps.<V, K>newHashMapWithExpectedSize( keyType.getEnumConstants().length)); this.keyType = keyType; } // Overriding these three methods to show that values may be null (but not keys) @Override K checkKey(K key) { return checkNotNull(key); } @Override public V put(K key, @Nullable V value) { return super.put(key, value); } @Override public V forcePut(K key, @Nullable V value) { return super.forcePut(key, value); } /** Returns the associated key type. */ public Class<K> keyType() { return keyType; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.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.Serializable; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * Provides static methods acting on or generating a {@code Multimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multimaps"> * {@code Multimaps}</a>. * * @author Jared Levy * @author Robert Konigsberg * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Multimaps { private Multimaps() {} /** * Creates a new {@code Multimap} that uses the provided map and factory. It * can generate a multimap based on arbitrary {@link Map} and * {@link Collection} classes. * * <p>The {@code factory}-generated and {@code map} classes determine the * multimap iteration order. They also specify the behavior of the * {@code equals}, {@code hashCode}, and {@code toString} methods for the * multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} * does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the * collections generated by {@code factory}, and the multimap contents are all * serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the * multimap, even if {@code map} and the instances generated by * {@code factory} are. Concurrent read operations will work correctly. To * allow concurrent update operations, wrap the multimap with a call to * {@link #synchronizedMultimap}. * * <p>Call this method only when the simpler methods * {@link ArrayListMultimap#create()}, {@link HashMultimap#create()}, * {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()}, * {@link TreeMultimap#create()}, and * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and * the collections returned by {@code factory}. Those objects should not be * manually updated and they should not use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding * values * @param factory supplier of new, empty collections that will each hold all * values for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K, V> Multimap<K, V> newMultimap(Map<K, Collection<V>> map, final Supplier<? extends Collection<V>> factory) { return new CustomMultimap<K, V>(map, factory); } private static class CustomMultimap<K, V> extends AbstractMultimap<K, V> { transient Supplier<? extends Collection<V>> factory; CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override protected Collection<V> createCollection() { return factory.get(); } // can't use Serialization writeMultimap and populateMultimap methods since // there's no way to generate the empty backing map. } /** * 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(); } } /** * 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(); } } /** * 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; } } /** * Copies each key-value mapping in {@code source} into {@code dest}, with * its key and value reversed. * * <p>If {@code source} is an {@link ImmutableMultimap}, consider using * {@link ImmutableMultimap#inverse} instead. * * @param source any multimap * @param dest the multimap to copy into; usually empty * @return {@code dest} */ public static <K, V, M extends Multimap<K, V>> M invertFrom( Multimap<? extends V, ? extends K> source, M dest) { checkNotNull(dest); for (Map.Entry<? extends V, ? extends K> entry : source.entries()) { dest.put(entry.getValue(), entry.getKey()); } return dest; } /** * Returns a synchronized (thread-safe) multimap backed by the specified * multimap. In order to guarantee serial access, it is critical that * <b>all</b> access to the backing multimap is accomplished through the * returned multimap. * * <p>It is imperative that the user manually synchronize on the returned * multimap when accessing any of its collection views: <pre> {@code * * Multimap<K, V> m = Multimaps.synchronizedMultimap( * HashMultimap.<K, V>create()); * ... * Set<K> s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator<K> i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * }}</pre> * * Failure to follow this advice may result in non-deterministic behavior. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that aren't * synchronized. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param multimap the multimap to be wrapped in a synchronized view * @return a synchronized view of the specified multimap */ public static <K, V> Multimap<K, V> synchronizedMultimap( Multimap<K, V> multimap) { return Synchronized.multimap(multimap, null); } /** * Returns an unmodifiable view of the specified multimap. Query operations on * the returned multimap "read through" to the specified multimap, and * attempts to modify the returned multimap, either directly or through the * multimap's views, result in an {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> Multimap<K, V> unmodifiableMultimap( Multimap<K, V> delegate) { if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) { return delegate; } return new UnmodifiableMultimap<K, V>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap( ImmutableMultimap<K, V> delegate) { return checkNotNull(delegate); } private static class UnmodifiableMultimap<K, V> extends ForwardingMultimap<K, V> implements Serializable { final Multimap<K, V> delegate; transient Collection<Entry<K, V>> entries; transient Multiset<K> keys; transient Set<K> keySet; transient Collection<V> values; transient Map<K, Collection<V>> map; UnmodifiableMultimap(final Multimap<K, V> delegate) { this.delegate = checkNotNull(delegate); } @Override protected Multimap<K, V> delegate() { return delegate; } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = map; if (result == null) { final Map<K, Collection<V>> unmodifiableMap = Collections.unmodifiableMap(delegate.asMap()); map = result = new ForwardingMap<K, Collection<V>>() { @Override protected Map<K, Collection<V>> delegate() { return unmodifiableMap; } Set<Entry<K, Collection<V>>> entrySet; @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { Set<Entry<K, Collection<V>>> result = entrySet; return (result == null) ? entrySet = unmodifiableAsMapEntries(unmodifiableMap.entrySet()) : result; } @Override public Collection<V> get(Object key) { Collection<V> collection = unmodifiableMap.get(key); return (collection == null) ? null : unmodifiableValueCollection(collection); } Collection<Collection<V>> asMapValues; @Override public Collection<Collection<V>> values() { Collection<Collection<V>> result = asMapValues; return (result == null) ? asMapValues = new UnmodifiableAsMapValues<V>(unmodifiableMap.values()) : result; } @Override public boolean containsValue(Object o) { return values().contains(o); } }; } return result; } @Override public Collection<Entry<K, V>> entries() { Collection<Entry<K, V>> result = entries; if (result == null) { entries = result = unmodifiableEntries(delegate.entries()); } return result; } @Override public Collection<V> get(K key) { return unmodifiableValueCollection(delegate.get(key)); } @Override public Multiset<K> keys() { Multiset<K> result = keys; if (result == null) { keys = result = Multisets.unmodifiableMultiset(delegate.keys()); } return result; } @Override public Set<K> keySet() { Set<K> result = keySet; if (result == null) { keySet = result = Collections.unmodifiableSet(delegate.keySet()); } return result; } @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public Collection<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public Collection<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Collection<V> values() { Collection<V> result = values; if (result == null) { values = result = Collections.unmodifiableCollection(delegate.values()); } return result; } private static final long serialVersionUID = 0; } private static class UnmodifiableAsMapValues<V> extends ForwardingCollection<Collection<V>> { final Collection<Collection<V>> delegate; UnmodifiableAsMapValues(Collection<Collection<V>> delegate) { this.delegate = Collections.unmodifiableCollection(delegate); } @Override protected Collection<Collection<V>> delegate() { return delegate; } @Override public Iterator<Collection<V>> iterator() { final Iterator<Collection<V>> iterator = delegate.iterator(); return new Iterator<Collection<V>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Collection<V> next() { return unmodifiableValueCollection(iterator.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return standardContains(o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } } private static class UnmodifiableListMultimap<K, V> extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> { UnmodifiableListMultimap(ListMultimap<K, V> delegate) { super(delegate); } @Override public ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { return Collections.unmodifiableList(delegate().get(key)); } @Override public List<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } private static class UnmodifiableSetMultimap<K, V> extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> { UnmodifiableSetMultimap(SetMultimap<K, V> delegate) { super(delegate); } @Override public SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { /* * Note that this doesn't return a SortedSet when delegate is a * SortedSetMultiset, unlike (SortedSet<V>) super.get(). */ return Collections.unmodifiableSet(delegate().get(key)); } @Override public Set<Map.Entry<K, V>> entries() { return Maps.unmodifiableEntrySet(delegate().entries()); } @Override public Set<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } private static class UnmodifiableSortedSetMultimap<K, V> extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> { UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) { super(delegate); } @Override public SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { return Collections.unmodifiableSortedSet(delegate().get(key)); } @Override public SortedSet<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Comparator<? super V> valueComparator() { return delegate().valueComparator(); } private static final long serialVersionUID = 0; } /** * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the * specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K, V> SetMultimap<K, V> synchronizedSetMultimap( SetMultimap<K, V> multimap) { return Synchronized.setMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code SetMultimap}. Query * operations on the returned multimap "read through" to the specified * multimap, and attempts to modify the returned multimap, either directly or * through the multimap's views, result in an * {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap( SetMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) { return delegate; } return new UnmodifiableSetMultimap<K, V>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap( ImmutableSetMultimap<K, V> delegate) { return checkNotNull(delegate); } /** * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by * the specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K, V> SortedSetMultimap<K, V> synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) { return Synchronized.sortedSetMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. * Query operations on the returned multimap "read through" to the specified * multimap, and attempts to modify the returned multimap, either directly or * through the multimap's views, result in an * {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap( SortedSetMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableSortedSetMultimap) { return delegate; } return new UnmodifiableSortedSetMultimap<K, V>(delegate); } /** * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the * specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K, V> ListMultimap<K, V> synchronizedListMultimap( ListMultimap<K, V> multimap) { return Synchronized.listMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code ListMultimap}. Query * operations on the returned multimap "read through" to the specified * multimap, and attempts to modify the returned multimap, either directly or * through the multimap's views, result in an * {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> ListMultimap<K, V> unmodifiableListMultimap( ListMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) { return delegate; } return new UnmodifiableListMultimap<K, V>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap( ImmutableListMultimap<K, V> delegate) { return checkNotNull(delegate); } /** * Returns an unmodifiable view of the specified collection, preserving the * interface for instances of {@code SortedSet}, {@code Set}, {@code List} and * {@code Collection}, in that order of preference. * * @param collection the collection for which to return an unmodifiable view * @return an unmodifiable view of the collection */ private static <V> Collection<V> unmodifiableValueCollection( Collection<V> collection) { if (collection instanceof SortedSet) { return Collections.unmodifiableSortedSet((SortedSet<V>) collection); } else if (collection instanceof Set) { return Collections.unmodifiableSet((Set<V>) collection); } else if (collection instanceof List) { return Collections.unmodifiableList((List<V>) collection); } return Collections.unmodifiableCollection(collection); } /** * Returns an unmodifiable view of the specified multimap {@code asMap} entry. * The {@link Entry#setValue} operation throws an {@link * UnsupportedOperationException}, and the collection returned by {@code * getValue} is also an unmodifiable (type-preserving) view. This also has the * side-effect of redefining equals to comply with the Map.Entry contract, and * to avoid a possible nefarious implementation of equals. * * @param entry the entry for which to return an unmodifiable view * @return an unmodifiable view of the entry */ private static <K, V> Map.Entry<K, Collection<V>> unmodifiableAsMapEntry( final Map.Entry<K, Collection<V>> entry) { checkNotNull(entry); return new AbstractMapEntry<K, Collection<V>>() { @Override public K getKey() { return entry.getKey(); } @Override public Collection<V> getValue() { return unmodifiableValueCollection(entry.getValue()); } }; } /** * Returns an unmodifiable view of the specified collection of entries. The * {@link Entry#setValue} operation throws an {@link * UnsupportedOperationException}. If the specified collection is a {@code * Set}, the returned collection is also a {@code Set}. * * @param entries the entries for which to return an unmodifiable view * @return an unmodifiable view of the entries */ private static <K, V> Collection<Entry<K, V>> unmodifiableEntries( Collection<Entry<K, V>> entries) { if (entries instanceof Set) { return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries); } return new Maps.UnmodifiableEntries<K, V>( Collections.unmodifiableCollection(entries)); } /** * Returns an unmodifiable view of the specified set of {@code asMap} entries. * The {@link Entry#setValue} operation throws an {@link * UnsupportedOperationException}, as do any operations that attempt to modify * the returned collection. * * @param asMapEntries the {@code asMap} entries for which to return an * unmodifiable view * @return an unmodifiable view of the collection entries */ private static <K, V> Set<Entry<K, Collection<V>>> unmodifiableAsMapEntries( Set<Entry<K, Collection<V>>> asMapEntries) { return new UnmodifiableAsMapEntries<K, V>( Collections.unmodifiableSet(asMapEntries)); } /** @see Multimaps#unmodifiableAsMapEntries */ static class UnmodifiableAsMapEntries<K, V> extends ForwardingSet<Entry<K, Collection<V>>> { private final Set<Entry<K, Collection<V>>> delegate; UnmodifiableAsMapEntries(Set<Entry<K, Collection<V>>> delegate) { this.delegate = delegate; } @Override protected Set<Entry<K, Collection<V>>> delegate() { return delegate; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { final Iterator<Entry<K, Collection<V>>> iterator = delegate.iterator(); return new ForwardingIterator<Entry<K, Collection<V>>>() { @Override protected Iterator<Entry<K, Collection<V>>> delegate() { return iterator; } @Override public Entry<K, Collection<V>> next() { return unmodifiableAsMapEntry(iterator.next()); } }; } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean equals(@Nullable Object object) { return standardEquals(object); } } /** * Returns a multimap view of the specified map. The multimap is backed by the * map, so changes to the map are reflected in the multimap, and vice versa. * If the map is modified while an iteration over one of the multimap's * collection views is in progress (except through the iterator's own {@code * remove} operation, or through the {@code setValue} operation on a map entry * returned by the iterator), the results of the iteration are undefined. * * <p>The multimap supports mapping removal, which removes the corresponding * mapping from the map. It does not support any operations which might add * mappings, such as {@code put}, {@code putAll} or {@code replaceValues}. * * <p>The returned multimap will be serializable if the specified map is * serializable. * * @param map the backing map for the returned multimap view */ public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) { return new MapMultimap<K, V>(map); } /** @see Multimaps#forMap */ private static class MapMultimap<K, V> implements SetMultimap<K, V>, Serializable { final Map<K, V> map; transient Map<K, Collection<V>> asMap; MapMultimap(Map<K, V> map) { this.map = checkNotNull(map); } @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public boolean containsEntry(Object key, Object value) { return map.entrySet().contains(Maps.immutableEntry(key, value)); } @Override public Set<V> get(final K key) { return new AbstractSet<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { int i; @Override public boolean hasNext() { return (i == 0) && map.containsKey(key); } @Override public V next() { if (!hasNext()) { throw new NoSuchElementException(); } i++; return map.get(key); } @Override public void remove() { checkState(i == 1); i = -1; map.remove(key); } }; } @Override public int size() { return map.containsKey(key) ? 1 : 0; } }; } @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { return map.entrySet().remove(Maps.immutableEntry(key, value)); } @Override public Set<V> removeAll(Object key) { Set<V> values = new HashSet<V>(2); if (!map.containsKey(key)) { return values; } values.add(map.remove(key)); return values; } @Override public void clear() { map.clear(); } @Override public Set<K> keySet() { return map.keySet(); } @Override public Multiset<K> keys() { return Multisets.forSet(map.keySet()); } @Override public Collection<V> values() { return map.values(); } @Override public Set<Entry<K, V>> entries() { return map.entrySet(); } @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = asMap; if (result == null) { asMap = result = new AsMap(); } return result; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return this.size() == that.size() && asMap().equals(that.asMap()); } return false; } @Override public int hashCode() { return map.hashCode(); } private static final MapJoiner JOINER = Joiner.on("], ").withKeyValueSeparator("=[").useForNull("null"); @Override public String toString() { if (map.isEmpty()) { return "{}"; } StringBuilder builder = Collections2.newStringBuilderForCollection(map.size()).append('{'); JOINER.appendTo(builder, map); return builder.append("]}").toString(); } /** @see MapMultimap#asMap */ class AsMapEntries extends AbstractSet<Entry<K, Collection<V>>> { @Override public int size() { return map.size(); } @Override public Iterator<Entry<K, Collection<V>>> iterator() { return new Iterator<Entry<K, Collection<V>>>() { final Iterator<K> keys = map.keySet().iterator(); @Override public boolean hasNext() { return keys.hasNext(); } @Override public Entry<K, Collection<V>> next() { final K key = keys.next(); return new AbstractMapEntry<K, Collection<V>>() { @Override public K getKey() { return key; } @Override public Collection<V> getValue() { return get(key); } }; } @Override public void remove() { keys.remove(); } }; } @Override public boolean contains(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> entry = (Entry<?, ?>) o; if (!(entry.getValue() instanceof Set)) { return false; } Set<?> set = (Set<?>) entry.getValue(); return (set.size() == 1) && containsEntry(entry.getKey(), set.iterator().next()); } @Override public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> entry = (Entry<?, ?>) o; if (!(entry.getValue() instanceof Set)) { return false; } Set<?> set = (Set<?>) entry.getValue(); return (set.size() == 1) && map.entrySet().remove( Maps.immutableEntry(entry.getKey(), set.iterator().next())); } } /** @see MapMultimap#asMap */ class AsMap extends Maps.ImprovedAbstractMap<K, Collection<V>> { @Override protected Set<Entry<K, Collection<V>>> createEntrySet() { return new AsMapEntries(); } // The following methods are included for performance. @Override public boolean containsKey(Object key) { return map.containsKey(key); } @SuppressWarnings("unchecked") @Override public Collection<V> get(Object key) { Collection<V> collection = MapMultimap.this.get((K) key); return collection.isEmpty() ? null : collection; } @Override public Collection<V> remove(Object key) { Collection<V> collection = removeAll(key); return collection.isEmpty() ? null : collection; } } private static final long serialVersionUID = 7845222491160860175L; } /** * Returns a view of a multimap where each value is transformed by a function. * All other properties of the multimap, such as iteration order, are left * intact. For example, the code: <pre> {@code * * Multimap<String, Integer> multimap = * ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6); * Function<Integer, String> square = new Function<Integer, String>() { * public String apply(Integer in) { * return Integer.toString(in * in); * } * }; * Multimap<String, String> transformed = * Multimaps.transformValues(multimap, square); * System.out.println(transformed);}</pre> * * ... prints {@code {a=[4, 16], b=[9, 9], c=[6]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys, and * even null values provided that the function is capable of accepting null * input. The transformed multimap might contain null values, if the function * sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. The {@code equals} and {@code hashCode} methods * of the returned multimap are meaningless, since there is not a definition * of {@code equals} or {@code hashCode} for general collections, and * {@code get()} will return a general {@code Collection} as opposed to a * {@code List} or a {@code Set}. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned multimap to be a view, but it means that the function will * be applied many times for bulk operations like * {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to * perform well, {@code function} should be fast. To avoid lazy evaluation * when the returned multimap doesn't need to be a view, copy the returned * multimap into a new multimap of your choosing. * * @since 7.0 */ @Beta public static <K, V1, V2> Multimap<K, V2> transformValues( Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = new EntryTransformer<K, V1, V2>() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; return transformEntries(fromMultimap, transformer); } /** * Returns a view of a multimap whose values are derived from the original * multimap's entries. In contrast to {@link #transformValues}, this method's * entry-transformation logic may depend on the key as well as the value. * * <p>All other properties of the transformed multimap, such as iteration * order, are left intact. For example, the code: <pre> {@code * * SetMultimap<String, Integer> multimap = * ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6); * EntryTransformer<String, Integer, String> transformer = * new EntryTransformer<String, Integer, String>() { * public String transformEntry(String key, Integer value) { * return (value >= 0) ? key : "no" + key; * } * }; * Multimap<String, String> transformed = * Multimaps.transformEntries(multimap, transformer); * System.out.println(transformed);}</pre> * * ... prints {@code {a=[a, a], b=[nob]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys and * null values provided that the transformer is capable of accepting null * inputs. The transformed multimap might contain null values if the * transformer sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. The {@code equals} and {@code hashCode} methods * of the returned multimap are meaningless, since there is not a definition * of {@code equals} or {@code hashCode} for general collections, and * {@code get()} will return a general {@code Collection} as opposed to a * {@code List} or a {@code Set}. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned multimap to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Multimap#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the * returned multimap doesn't need to be a view, copy the returned multimap * into a new multimap of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed multimap. * * @since 7.0 */ @Beta public static <K, V1, V2> Multimap<K, V2> transformEntries( Multimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesMultimap<K, V1, V2>(fromMap, transformer); } private static class TransformedEntriesMultimap<K, V1, V2> implements Multimap<K, V2> { final Multimap<K, V1> fromMultimap; final EntryTransformer<? super K, ? super V1, V2> transformer; TransformedEntriesMultimap(Multimap<K, V1> fromMultimap, final EntryTransformer<? super K, ? super V1, V2> transformer) { this.fromMultimap = checkNotNull(fromMultimap); this.transformer = checkNotNull(transformer); } Collection<V2> transform(final K key, Collection<V1> values) { return Collections2.transform(values, new Function<V1, V2>() { @Override public V2 apply(V1 value) { return transformer.transformEntry(key, value); } }); } private transient Map<K, Collection<V2>> asMap; @Override public Map<K, Collection<V2>> asMap() { if (asMap == null) { Map<K, Collection<V2>> aM = Maps.transformEntries(fromMultimap.asMap(), new EntryTransformer<K, Collection<V1>, Collection<V2>>() { @Override public Collection<V2> transformEntry( K key, Collection<V1> value) { return transform(key, value); } }); asMap = aM; return aM; } return asMap; } @Override public void clear() { fromMultimap.clear(); } @SuppressWarnings("unchecked") @Override public boolean containsEntry(Object key, Object value) { Collection<V2> values = get((K) key); return values.contains(value); } @Override public boolean containsKey(Object key) { return fromMultimap.containsKey(key); } @Override public boolean containsValue(Object value) { return values().contains(value); } private transient Collection<Entry<K, V2>> entries; @Override public Collection<Entry<K, V2>> entries() { if (entries == null) { Collection<Entry<K, V2>> es = new TransformedEntries(transformer); entries = es; return es; } return entries; } private class TransformedEntries extends TransformedCollection<Entry<K, V1>, Entry<K, V2>> { TransformedEntries( final EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMultimap.entries(), new Function<Entry<K, V1>, Entry<K, V2>>() { @Override public Entry<K, V2> apply(final Entry<K, V1> entry) { return new AbstractMapEntry<K, V2>() { @Override public K getKey() { return entry.getKey(); } @Override public V2 getValue() { return transformer.transformEntry( entry.getKey(), entry.getValue()); } }; } }); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; return containsEntry(entry.getKey(), entry.getValue()); } return false; } @SuppressWarnings("unchecked") @Override public boolean remove(Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; Collection<V2> values = get((K) entry.getKey()); return values.remove(entry.getValue()); } return false; } } @Override public Collection<V2> get(final K key) { return transform(key, fromMultimap.get(key)); } @Override public boolean isEmpty() { return fromMultimap.isEmpty(); } @Override public Set<K> keySet() { return fromMultimap.keySet(); } @Override public Multiset<K> keys() { return fromMultimap.keys(); } @Override public boolean put(K key, V2 value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll( Multimap<? extends K, ? extends V2> multimap) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean remove(Object key, Object value) { return get((K) key).remove(value); } @SuppressWarnings("unchecked") @Override public Collection<V2> removeAll(Object key) { return transform((K) key, fromMultimap.removeAll(key)); } @Override public Collection<V2> replaceValues( K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } @Override public int size() { return fromMultimap.size(); } private transient Collection<V2> values; @Override public Collection<V2> values() { if (values == null) { Collection<V2> vs = Collections2.transform( fromMultimap.entries(), new Function<Entry<K, V1>, V2>() { @Override public V2 apply(Entry<K, V1> entry) { return transformer.transformEntry( entry.getKey(), entry.getValue()); } }); values = vs; return vs; } return values; } @Override public boolean equals(Object obj) { if (obj instanceof Multimap) { Multimap<?, ?> other = (Multimap<?, ?>) obj; return asMap().equals(other.asMap()); } return false; } @Override public int hashCode() { return asMap().hashCode(); } @Override public String toString() { return asMap().toString(); } } /** * Returns a view of a {@code ListMultimap} where each value is transformed by * a function. All other properties of the multimap, such as iteration order, * are left intact. For example, the code: <pre> {@code * * ListMultimap<String, Integer> multimap * = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * ListMultimap<String, Double> transformed = Multimaps.transformValues(map, * sqrt); * System.out.println(transformed);}</pre> * * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys, and * even null values provided that the function is capable of accepting null * input. The transformed multimap might contain null values, if the function * sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned multimap to be a view, but it means that the function will * be applied many times for bulk operations like * {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to * perform well, {@code function} should be fast. To avoid lazy evaluation * when the returned multimap doesn't need to be a view, copy the returned * multimap into a new multimap of your choosing. * * @since 7.0 */ @Beta public static <K, V1, V2> ListMultimap<K, V2> transformValues( ListMultimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = new EntryTransformer<K, V1, V2>() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; return transformEntries(fromMultimap, transformer); } /** * Returns a view of a {@code ListMultimap} whose values are derived from the * original multimap's entries. In contrast to * {@link #transformValues(ListMultimap, Function)}, this method's * entry-transformation logic may depend on the key as well as the value. * * <p>All other properties of the transformed multimap, such as iteration * order, are left intact. For example, the code: <pre> {@code * * Multimap<String, Integer> multimap = * ImmutableMultimap.of("a", 1, "a", 4, "b", 6); * EntryTransformer<String, Integer, String> transformer = * new EntryTransformer<String, Integer, String>() { * public String transformEntry(String key, Integer value) { * return key + value; * } * }; * Multimap<String, String> transformed = * Multimaps.transformEntries(multimap, transformer); * System.out.println(transformed);}</pre> * * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys and * null values provided that the transformer is capable of accepting null * inputs. The transformed multimap might contain null values if the * transformer sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned multimap to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Multimap#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the * returned multimap doesn't need to be a view, copy the returned multimap * into a new multimap of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed multimap. * * @since 7.0 */ @Beta public static <K, V1, V2> ListMultimap<K, V2> transformEntries( ListMultimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesListMultimap<K, V1, V2>(fromMap, transformer); } private static final class TransformedEntriesListMultimap<K, V1, V2> extends TransformedEntriesMultimap<K, V1, V2> implements ListMultimap<K, V2> { TransformedEntriesListMultimap(ListMultimap<K, V1> fromMultimap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMultimap, transformer); } @Override List<V2> transform(final K key, Collection<V1> values) { return Lists.transform((List<V1>) values, new Function<V1, V2>() { @Override public V2 apply(V1 value) { return transformer.transformEntry(key, value); } }); } @Override public List<V2> get(K key) { return transform(key, fromMultimap.get(key)); } @SuppressWarnings("unchecked") @Override public List<V2> removeAll(Object key) { return transform((K) key, fromMultimap.removeAll(key)); } @Override public List<V2> replaceValues( K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } } /** * Creates an index {@code ImmutableListMultimap} that contains the results of * applying a specified function to each item in an {@code Iterable} of * values. Each value will be stored as a value in the resulting multimap, * yielding a multimap with the same size as the input iterable. The key used * to store that value in the multimap will be the result of calling the * function on that value. The resulting multimap is created as an immutable * snapshot. In the returned multimap, keys appear in the order they are first * encountered, and the values corresponding to each key appear in the same * order as they are encountered. * * <p>For example, <pre> {@code * * List<String> badGuys = * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); * Function<String, Integer> stringLengthFunction = ...; * Multimap<Integer, String> index = * Multimaps.index(badGuys, stringLengthFunction); * System.out.println(index);}</pre> * * prints <pre> {@code * * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre> * * The returned multimap is serializable if its keys and values are all * serializable. * * @param values the values to use when constructing the {@code * ImmutableListMultimap} * @param keyFunction the function used to produce the key for each value * @return {@code ImmutableListMultimap} mapping the result of evaluating the * function {@code keyFunction} on each value in the input collection to * that value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code values} is null * <li>{@code keyFunction} is null * <li>An element in {@code values} is null * <li>{@code keyFunction} returns {@code null} for any element of {@code * values} * </ul> */ public static <K, V> ImmutableListMultimap<K, V> index( Iterable<V> values, Function<? super V, K> keyFunction) { return index(values.iterator(), keyFunction); } /** * <b>Deprecated.</b> * * @since 10.0 * @deprecated use {@link #index(Iterator, Function)} by casting {@code * values} to {@code Iterator<V>}, or better yet, by implementing only * {@code Iterator} and not {@code Iterable}. <b>This method is scheduled * for deletion in March 2012.</b> */ @Beta @Deprecated public static <K, V, I extends Object & Iterable<V> & Iterator<V>> ImmutableListMultimap<K, V> index( I values, Function<? super V, K> keyFunction) { Iterable<V> valuesIterable = checkNotNull(values); return index(valuesIterable, keyFunction); } /** * Creates an index {@code ImmutableListMultimap} that contains the results of * applying a specified function to each item in an {@code Iterator} of * values. Each value will be stored as a value in the resulting multimap, * yielding a multimap with the same size as the input iterator. The key used * to store that value in the multimap will be the result of calling the * function on that value. The resulting multimap is created as an immutable * snapshot. In the returned multimap, keys appear in the order they are first * encountered, and the values corresponding to each key appear in the same * order as they are encountered. * * <p>For example, <pre> {@code * * List<String> badGuys = * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); * Function<String, Integer> stringLengthFunction = ...; * Multimap<Integer, String> index = * Multimaps.index(badGuys.iterator(), stringLengthFunction); * System.out.println(index);}</pre> * * prints <pre> {@code * * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre> * * The returned multimap is serializable if its keys and values are all * serializable. * * @param values the values to use when constructing the {@code * ImmutableListMultimap} * @param keyFunction the function used to produce the key for each value * @return {@code ImmutableListMultimap} mapping the result of evaluating the * function {@code keyFunction} on each value in the input collection to * that value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code values} is null * <li>{@code keyFunction} is null * <li>An element in {@code values} is null * <li>{@code keyFunction} returns {@code null} for any element of {@code * values} * </ul> * @since 10.0 */ public static <K, V> ImmutableListMultimap<K, V> index( Iterator<V> values, Function<? super V, K> keyFunction) { checkNotNull(keyFunction); ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); while (values.hasNext()) { V value = values.next(); checkNotNull(value, values); builder.put(keyFunction.apply(value), value); } return builder.build(); } static abstract class Keys<K, V> extends AbstractMultiset<K> { abstract Multimap<K, V> multimap(); @Override Iterator<Multiset.Entry<K>> entryIterator() { final Iterator<Map.Entry<K, Collection<V>>> backingIterator = multimap().asMap().entrySet().iterator(); return new Iterator<Multiset.Entry<K>>() { @Override public boolean hasNext() { return backingIterator.hasNext(); } @Override public Multiset.Entry<K> next() { final Map.Entry<K, Collection<V>> backingEntry = backingIterator.next(); return new Multisets.AbstractEntry<K>() { @Override public K getElement() { return backingEntry.getKey(); } @Override public int getCount() { return backingEntry.getValue().size(); } }; } @Override public void remove() { backingIterator.remove(); } }; } @Override int distinctElements() { return multimap().asMap().size(); } @Override Set<Multiset.Entry<K>> createEntrySet() { return new KeysEntrySet(); } class KeysEntrySet extends Multisets.EntrySet<K> { @Override Multiset<K> multiset() { return Keys.this; } @Override public Iterator<Multiset.Entry<K>> iterator() { return entryIterator(); } @Override public int size() { return distinctElements(); } @Override public boolean isEmpty() { return multimap().isEmpty(); } @Override public boolean contains(@Nullable Object o) { if (o instanceof Multiset.Entry<?>) { Multiset.Entry<?> entry = (Multiset.Entry<?>) o; Collection<V> collection = multimap().asMap().get(entry.getElement()); return collection != null && collection.size() == entry.getCount(); } return false; } @Override public boolean remove(@Nullable Object o) { if (o instanceof Multiset.Entry<?>) { Multiset.Entry<?> entry = (Multiset.Entry<?>) o; Collection<V> collection = multimap().asMap().get(entry.getElement()); if (collection != null && collection.size() == entry.getCount()) { collection.clear(); return true; } } return false; } } @Override public boolean contains(@Nullable Object element) { return multimap().containsKey(element); } @Override public Iterator<K> iterator() { return Iterators.transform(multimap().entries().iterator(), new Function<Map.Entry<K, V>, K>() { @Override public K apply(Map.Entry<K, V> entry) { return entry.getKey(); } }); } @Override public int count(@Nullable Object element) { try { if (multimap().containsKey(element)) { Collection<V> values = multimap().asMap().get(element); return (values == null) ? 0 : values.size(); } return 0; } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } } @Override public int remove(@Nullable Object element, int occurrences) { checkArgument(occurrences >= 0); if (occurrences == 0) { return count(element); } Collection<V> values; try { values = multimap().asMap().get(element); } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } if (values == null) { return 0; } int oldCount = values.size(); if (occurrences >= oldCount) { values.clear(); } else { Iterator<V> iterator = values.iterator(); for (int i = 0; i < occurrences; i++) { iterator.next(); iterator.remove(); } } return oldCount; } @Override public void clear() { multimap().clear(); } @Override public Set<K> elementSet() { return multimap().keySet(); } } static abstract class Values<K, V> extends AbstractCollection<V> { abstract Multimap<K, V> multimap(); @Override public Iterator<V> iterator() { final Iterator<Map.Entry<K, V>> backingIterator = multimap().entries().iterator(); return new Iterator<V>() { @Override public boolean hasNext() { return backingIterator.hasNext(); } @Override public V next() { return backingIterator.next().getValue(); } @Override public void remove() { backingIterator.remove(); } }; } @Override public int size() { return multimap().size(); } @Override public boolean contains(@Nullable Object o) { return multimap().containsValue(o); } @Override public void clear() { multimap().clear(); } } /** * A skeleton implementation of {@link Multimap#entries()}. */ static abstract class Entries<K, V> extends AbstractCollection<Map.Entry<K, V>> { abstract Multimap<K, V> multimap(); @Override public int size() { return multimap().size(); } @Override public boolean contains(@Nullable Object o) { if (o instanceof Map.Entry<?, ?>) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return multimap().containsEntry(entry.getKey(), entry.getValue()); } return false; } @Override public boolean remove(@Nullable Object o) { if (o instanceof Map.Entry<?, ?>) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return multimap().remove(entry.getKey(), entry.getValue()); } return false; } @Override public void clear() { multimap().clear(); } } /** * A skeleton implementation of {@link SetMultimap#entries()}. */ static abstract class EntrySet<K, V> extends Entries<K, V> implements Set<Map.Entry<K, V>> { @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean equals(@Nullable Object obj) { return Sets.equalsImpl(this, obj); } } /** * A skeleton implementation of {@link Multimap#asMap()}. */ static abstract class AsMap<K, V> extends Maps.ImprovedAbstractMap<K, Collection<V>> { abstract Multimap<K, V> multimap(); @Override public abstract int size(); abstract Iterator<Entry<K, Collection<V>>> entryIterator(); @Override protected Set<Entry<K, Collection<V>>> createEntrySet() { return new EntrySet(); } void removeValuesForKey(Object key){ multimap().removeAll(key); } class EntrySet extends Maps.EntrySet<K, Collection<V>> { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { return entryIterator(); } @Override public boolean remove(Object o) { if (!contains(o)) { return false; } Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; removeValuesForKey(entry.getKey()); return true; } } @SuppressWarnings("unchecked") @Override public Collection<V> get(Object key) { return containsKey(key) ? multimap().get((K) key) : null; } @Override public Collection<V> remove(Object key) { return containsKey(key) ? multimap().removeAll(key) : null; } @Override public Set<K> keySet() { return multimap().keySet(); } @Override public boolean isEmpty() { return multimap().isEmpty(); } @Override public boolean containsKey(Object key) { return multimap().containsKey(key); } @Override public void clear() { multimap().clear(); } } /** * Support removal operations when filtering a filtered multimap. Since a * filtered multimap has iterators that don't support remove, passing one to * the FilteredMultimap constructor would lead to a multimap whose removal * operations would fail. This method combines the predicates to avoid that * problem. */ private static <K, V> Multimap<K, V> filterFiltered(FilteredMultimap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredMultimap<K, V>(map.unfiltered, predicate); } private static class FilteredMultimap<K, V> implements Multimap<K, V> { final Multimap<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; FilteredMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } @Override public int size() { return entries().size(); } @Override public boolean isEmpty() { return entries().isEmpty(); } @Override public boolean containsKey(Object key) { return asMap().containsKey(key); } @Override public boolean containsValue(Object value) { return values().contains(value); } // This method should be called only when key is a K and value is a V. @SuppressWarnings("unchecked") boolean satisfiesPredicate(Object key, Object value) { return predicate.apply(Maps.immutableEntry((K) key, (V) value)); } @Override public boolean containsEntry(Object key, Object value) { return unfiltered.containsEntry(key, value) && satisfiesPredicate(key, value); } @Override public boolean put(K key, V value) { checkArgument(satisfiesPredicate(key, value)); return unfiltered.put(key, value); } @Override public boolean remove(Object key, Object value) { return containsEntry(key, value) ? unfiltered.remove(key, value) : false; } @Override public boolean putAll(K key, Iterable<? extends V> values) { for (V value : values) { checkArgument(satisfiesPredicate(key, value)); } return unfiltered.putAll(key, values); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends V> entry : multimap.entries()) { checkArgument(satisfiesPredicate(entry.getKey(), entry.getValue())); } return unfiltered.putAll(multimap); } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { for (V value : values) { checkArgument(satisfiesPredicate(key, value)); } // Not calling unfiltered.replaceValues() since values that don't satisify // the filter should remain in the multimap. Collection<V> oldValues = removeAll(key); unfiltered.putAll(key, values); return oldValues; } @Override public Collection<V> removeAll(Object key) { List<V> removed = Lists.newArrayList(); Collection<V> values = unfiltered.asMap().get(key); if (values != null) { Iterator<V> iterator = values.iterator(); while (iterator.hasNext()) { V value = iterator.next(); if (satisfiesPredicate(key, value)) { removed.add(value); iterator.remove(); } } } if (unfiltered instanceof SetMultimap) { return Collections.unmodifiableSet(Sets.newLinkedHashSet(removed)); } else { return Collections.unmodifiableList(removed); } } @Override public void clear() { entries().clear(); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return asMap().equals(that.asMap()); } return false; } @Override public int hashCode() { return asMap().hashCode(); } @Override public String toString() { return asMap().toString(); } class ValuePredicate implements Predicate<V> { final K key; ValuePredicate(K key) { this.key = key; } @Override public boolean apply(V value) { return satisfiesPredicate(key, value); } } Collection<V> filterCollection(Collection<V> collection, Predicate<V> predicate) { if (collection instanceof Set) { return Sets.filter((Set<V>) collection, predicate); } else { return Collections2.filter(collection, predicate); } } @Override public Collection<V> get(K key) { return filterCollection(unfiltered.get(key), new ValuePredicate(key)); } @Override public Set<K> keySet() { return asMap().keySet(); } Collection<V> values; @Override public Collection<V> values() { return (values == null) ? values = new Values() : values; } class Values extends Multimaps.Values<K, V> { @Override Multimap<K, V> multimap() { return FilteredMultimap.this; } @Override public boolean contains(@Nullable Object o) { return Iterators.contains(iterator(), o); } // Override remove methods since iterator doesn't support remove. @Override public boolean remove(Object o) { Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) { iterator.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { boolean changed = false; Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (c.contains(entry.getValue()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } @Override public boolean retainAll(Collection<?> c) { boolean changed = false; Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator(); while (iterator.hasNext()) { Entry<K, V> entry = iterator.next(); if (!c.contains(entry.getValue()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } } Collection<Entry<K, V>> entries; @Override public Collection<Entry<K, V>> entries() { return (entries == null) ? entries = Collections2.filter(unfiltered.entries(), predicate) : entries; } /** * Remove all filtered asMap() entries that satisfy the predicate. */ boolean removeEntriesIf(Predicate<Map.Entry<K, Collection<V>>> removalPredicate) { Iterator<Map.Entry<K, Collection<V>>> iterator = unfiltered.asMap().entrySet().iterator(); boolean changed = false; while (iterator.hasNext()) { // Determine whether to remove the filtered values with this key. Map.Entry<K, Collection<V>> entry = iterator.next(); K key = entry.getKey(); Collection<V> collection = entry.getValue(); Predicate<V> valuePredicate = new ValuePredicate(key); Collection<V> filteredCollection = filterCollection(collection, valuePredicate); Map.Entry<K, Collection<V>> filteredEntry = Maps.immutableEntry(key, filteredCollection); if (removalPredicate.apply(filteredEntry) && !filteredCollection.isEmpty()) { changed = true; if (Iterables.all(collection, valuePredicate)) { iterator.remove(); // Remove all values for the key. } else { filteredCollection.clear(); // Remove the filtered values only. } } } return changed; } Map<K, Collection<V>> asMap; @Override public Map<K, Collection<V>> asMap() { return (asMap == null) ? asMap = createAsMap() : asMap; } static final Predicate<Collection<?>> NOT_EMPTY = new Predicate<Collection<?>>() { @Override public boolean apply(Collection<?> input) { return !input.isEmpty(); } }; Map<K, Collection<V>> createAsMap() { // Select the values that satisify the predicate. EntryTransformer<K, Collection<V>, Collection<V>> transformer = new EntryTransformer<K, Collection<V>, Collection<V>>() { @Override public Collection<V> transformEntry(K key, Collection<V> collection) { return filterCollection(collection, new ValuePredicate(key)); } }; Map<K, Collection<V>> transformed = Maps.transformEntries(unfiltered.asMap(), transformer); // Select the keys that have at least one value remaining. Map<K, Collection<V>> filtered = Maps.filterValues(transformed, NOT_EMPTY); // Override the removal methods, since removing a map entry should not // affect values that don't satisfy the filter. return new AsMap(filtered); } class AsMap extends ForwardingMap<K, Collection<V>> { final Map<K, Collection<V>> delegate; AsMap(Map<K, Collection<V>> delegate) { this.delegate = delegate; } @Override protected Map<K, Collection<V>> delegate() { return delegate; } @Override public Collection<V> remove(Object o) { Collection<V> output = FilteredMultimap.this.removeAll(o); return output.isEmpty() ? null : output; } @Override public void clear() { FilteredMultimap.this.clear(); } Set<K> keySet; @Override public Set<K> keySet() { return (keySet == null) ? keySet = new KeySet() : keySet; } class KeySet extends Maps.KeySet<K, Collection<V>> { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public boolean remove(Object o) { Collection<V> collection = delegate.get(o); if (collection == null) { return false; } collection.clear(); return true; } @Override public boolean removeAll(Collection<?> c) { return Sets.removeAllImpl(this, c); } @Override public boolean retainAll(final Collection<?> c) { Predicate<Map.Entry<K, Collection<V>>> removalPredicate = new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { return !c.contains(entry.getKey()); } }; return removeEntriesIf(removalPredicate); } } Values asMapValues; @Override public Collection<Collection<V>> values() { return (asMapValues == null) ? asMapValues = new Values() : asMapValues; } class Values extends Maps.Values<K, Collection<V>> { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public boolean remove(Object o) { for (Collection<V> collection : this) { if (collection.equals(o)) { collection.clear(); return true; } } return false; } @Override public boolean removeAll(final Collection<?> c) { Predicate<Map.Entry<K, Collection<V>>> removalPredicate = new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { return c.contains(entry.getValue()); } }; return removeEntriesIf(removalPredicate); } @Override public boolean retainAll(final Collection<?> c) { Predicate<Map.Entry<K, Collection<V>>> removalPredicate = new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { return !c.contains(entry.getValue()); } }; return removeEntriesIf(removalPredicate); } } EntrySet entrySet; @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { return (entrySet == null) ? entrySet = new EntrySet(super.entrySet()) : entrySet; } class EntrySet extends Maps.EntrySet<K, Collection<V>> { Set<Map.Entry<K, Collection<V>>> delegateEntries; public EntrySet(Set<Map.Entry<K, Collection<V>>> delegateEntries) { this.delegateEntries = delegateEntries; } @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { return delegateEntries.iterator(); } @Override public boolean remove(Object o) { if (o instanceof Entry<?, ?>) { Entry<?, ?> entry = (Entry<?, ?>) o; Collection<V> collection = delegate.get(entry.getKey()); if (collection != null && collection.equals(entry.getValue())) { collection.clear(); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { return Sets.removeAllImpl(this, c); } @Override public boolean retainAll(final Collection<?> c) { Predicate<Map.Entry<K, Collection<V>>> removalPredicate = new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { return !c.contains(entry); } }; return removeEntriesIf(removalPredicate); } } } AbstractMultiset<K> keys; @Override public Multiset<K> keys() { return (keys == null) ? keys = new Keys() : keys; } class Keys extends Multimaps.Keys<K, V> { @Override Multimap<K, V> multimap() { return FilteredMultimap.this; } @Override public int remove(Object o, int occurrences) { checkArgument(occurrences >= 0); Collection<V> values = unfiltered.asMap().get(o); if (values == null) { return 0; } int priorCount = 0; int removed = 0; Iterator<V> iterator = values.iterator(); while (iterator.hasNext()) { if (satisfiesPredicate(o, iterator.next())) { priorCount++; if (removed < occurrences) { iterator.remove(); removed++; } } } return priorCount; } @Override Set<Multiset.Entry<K>> createEntrySet() { return new EntrySet(); } class EntrySet extends Multimaps.Keys<K, V>.KeysEntrySet { @Override public boolean removeAll(Collection<?> c) { return Sets.removeAllImpl(this, c); } @Override public boolean retainAll(final Collection<?> c) { Predicate<Map.Entry<K, Collection<V>>> removalPredicate = new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { Multiset.Entry<K> multisetEntry = Multisets.immutableEntry(entry.getKey(), entry.getValue().size()); return !c.contains(multisetEntry); } }; return removeEntriesIf(removalPredicate); } } } } // TODO(jlevy): Create methods that filter a SetMultimap or SortedSetMultimap. }
Java
/* * Copyright (C) 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.base.Preconditions; import com.google.common.primitives.Ints; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@code Multimap} that does not allow duplicate key-value * entries and that returns collections whose iterators follow the ordering in * which the data was added to the multimap. * * <p>The collections returned by {@code keySet}, {@code keys}, and {@code * asMap} iterate through the keys in the order they were first added to the * multimap. Similarly, {@code get}, {@code removeAll}, and {@code * replaceValues} return collections that iterate through the values in the * order they were added. The collections generated by {@code entries} and * {@code values} iterate across the key-value mappings in the order they were * added to the multimap. * * <p>The iteration ordering of the collections generated by {@code keySet}, * {@code keys}, and {@code asMap} has a few subtleties. As long as the set of * keys remains unchanged, adding or removing mappings does not affect the key * iteration order. However, if you remove all values associated with a key and * then add the key back to the multimap, that key will come last in the key * iteration order. * * <p>The multimap does not store duplicate key-value pairs. Adding a new * key-value pair equal to an existing key-value pair has no effect. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedSetMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> { private static final int DEFAULT_VALUES_PER_KEY = 8; @VisibleForTesting transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; /** * Map entries with an iteration order corresponding to the order in which the * key-value pairs were added to the multimap. */ // package-private for GWT deserialization transient Collection<Map.Entry<K, V>> linkedEntries; /** * Creates a new, empty {@code LinkedHashMultimap} with the default initial * capacities. */ public static <K, V> LinkedHashMultimap<K, V> create() { return new LinkedHashMultimap<K, V>(); } /** * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold * the specified numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> LinkedHashMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new LinkedHashMultimap<K, V>(expectedKeys, expectedValuesPerKey); } /** * Constructs a {@code LinkedHashMultimap} with the same mappings as the * specified multimap. If a key-value mapping appears multiple times in the * input multimap, it only appears once in the constructed multimap. The new * multimap has the same {@link Multimap#entries()} iteration order as the * input multimap, except for excluding duplicate mappings. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> LinkedHashMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new LinkedHashMultimap<K, V>(multimap); } private LinkedHashMultimap() { super(new LinkedHashMap<K, Collection<V>>()); linkedEntries = Sets.newLinkedHashSet(); } private LinkedHashMultimap(int expectedKeys, int expectedValuesPerKey) { super(new LinkedHashMap<K, Collection<V>>(expectedKeys)); Preconditions.checkArgument(expectedValuesPerKey >= 0); this.expectedValuesPerKey = expectedValuesPerKey; linkedEntries = new LinkedHashSet<Map.Entry<K, V>>( (int) Math.min(Ints.MAX_POWER_OF_TWO, ((long) expectedKeys) * expectedValuesPerKey)); } private LinkedHashMultimap(Multimap<? extends K, ? extends V> multimap) { super(new LinkedHashMap<K, Collection<V>>( Maps.capacity(multimap.keySet().size()))); linkedEntries = new LinkedHashSet<Map.Entry<K, V>>(Maps.capacity(multimap.size())); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code LinkedHashSet} for a collection of values for * one key. * * @return a new {@code LinkedHashSet} containing a collection of values for * one key */ @Override Set<V> createCollection() { return new LinkedHashSet<V>(Maps.capacity(expectedValuesPerKey)); } /** * {@inheritDoc} * * <p>Creates a decorated {@code LinkedHashSet} that also keeps track of the * order in which key-value pairs are added to the multimap. * * @param key key to associate with values in the collection * @return a new decorated {@code LinkedHashSet} containing a collection of * values for one key */ @Override Collection<V> createCollection(@Nullable K key) { return new SetDecorator(key, createCollection()); } private class SetDecorator extends ForwardingSet<V> { final Set<V> delegate; final K key; SetDecorator(@Nullable K key, Set<V> delegate) { this.delegate = delegate; this.key = key; } @Override protected Set<V> delegate() { return delegate; } <E> Map.Entry<K, E> createEntry(@Nullable E value) { return Maps.immutableEntry(key, value); } <E> Collection<Map.Entry<K, E>> createEntries(Collection<E> values) { // converts a collection of values into a list of key/value map entries Collection<Map.Entry<K, E>> entries = Lists.newArrayListWithExpectedSize(values.size()); for (E value : values) { entries.add(createEntry(value)); } return entries; } @Override public boolean add(@Nullable V value) { boolean changed = delegate.add(value); if (changed) { linkedEntries.add(createEntry(value)); } return changed; } @Override public boolean addAll(Collection<? extends V> values) { boolean changed = delegate.addAll(values); if (changed) { linkedEntries.addAll(createEntries(delegate())); } return changed; } @Override public void clear() { for (V value : delegate) { linkedEntries.remove(createEntry(value)); } delegate.clear(); } @Override public Iterator<V> iterator() { final Iterator<V> delegateIterator = delegate.iterator(); return new Iterator<V>() { V value; @Override public boolean hasNext() { return delegateIterator.hasNext(); } @Override public V next() { value = delegateIterator.next(); return value; } @Override public void remove() { delegateIterator.remove(); linkedEntries.remove(createEntry(value)); } }; } @Override public boolean remove(@Nullable Object value) { boolean changed = delegate.remove(value); if (changed) { /* * linkedEntries.remove() will return false when this method is called * by entries().iterator().remove() */ linkedEntries.remove(createEntry(value)); } return changed; } @Override public boolean removeAll(Collection<?> values) { boolean changed = delegate.removeAll(values); if (changed) { linkedEntries.removeAll(createEntries(values)); } return changed; } @Override public boolean retainAll(Collection<?> values) { /* * Calling linkedEntries.retainAll() would incorrectly remove values * with other keys. */ boolean changed = false; Iterator<V> iterator = delegate.iterator(); while (iterator.hasNext()) { V value = iterator.next(); if (!values.contains(value)) { iterator.remove(); linkedEntries.remove(Maps.immutableEntry(key, value)); changed = true; } } return changed; } } /** * {@inheritDoc} * * <p>Generates an iterator across map entries that follows the ordering in * which the key-value pairs were added to the multimap. * * @return a key-value iterator with the correct ordering */ @Override Iterator<Map.Entry<K, V>> createEntryIterator() { final Iterator<Map.Entry<K, V>> delegateIterator = linkedEntries.iterator(); return new Iterator<Map.Entry<K, V>>() { Map.Entry<K, V> entry; @Override public boolean hasNext() { return delegateIterator.hasNext(); } @Override public Map.Entry<K, V> next() { entry = delegateIterator.next(); return entry; } @Override public void remove() { // Remove from iterator first to keep iterator valid. delegateIterator.remove(); LinkedHashMultimap.this.remove(entry.getKey(), entry.getValue()); } }; } /** * {@inheritDoc} * * <p>If {@code values} is not empty and the multimap already contains a * mapping for {@code key}, the {@code keySet()} ordering is unchanged. * However, the provided values always come last in the {@link #entries()} and * {@link #values()} iteration orderings. */ @Override public Set<V> replaceValues( @Nullable K key, Iterable<? extends V> values) { return super.replaceValues(key, values); } /** * Returns a set of all key-value pairs. Changes to the returned set will * update the underlying multimap, and vice versa. The entries set does not * support the {@code add} or {@code addAll} operations. * * <p>The iterator generated by the returned set traverses the entries in the * order they were added to the multimap. * * <p>Each entry is an immutable snapshot of a key-value mapping in the * multimap, taken at the time the entry is returned by a method call to the * collection or its iterator. */ @Override public Set<Map.Entry<K, V>> entries() { return super.entries(); } /** * Returns a collection of all values in the multimap. Changes to the returned * collection will update the underlying multimap, and vice versa. * * <p>The iterator generated by the returned collection traverses the values * in the order they were added to the multimap. */ @Override public Collection<V> values() { return super.values(); } // Unfortunately, the entries() ordering does not determine the key ordering; // see the example in the LinkedListMultimap class Javadoc. }
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 java.util.SortedSet; /** * GWT emulation of {@link RegularImmutableSortedSet}. * * @author Hayward Chan */ final class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> { /** true if this set is a subset of another immutable sorted set. */ final boolean isSubset; RegularImmutableSortedSet(SortedSet<E> delegate, boolean isSubset) { super(delegate); this.isSubset = isSubset; } }
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.primitives.Ints; import java.io.Serializable; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Basic implementation of {@code Multiset<E>} backed by an instance of {@code * Map<E, AtomicInteger>}. * * <p>For serialization to work, the subclass must specify explicit {@code * readObject} and {@code writeObject} methods. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E> implements Serializable { private transient Map<E, Count> backingMap; /* * Cache the size for efficiency. Using a long lets us avoid the need for * overflow checking and ensures that size() will function correctly even if * the multiset had once been larger than Integer.MAX_VALUE. */ private transient long size; /** Standard constructor. */ protected AbstractMapBasedMultiset(Map<E, Count> backingMap) { this.backingMap = checkNotNull(backingMap); this.size = super.size(); } Map<E, Count> backingMap() { return backingMap; } /** Used during deserialization only. The backing map must be empty. */ void setBackingMap(Map<E, Count> backingMap) { this.backingMap = backingMap; } // Required Implementations /** * {@inheritDoc} * * <p>Invoking {@link Multiset.Entry#getCount} on an entry in the returned * set always returns the current count of that element in the multiset, as * opposed to the count at the time the entry was retrieved. */ @Override public Set<Multiset.Entry<E>> entrySet() { return super.entrySet(); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Map.Entry<E, Count>> backingEntries = backingMap.entrySet().iterator(); return new Iterator<Multiset.Entry<E>>() { Map.Entry<E, Count> toRemove; @Override public boolean hasNext() { return backingEntries.hasNext(); } @Override public Multiset.Entry<E> next() { final Map.Entry<E, Count> mapEntry = backingEntries.next(); toRemove = mapEntry; return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return mapEntry.getKey(); } @Override public int getCount() { int count = mapEntry.getValue().get(); if (count == 0) { Count frequency = backingMap.get(getElement()); if (frequency != null) { count = frequency.get(); } } return count; } }; } @Override public void remove() { checkState(toRemove != null, "no calls to next() since the last call to remove()"); size -= toRemove.getValue().getAndSet(0); backingEntries.remove(); toRemove = null; } }; } @Override public void clear() { for (Count frequency : backingMap.values()) { frequency.set(0); } backingMap.clear(); size = 0L; } @Override int distinctElements() { return backingMap.size(); } // Optimizations - Query Operations @Override public int size() { return Ints.saturatedCast(size); } @Override public Iterator<E> iterator() { return new MapBasedMultisetIterator(); } /* * Not subclassing AbstractMultiset$MultisetIterator because next() needs to * retrieve the Map.Entry<E, AtomicInteger> entry, which can then be used for * a more efficient remove() call. */ private class MapBasedMultisetIterator implements Iterator<E> { final Iterator<Map.Entry<E, Count>> entryIterator; Map.Entry<E, Count> currentEntry; int occurrencesLeft; boolean canRemove; MapBasedMultisetIterator() { this.entryIterator = backingMap.entrySet().iterator(); } @Override public boolean hasNext() { return occurrencesLeft > 0 || entryIterator.hasNext(); } @Override public E next() { if (occurrencesLeft == 0) { currentEntry = entryIterator.next(); occurrencesLeft = currentEntry.getValue().get(); } occurrencesLeft--; canRemove = true; return currentEntry.getKey(); } @Override public void remove() { checkState(canRemove, "no calls to next() since the last call to remove()"); int frequency = currentEntry.getValue().get(); if (frequency <= 0) { throw new ConcurrentModificationException(); } if (currentEntry.getValue().addAndGet(-1) == 0) { entryIterator.remove(); } size--; canRemove = false; } } @Override public int count(@Nullable Object element) { try { Count frequency = backingMap.get(element); return (frequency == null) ? 0 : frequency.get(); } catch (NullPointerException e) { return 0; } catch (ClassCastException e) { return 0; } } // Optional Operations - Modification Operations /** * {@inheritDoc} * * @throws IllegalArgumentException if the call would result in more than * {@link Integer#MAX_VALUE} occurrences of {@code element} in this * multiset. */ @Override public int add(@Nullable E element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument( occurrences > 0, "occurrences cannot be negative: %s", occurrences); Count frequency = backingMap.get(element); int oldCount; if (frequency == null) { oldCount = 0; backingMap.put(element, new Count(occurrences)); } else { oldCount = frequency.get(); long newCount = (long) oldCount + (long) occurrences; checkArgument(newCount <= Integer.MAX_VALUE, "too many occurrences: %s", newCount); frequency.getAndAdd(occurrences); } size += occurrences; return oldCount; } @Override public int remove(@Nullable Object element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument( occurrences > 0, "occurrences cannot be negative: %s", occurrences); Count frequency = backingMap.get(element); if (frequency == null) { return 0; } int oldCount = frequency.get(); int numberRemoved; if (oldCount > occurrences) { numberRemoved = occurrences; } else { numberRemoved = oldCount; backingMap.remove(element); } frequency.addAndGet(-numberRemoved); size -= numberRemoved; return oldCount; } // Roughly a 33% performance improvement over AbstractMultiset.setCount(). @Override public int setCount(E element, int count) { checkNonnegative(count, "count"); Count existingCounter; int oldCount; if (count == 0) { existingCounter = backingMap.remove(element); oldCount = getAndSet(existingCounter, count); } else { existingCounter = backingMap.get(element); oldCount = getAndSet(existingCounter, count); if (existingCounter == null) { backingMap.put(element, new Count(count)); } } size += (count - oldCount); return oldCount; } private static int getAndSet(Count i, int count) { if (i == null) { return 0; } return i.getAndSet(count); } private int removeAllOccurrences(@Nullable Object element, Map<E, Count> map) { Count frequency = map.remove(element); if (frequency == null) { return 0; } int numberRemoved = frequency.getAndSet(0); size -= numberRemoved; return numberRemoved; } // Views @Override Set<E> createElementSet() { return new MapBasedElementSet(backingMap); } // TODO(user): once TreeMultiset is replaced with a SortedMultiset // implementation, replace this with a subclass of Multisets.ElementSet. class MapBasedElementSet extends ForwardingSet<E> { // This mapping is the usually the same as 'backingMap', but can be a // submap in some implementations. private final Map<E, Count> map; private final Set<E> delegate; MapBasedElementSet(Map<E, Count> map) { this.map = map; delegate = map.keySet(); } @Override protected Set<E> delegate() { return delegate; } @Override public Iterator<E> iterator() { final Iterator<Map.Entry<E, Count>> entries = map.entrySet().iterator(); return new Iterator<E>() { Map.Entry<E, Count> toRemove; @Override public boolean hasNext() { return entries.hasNext(); } @Override public E next() { toRemove = entries.next(); return toRemove.getKey(); } @Override public void remove() { checkState(toRemove != null, "no calls to next() since the last call to remove()"); size -= toRemove.getValue().getAndSet(0); entries.remove(); toRemove = null; } }; } @Override public boolean remove(Object element) { return removeAllOccurrences(element, map) != 0; } @Override public boolean removeAll(Collection<?> elementsToRemove) { return Iterators.removeAll(iterator(), elementsToRemove); } @Override public boolean retainAll(Collection<?> elementsToRetain) { return Iterators.retainAll(iterator(), elementsToRetain); } @Override public void clear() { if (map == backingMap) { AbstractMapBasedMultiset.this.clear(); } else { Iterator<E> i = iterator(); while (i.hasNext()) { i.next(); i.remove(); } } } public Map<E, Count> getMap() { return map; } } // Don't allow default serialization. }
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.base.Function; 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> { // Set by MapMaker, but sits in this class to preserve the type relationship // No subclasses but our own GenericMapMaker() {} /** * See {@link MapMaker#initialCapacity}. */ public abstract GenericMapMaker<K0, V0> initialCapacity(int initialCapacity); /** * See {@link MapMaker#maximumSize}. */ abstract GenericMapMaker<K0, V0> maximumSize(int maximumSize); /** * See {@link MapMaker#strongKeys}. */ abstract GenericMapMaker<K0, V0> strongKeys(); /** * See {@link MapMaker#concurrencyLevel}. */ public abstract GenericMapMaker<K0, V0> concurrencyLevel(int concurrencyLevel); /** * See {@link MapMaker#strongValues}. */ abstract GenericMapMaker<K0, V0> strongValues(); /** * See {@link MapMaker#expiration}. */ @Deprecated public abstract GenericMapMaker<K0, V0> expiration(long duration, TimeUnit unit); /** * See {@link MapMaker#expireAfterWrite}. */ abstract GenericMapMaker<K0, V0> expireAfterWrite(long duration, TimeUnit unit); /* * 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. */ /** * See {@link MapMaker#makeMap}. */ public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeMap(); /** * 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 static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; /** * Implementation of {@code Multimap} that uses an {@code ArrayList} to store * the values for a given key. A {@link HashMap} associates each key with an * {@link ArrayList} of values. * * <p>When iterating through the collections supplied by this class, the * ordering of values for a given key agrees with the order in which the values * were added. * * <p>This multimap allows duplicate key-value pairs. After adding a new * key-value pair equal to an existing key-value pair, the {@code * ArrayListMultimap} will contain entries for both the new value and the old * value. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link * #replaceValues} all implement {@link java.util.RandomAccess}. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedListMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> { // Default from ArrayList private static final int DEFAULT_VALUES_PER_KEY = 10; @VisibleForTesting transient int expectedValuesPerKey; /** * Creates a new, empty {@code ArrayListMultimap} with the default initial * capacities. */ public static <K, V> ArrayListMultimap<K, V> create() { return new ArrayListMultimap<K, V>(); } /** * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold * the specified numbers of keys and values without resizing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> ArrayListMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey); } /** * Constructs an {@code ArrayListMultimap} with the same mappings as the * specified multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> ArrayListMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new ArrayListMultimap<K, V>(multimap); } private ArrayListMultimap() { super(new HashMap<K, Collection<V>>()); expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; } private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys)); checkArgument(expectedValuesPerKey >= 0); this.expectedValuesPerKey = expectedValuesPerKey; } private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size(), (multimap instanceof ArrayListMultimap) ? ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey : DEFAULT_VALUES_PER_KEY); putAll(multimap); } /** * Creates a new, empty {@code ArrayList} to hold the collection of values for * an arbitrary key. */ @Override List<V> createCollection() { return new ArrayList<V>(expectedValuesPerKey); } /** * Reduces the memory used by this {@code ArrayListMultimap}, if feasible. */ public void trimToSize() { for (Collection<V> collection : backingMap().values()) { ArrayList<V> arrayList = (ArrayList<V>) collection; arrayList.trimToSize(); } } }
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 java.util.Collections; /** * GWT emulation of {@link SingletonImmutableSet}. * * @author Hayward Chan */ final class SingletonImmutableSet<E> extends ImmutableSet<E> { // This reference is used both by the custom field serializer, and by the // GWT compiler to infer the elements of the lists that needs to be // serialized. // // Although this reference is non-final, it doesn't change after set creation. E element; SingletonImmutableSet(E element) { super(Collections.singleton(checkNotNull(element))); this.element = element; } }
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.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An empty contiguous set. * * @author Gregory Kick */ @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> { EmptyContiguousSet(DiscreteDomain<C> domain) { super(domain); } @Override public C first() { throw new NoSuchElementException(); } @Override public C last() { throw new NoSuchElementException(); } @Override public int size() { return 0; } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { return this; } @Override public Range<C> range() { throw new NoSuchElementException(); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { throw new NoSuchElementException(); } @Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return this; } @Override ContiguousSet<C> subSetImpl( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { return this; } @Override ContiguousSet<C> tailSetImpl(C fromElement, boolean fromInclusive) { return this; } //Abstract method doesn't exist in GWT emulation /* @Override */ int indexOf(Object target) { return -1; } @Override public UnmodifiableIterator<C> iterator() { return Iterators.emptyIterator(); } @Override boolean isPartialView() { return false; } @Override public boolean isEmpty() { return true; } @Override public ImmutableList<C> asList() { return ImmutableList.of(); } @Override public String toString() { return "[]"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { Set<?> that = (Set<?>) object; return that.isEmpty(); } return false; } @Override public int hashCode() { return 0; } }
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.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); } }
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 java.util.Comparator; /** * GWT emulation of {@link EmptyImmutableSortedSet}. * * @author Hayward Chan */ class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> { EmptyImmutableSortedSet(Comparator<? super E> comparator) { super(comparator); } }
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.base.Preconditions; import java.util.Collection; import java.util.HashMap; import java.util.Set; /** * Implementation of {@link Multimap} using hash tables. * * <p>The multimap does not store duplicate key-value pairs. Adding a new * key-value pair equal to an existing key-value pair has no effect. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedSetMultimap}. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultimap<K, V> extends AbstractSetMultimap<K, V> { private static final int DEFAULT_VALUES_PER_KEY = 8; @VisibleForTesting transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; /** * Creates a new, empty {@code HashMultimap} with the default initial * capacities. */ public static <K, V> HashMultimap<K, V> create() { return new HashMultimap<K, V>(); } /** * Constructs an empty {@code HashMultimap} with enough capacity to hold the * specified numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> HashMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new HashMultimap<K, V>(expectedKeys, expectedValuesPerKey); } /** * Constructs a {@code HashMultimap} with the same mappings as the specified * multimap. If a key-value mapping appears multiple times in the input * multimap, it only appears once in the constructed multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> HashMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new HashMultimap<K, V>(multimap); } private HashMultimap() { super(new HashMap<K, Collection<V>>()); } private HashMultimap(int expectedKeys, int expectedValuesPerKey) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys)); Preconditions.checkArgument(expectedValuesPerKey >= 0); this.expectedValuesPerKey = expectedValuesPerKey; } private HashMultimap(Multimap<? extends K, ? extends V> multimap) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize( multimap.keySet().size())); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code HashSet} for a collection of values for one key. * * @return a new {@code HashSet} containing a collection of values for one key */ @Override Set<V> createCollection() { return Sets.<V>newHashSetWithExpectedSize(expectedValuesPerKey); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import javax.annotation.Nullable; /** * An immutable {@link Multimap}. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableMultimap(Multimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableMultimap} is convenient for * {@code public static final} multimaps ("constant multimaps") and also lets * you easily make a "defensive copy" of a multimap provided to your class by * a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this class * are guaranteed to be immutable. * * <p>In addition to methods defined by {@link Multimap}, an {@link #inverse} * method is also supported. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) // TODO(user): If BiMultimap graduates from labs, this class should implement it. public abstract class ImmutableMultimap<K, V> implements Multimap<K, V>, Serializable { /** Returns an empty multimap. */ public static <K, V> ImmutableMultimap<K, V> of() { return ImmutableListMultimap.of(); } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) { return ImmutableListMultimap.of(k1, v1); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) { return ImmutableListMultimap.of(k1, v1, k2, v2); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * Multimap for {@link ImmutableMultimap.Builder} that maintains key and * value orderings, allows duplicate values, and performs better than * {@link LinkedListMultimap}. */ private static class BuilderMultimap<K, V> extends AbstractMultimap<K, V> { BuilderMultimap() { super(new LinkedHashMap<K, Collection<V>>()); } @Override Collection<V> createCollection() { return Lists.newArrayList(); } private static final long serialVersionUID = 0; } /** * Multimap for {@link ImmutableMultimap.Builder} that sorts key and allows * duplicate values, */ 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 Lists.newArrayList(); } private static final long serialVersionUID = 0; } /** * A builder for creating immutable multimap instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<K, V> { Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>(); Comparator<? super V> valueComparator; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMultimap#builder}. */ public Builder() {} /** * Adds a key-value mapping to the built multimap. */ public Builder<K, V> put(K key, V value) { builderMultimap.put(checkNotNull(key), checkNotNull(value)); return this; } /** * Adds an entry to the built multimap. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { builderMultimap.put( checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); return this; } /** * Stores a collection of values with the same key in the built multimap. * * @throws NullPointerException if {@code key}, {@code values}, or any * element in {@code values} is null. The builder is left in an invalid * state. */ public Builder<K, V> putAll(K key, Iterable<? extends V> values) { Collection<V> valueList = builderMultimap.get(checkNotNull(key)); for (V value : values) { valueList.add(checkNotNull(value)); } return this; } /** * Stores an array of values with the same key in the built multimap. * * @throws NullPointerException if the key or any value is null. The builder * is left in an invalid state. */ public Builder<K, V> putAll(K key, V... values) { return putAll(key, Arrays.asList(values)); } /** * Stores another multimap's entries in the built multimap. The generated * multimap's key and value orderings correspond to the iteration ordering * of the {@code multimap.asMap()} view, with new keys and values following * any existing keys and values. * * @throws NullPointerException if any key or value in {@code multimap} is * null. The builder is left in an invalid state. */ public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { putAll(entry.getKey(), entry.getValue()); } return this; } /** * Specifies the ordering of the generated multimap's keys. * * @since 8.0 */ @Beta public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { builderMultimap = new SortedKeyBuilderMultimap<K, V>( checkNotNull(keyComparator), builderMultimap); return this; } /** * Specifies the ordering of the generated multimap's values for each key. * * @since 8.0 */ @Beta public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { this.valueComparator = checkNotNull(valueComparator); return this; } /** * Returns a newly-created immutable multimap. */ public ImmutableMultimap<K, V> build() { if (valueComparator != null) { for (Collection<V> values : builderMultimap.asMap().values()) { List<V> list = (List <V>) values; Collections.sort(list, valueComparator); } } return copyOf(builderMultimap); } } /** * Returns an immutable multimap containing the same mappings as {@code * multimap}. The generated multimap's key and value orderings correspond to * the iteration ordering of the {@code multimap.asMap()} view. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws NullPointerException if any key or value in {@code multimap} is * null */ public static <K, V> ImmutableMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { if (multimap instanceof ImmutableMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableMultimap<K, V> kvMultimap = (ImmutableMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } return ImmutableListMultimap.copyOf(multimap); } final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map; final transient int size; // These constants allow the deserialization code to set final fields. This // holder class makes sure they are not initialized unless an instance is // deserialized. ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map, int size) { this.map = map; this.size = size; } // mutators (not supported) /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public ImmutableCollection<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public ImmutableCollection<V> replaceValues(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public void clear() { throw new UnsupportedOperationException(); } /** * Returns an immutable collection of the values for the given key. If no * mappings in the multimap have the provided key, an empty immutable * collection is returned. The values are in the same order as the parameters * used to build this multimap. */ @Override public abstract ImmutableCollection<V> get(K key); /** * Returns an immutable multimap which is the inverse of this one. For every * key-value mapping in the original, the result will have a mapping with * key and value reversed. * * @since 11 */ @Beta public abstract ImmutableMultimap<V, K> inverse(); /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } boolean isPartialView(){ return map.isPartialView(); } // accessors @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { Collection<V> values = map.get(key); return values != null && values.contains(value); } @Override public boolean containsKey(@Nullable Object key) { return map.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { for (Collection<V> valueCollection : map.values()) { if (valueCollection.contains(value)) { return true; } } return false; } @Override public boolean isEmpty() { return size == 0; } @Override public int size() { return size; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return this.map.equals(that.asMap()); } return false; } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return map.toString(); } // views /** * Returns an immutable set of the distinct keys in this multimap. These keys * are ordered according to when they first appeared during the construction * of this multimap. */ @Override public ImmutableSet<K> keySet() { return map.keySet(); } /** * Returns an immutable map that associates each key with its corresponding * values in the multimap. */ @Override @SuppressWarnings("unchecked") // a widening cast public ImmutableMap<K, Collection<V>> asMap() { return (ImmutableMap) map; } private transient ImmutableCollection<Entry<K, V>> entries; /** * Returns an immutable collection of all key-value pairs in the multimap. Its * iterator traverses the values for the first key, the values for the second * key, and so on. */ @Override public ImmutableCollection<Entry<K, V>> entries() { ImmutableCollection<Entry<K, V>> result = entries; return (result == null) ? (entries = new EntryCollection<K, V>(this)) : result; } private static class EntryCollection<K, V> extends ImmutableCollection<Entry<K, V>> { final ImmutableMultimap<K, V> multimap; EntryCollection(ImmutableMultimap<K, V> multimap) { this.multimap = multimap; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>> mapIterator = this.multimap.map.entrySet().iterator(); return new UnmodifiableIterator<Entry<K, V>>() { K key; Iterator<V> valueIterator; @Override public boolean hasNext() { return (key != null && valueIterator.hasNext()) || mapIterator.hasNext(); } @Override public Entry<K, V> next() { if (key == null || !valueIterator.hasNext()) { Entry<K, ? extends ImmutableCollection<V>> entry = mapIterator.next(); key = entry.getKey(); valueIterator = entry.getValue().iterator(); } return Maps.immutableEntry(key, valueIterator.next()); } }; } @Override boolean isPartialView() { return multimap.isPartialView(); } @Override public int size() { return multimap.size(); } @Override public boolean contains(Object object) { if (object instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) object; return multimap.containsEntry(entry.getKey(), entry.getValue()); } return false; } private static final long serialVersionUID = 0; } private transient ImmutableMultiset<K> keys; /** * Returns a collection, which may contain duplicates, of all keys. The number * of times a key appears in the returned multiset equals the number of * mappings the key has in the multimap. Duplicate keys appear consecutively * in the multiset's iteration order. */ @Override public ImmutableMultiset<K> keys() { ImmutableMultiset<K> result = keys; return (result == null) ? (keys = createKeys()) : result; } private ImmutableMultiset<K> createKeys() { ImmutableMultiset.Builder<K> builder = ImmutableMultiset.builder(); for (Entry<K, ? extends ImmutableCollection<V>> entry : map.entrySet()) { builder.addCopies(entry.getKey(), entry.getValue().size()); } return builder.build(); } private transient ImmutableCollection<V> values; /** * Returns an immutable collection of the values in this multimap. Its * iterator traverses the values for the first key, the values for the second * key, and so on. */ @Override public ImmutableCollection<V> values() { ImmutableCollection<V> result = values; return (result == null) ? (values = new Values<V>(this)) : result; } private static class Values<V> extends ImmutableCollection<V> { final ImmutableMultimap<?, V> multimap; Values(ImmutableMultimap<?, V> multimap) { this.multimap = multimap; } @Override public UnmodifiableIterator<V> iterator() { final Iterator<? extends Entry<?, V>> entryIterator = multimap.entries().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 multimap.size(); } @Override boolean isPartialView() { return true; } private static final long serialVersionUID = 0; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableSortedSet; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; /** * GWT emulated version of {@link ImmutableSortedMap}. It's a thin wrapper * around a {@link java.util.TreeMap}. * * @author Hayward Chan */ public class ImmutableSortedMap<K, V> extends ImmutableMap<K, V> implements SortedMap<K, V> { // TODO: Confirm that ImmutableSortedMap is faster to construct and uses less // memory than TreeMap; then say so in the class Javadoc. // TODO: Create separate subclasses for empty, single-entry, and // multiple-entry instances. @SuppressWarnings("unchecked") private static final Comparator NATURAL_ORDER = Ordering.natural(); @SuppressWarnings("unchecked") private static final ImmutableSortedMap<Object, Object> NATURAL_EMPTY_MAP = create(NATURAL_ORDER); // This reference is only used by GWT compiler to infer the keys and values // of the map that needs to be serialized. private Comparator<K> unusedComparatorForSerialization; private K unusedKeyForSerialization; private V unusedValueForSerialization; private transient final SortedMap<K, V> sortedDelegate; // The comparator used by this map. It's the same as that of sortedDelegate, // except that when sortedDelegate's comparator is null, it points to a // non-null instance of Ordering.natural(). private transient final Comparator<K> comparator; // If map has a null comparator, the keys should have a natural ordering, // even though K doesn't explicitly implement Comparable. @SuppressWarnings("unchecked") ImmutableSortedMap(SortedMap<K, ? extends V> delegate) { super(delegate); this.comparator = (delegate.comparator() == null) ? NATURAL_ORDER : delegate.comparator(); this.sortedDelegate = Collections.unmodifiableSortedMap(delegate); } private static <K, V> ImmutableSortedMap<K, V> create( Comparator<? super K> comparator, Entry<? extends K, ? extends V>... entries) { checkNotNull(comparator); SortedMap<K, V> delegate = Maps.newTreeMap(comparator); for (Entry<? extends K, ? extends V> entry : entries) { delegate.put(entry.getKey(), entry.getValue()); } return new ImmutableSortedMap<K, V>(delegate); } // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableSortedMap<K, V> of() { return (ImmutableSortedMap) NATURAL_EMPTY_MAP; } public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) { return create(Ordering.natural(), entryOf(k1, v1)); } 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(); } 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(); } 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(); } 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(); } public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> copyOf(Map<? extends K, ? extends V> map) { return copyOfInternal(map, Ordering.natural()); } public static <K, V> ImmutableSortedMap<K, V> copyOf( Map<? extends K, ? extends V> map, Comparator<? super K> comparator) { return copyOfInternal(map, checkNotNull(comparator)); } public static <K, V> ImmutableSortedMap<K, V> copyOfSorted( SortedMap<K, ? extends V> map) { // If map has a null comparator, the keys should have a natural ordering, // even though K doesn't explicitly implement Comparable. @SuppressWarnings("unchecked") Comparator<? super K> comparator = (map.comparator() == null) ? NATURAL_ORDER : map.comparator(); return copyOfInternal(map, comparator); } private static <K, V> ImmutableSortedMap<K, V> copyOfInternal( Map<? extends K, ? extends V> map, Comparator<? super K> comparator) { if (map instanceof ImmutableSortedMap) { // TODO: 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; Comparator<?> comparator2 = kvMap.comparator(); boolean sameComparator = (comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2); if (sameComparator) { return kvMap; } } SortedMap<K, V> delegate = Maps.newTreeMap(comparator); for (Entry<? extends K, ? extends V> entry : map.entrySet()) { putEntryWithChecks(delegate, entry); } return new ImmutableSortedMap<K, V>(delegate); } private static <K, V> void putEntryWithChecks( SortedMap<K, V> map, Entry<? extends K, ? extends V> entry) { K key = checkNotNull(entry.getKey()); V value = checkNotNull(entry.getValue()); if (map.containsKey(key)) { // When a collision happens, the colliding entry is the first entry // of the tail map. Entry<K, V> previousEntry = map.tailMap(key).entrySet().iterator().next(); throw new IllegalArgumentException( "Duplicate keys in mappings " + previousEntry.getKey() + "=" + previousEntry.getValue() + " and " + key + "=" + value); } map.put(key, value); } public static <K extends Comparable<K>, V> Builder<K, V> naturalOrder() { return new Builder<K, V>(Ordering.natural()); } public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) { return new Builder<K, V>(comparator); } public static <K extends Comparable<K>, V> Builder<K, V> reverseOrder() { return new Builder<K, V>(Ordering.natural().reverse()); } public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { private final Comparator<? super K> comparator; public Builder(Comparator<? super K> comparator) { this.comparator = checkNotNull(comparator); } @Override public Builder<K, V> put(K key, V value) { entries.add(entryOf(key, value)); return this; } @Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { super.put(entry); return this; } @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; } @Override public ImmutableSortedMap<K, V> build() { SortedMap<K, V> delegate = Maps.newTreeMap(comparator); for (Entry<? extends K, ? extends V> entry : entries) { putEntryWithChecks(delegate, entry); } return new ImmutableSortedMap<K, V>(delegate); } } private transient ImmutableSortedSet<K> keySet; @Override public ImmutableSortedSet<K> keySet() { ImmutableSortedSet<K> ks = keySet; return (ks == null) ? (keySet = createKeySet()) : ks; } private ImmutableSortedSet<K> createKeySet() { // the keySet() of the delegate is only a Set and TreeMap.navigatableKeySet // is not available in GWT yet. To keep the code simple and code size more, // we make a copy here, instead of creating a view of it. // // TODO: revisit if it's unbearably slow or when GWT supports // TreeMap.navigatbleKeySet(). return ImmutableSortedSet.copyOf(comparator, sortedDelegate.keySet()); } public Comparator<? super K> comparator() { return comparator; } public K firstKey() { return sortedDelegate.firstKey(); } public K lastKey() { return sortedDelegate.lastKey(); } K higher(K k) { Iterator<K> iterator = keySet().tailSet(k).iterator(); while (iterator.hasNext()) { K tmp = iterator.next(); if (comparator().compare(k, tmp) < 0) { return tmp; } } return null; } public ImmutableSortedMap<K, V> headMap(K toKey) { checkNotNull(toKey); return new ImmutableSortedMap<K, V>(sortedDelegate.headMap(toKey)); } ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) { checkNotNull(toKey); if (inclusive) { K tmp = higher(toKey); if (tmp == null) { return this; } toKey = tmp; } return headMap(toKey); } public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) { checkNotNull(fromKey); checkNotNull(toKey); checkArgument(comparator.compare(fromKey, toKey) <= 0); return new ImmutableSortedMap<K, V>(sortedDelegate.subMap(fromKey, toKey)); } ImmutableSortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive){ checkNotNull(fromKey); checkNotNull(toKey); checkArgument(comparator.compare(fromKey, toKey) <= 0); return tailMap(fromKey, fromInclusive).headMap(toKey, toInclusive); } public ImmutableSortedMap<K, V> tailMap(K fromKey) { checkNotNull(fromKey); return new ImmutableSortedMap<K, V>(sortedDelegate.tailMap(fromKey)); } public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) { checkNotNull(fromKey); if (!inclusive) { fromKey = higher(fromKey); if (fromKey == null) { return emptyMap(comparator()); } } return tailMap(fromKey); } static <K, V> ImmutableSortedMap<K, V> emptyMap(Comparator<? super K> comparator) { if (comparator == NATURAL_ORDER) { return (ImmutableSortedMap) NATURAL_EMPTY_MAP; } return create(comparator); } }
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.testing; import static com.google.common.base.Preconditions.checkNotNull; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Chris Povirk */ final class Platform { /** * Serializes and deserializes the specified object (a no-op under GWT). */ @SuppressWarnings("unchecked") static <T> T reserialize(T object) { return checkNotNull(object); } private Platform() {} }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent; /** * Emulation of Callable. * * @author Charles Fry */ public interface Callable<V> { V call() throws Exception; }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent; /** * Emulation of ExecutionException. * * @author fry@google.com (Charles Fry) */ public class ExecutionException extends Exception { protected ExecutionException() { } protected ExecutionException(String message) { super(message); } public ExecutionException(String message, Throwable cause) { super(message, cause); } public ExecutionException(Throwable cause) { super(cause); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent; import java.util.Map; /** * Minimal GWT emulation of a map providing atomic operations. * * @author Jesse Wilson */ public interface ConcurrentMap<K, V> extends Map<K, V> { V putIfAbsent(K key, V value); boolean remove(Object key, Object value); V replace(K key, V value); boolean replace(K key, V oldValue, V newValue); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent.atomic; /** * GWT emulated version of {@link AtomicLong}. It's a thin wrapper * around the primitive {@code long}. * * @author Jige Yu */ public class AtomicLong extends Number implements java.io.Serializable { private long value; public AtomicLong(long initialValue) { this.value = initialValue; } public AtomicLong() { } public final long get() { return value; } public final void set(long newValue) { value = newValue; } public final void lazySet(long newValue) { set(newValue); } public final long getAndSet(long newValue) { long current = value; value = newValue; return current; } public final boolean compareAndSet(long expect, long update) { if (value == expect) { value = update; return true; } else { return false; } } public final long getAndIncrement() { return value++; } public final long getAndDecrement() { return value--; } public final long getAndAdd(long delta) { long current = value; value += delta; return current; } public final long incrementAndGet() { return ++value; } public final long decrementAndGet() { return --value; } public final long addAndGet(long delta) { value += delta; return value; } @Override public String toString() { return Long.toString(value); } public int intValue() { return (int) value; } public long longValue() { return value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent.atomic; /** * GWT emulated version of {@link AtomicInteger}. It's a thin wrapper * around the primitive {@code int}. * * @author Hayward Chan */ public class AtomicInteger extends Number implements java.io.Serializable { private int value; public AtomicInteger(int initialValue) { value = initialValue; } public AtomicInteger() { } public final int get() { return value; } public final void set(int newValue) { value = newValue; } public final void lazySet(int newValue) { set(newValue); } public final int getAndSet(int newValue) { int current = value; value = newValue; return current; } public final boolean compareAndSet(int expect, int update) { if (value == expect) { value = update; return true; } else { return false; } } public final int getAndIncrement() { return value++; } public final int getAndDecrement() { return value--; } public final int getAndAdd(int delta) { int current = value; value += delta; return current; } public final int incrementAndGet() { return ++value; } public final int decrementAndGet() { return --value; } public final int addAndGet(int delta) { value += delta; return value; } @Override public String toString() { return Integer.toString(value); } public int intValue() { return value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent; import java.util.AbstractMap; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Minimal emulation of {@link java.util.concurrent.ConcurrentHashMap}. * Note that javascript intepreter is <a * href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&t=DevGuideJavaCompatibility"> * single-threaded</a>, it is essentially a {@link java.util.HashMap}, * implementing the new methods introduced by {@link ConcurrentMap}. * * @author Hayward Chan */ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> { private final Map<K, V> backingMap; public ConcurrentHashMap() { this.backingMap = new HashMap<K, V>(); } public ConcurrentHashMap(int initialCapacity) { this.backingMap = new HashMap<K, V>(initialCapacity); } public ConcurrentHashMap(int initialCapacity, float loadFactor) { this.backingMap = new HashMap<K, V>(initialCapacity, loadFactor); } public ConcurrentHashMap(Map<? extends K, ? extends V> t) { this.backingMap = new HashMap<K, V>(t); } public V putIfAbsent(K key, V value) { if (!containsKey(key)) { return put(key, value); } else { return get(key); } } public boolean remove(Object key, Object value) { if (containsKey(key) && get(key).equals(value)) { remove(key); return true; } else { return false; } } public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) { throw new NullPointerException(); } else if (containsKey(key) && get(key).equals(oldValue)) { put(key, newValue); return true; } else { return false; } } public V replace(K key, V value) { if (value == null) { throw new NullPointerException(); } else if (containsKey(key)) { return put(key, value); } else { return null; } } @Override public boolean containsKey(Object key) { if (key == null) { throw new NullPointerException(); } return backingMap.containsKey(key); } @Override public V get(Object key) { if (key == null) { throw new NullPointerException(); } return backingMap.get(key); } @Override public V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException(); } return backingMap.put(key, value); } @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } return backingMap.containsValue(value); } @Override public V remove(Object key) { if (key == null) { throw new NullPointerException(); } return backingMap.remove(key); } @Override public Set<Entry<K, V>> entrySet() { return backingMap.entrySet(); } public boolean contains(Object value) { return containsValue(value); } public Enumeration<V> elements() { return Collections.enumeration(values()); } public Enumeration<K> keys() { return Collections.enumeration(keySet()); } }
Java
/* * 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/publicdomain/zero/1.0/ */ package java.util.concurrent; /** * GWT emulation of TimeUnit, created by removing unsupported operations from * Doug Lea's public domain version. */ public enum TimeUnit { NANOSECONDS { public long toNanos(long d) { return d; } public long toMicros(long d) { return d/(C1/C0); } public long toMillis(long d) { return d/(C2/C0); } public long toSeconds(long d) { return d/(C3/C0); } public long toMinutes(long d) { return d/(C4/C0); } public long toHours(long d) { return d/(C5/C0); } public long toDays(long d) { return d/(C6/C0); } public long convert(long d, TimeUnit u) { return u.toNanos(d); } int excessNanos(long d, long m) { return (int)(d - (m*C2)); } }, MICROSECONDS { public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); } public long toMicros(long d) { return d; } public long toMillis(long d) { return d/(C2/C1); } public long toSeconds(long d) { return d/(C3/C1); } public long toMinutes(long d) { return d/(C4/C1); } public long toHours(long d) { return d/(C5/C1); } public long toDays(long d) { return d/(C6/C1); } public long convert(long d, TimeUnit u) { return u.toMicros(d); } int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); } }, MILLISECONDS { public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); } public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); } public long toMillis(long d) { return d; } public long toSeconds(long d) { return d/(C3/C2); } public long toMinutes(long d) { return d/(C4/C2); } public long toHours(long d) { return d/(C5/C2); } public long toDays(long d) { return d/(C6/C2); } public long convert(long d, TimeUnit u) { return u.toMillis(d); } int excessNanos(long d, long m) { return 0; } }, SECONDS { public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); } public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); } public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); } public long toSeconds(long d) { return d; } public long toMinutes(long d) { return d/(C4/C3); } public long toHours(long d) { return d/(C5/C3); } public long toDays(long d) { return d/(C6/C3); } public long convert(long d, TimeUnit u) { return u.toSeconds(d); } int excessNanos(long d, long m) { return 0; } }, MINUTES { public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); } public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); } public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); } public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); } public long toMinutes(long d) { return d; } public long toHours(long d) { return d/(C5/C4); } public long toDays(long d) { return d/(C6/C4); } public long convert(long d, TimeUnit u) { return u.toMinutes(d); } int excessNanos(long d, long m) { return 0; } }, HOURS { public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); } public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); } public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); } public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); } public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); } public long toHours(long d) { return d; } public long toDays(long d) { return d/(C6/C5); } public long convert(long d, TimeUnit u) { return u.toHours(d); } int excessNanos(long d, long m) { return 0; } }, DAYS { public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); } public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); } public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); } public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); } public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); } public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); } public long toDays(long d) { return d; } public long convert(long d, TimeUnit u) { return u.toDays(d); } int excessNanos(long d, long m) { return 0; } }; // Handy constants for conversion methods static final long C0 = 1L; static final long C1 = C0 * 1000L; static final long C2 = C1 * 1000L; static final long C3 = C2 * 1000L; static final long C4 = C3 * 60L; static final long C5 = C4 * 60L; static final long C6 = C5 * 24L; static final long MAX = Long.MAX_VALUE; static long x(long d, long m, long over) { if (d > over) return Long.MAX_VALUE; if (d < -over) return Long.MIN_VALUE; return d * m; } // exceptions below changed from AbstractMethodError for GWT public long convert(long sourceDuration, TimeUnit sourceUnit) { throw new AssertionError(); } public long toNanos(long duration) { throw new AssertionError(); } public long toMicros(long duration) { throw new AssertionError(); } public long toMillis(long duration) { throw new AssertionError(); } public long toSeconds(long duration) { throw new AssertionError(); } public long toMinutes(long duration) { throw new AssertionError(); } public long toHours(long duration) { throw new AssertionError(); } public long toDays(long duration) { throw new AssertionError(); } abstract int excessNanos(long d, long m); }
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.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.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code Predicate} instances. * * <p>All methods returns serializable predicates 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 * Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Predicates { private Predicates() {} // TODO(kevinb): considering having these implement a VisitablePredicate // interface which specifies an accept(PredicateVisitor) method. /** * Returns a predicate that always evaluates to {@code true}. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> alwaysTrue() { return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); } /** * Returns a predicate that always evaluates to {@code false}. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> alwaysFalse() { return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is null. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> isNull() { return ObjectPredicate.IS_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is not null. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> notNull() { return ObjectPredicate.NOT_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the given predicate * evaluates to {@code false}. */ public static <T> Predicate<T> not(Predicate<T> predicate) { return new NotPredicate<T>(predicate); } /** * Returns a predicate that evaluates to {@code true} if each of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * true}. */ public static <T> Predicate<T> and( Iterable<? extends Predicate<? super T>> components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if each of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * true}. */ public static <T> Predicate<T> and(Predicate<? super T>... components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if both of its * components evaluate to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. */ public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) { return new AndPredicate<T>(Predicates.<T>asList( checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if any one of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. It defensively copies the iterable passed in, so * future changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * false}. */ public static <T> Predicate<T> or( Iterable<? extends Predicate<? super T>> components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if any one of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. It defensively copies the array passed in, so * future changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * false}. */ public static <T> Predicate<T> or(Predicate<? super T>... components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if either of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. */ public static <T> Predicate<T> or( Predicate<? super T> first, Predicate<? super T> second) { return new OrPredicate<T>(Predicates.<T>asList( checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if the object being * tested {@code equals()} the given target or both are null. */ public static <T> Predicate<T> equalTo(@Nullable T target) { return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate<T>(target); } /** * Returns a predicate that evaluates to {@code true} if the object being * tested is an instance of the given class. If the object being tested * is {@code null} this predicate evaluates to {@code false}. * * <p>If you want to filter an {@code Iterable} to narrow its type, consider * using {@link com.google.common.collect.Iterables#filter(Iterable, Class)} * in preference. * * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as * documented at {@link Predicate#apply}), the returned predicate may not be * <i>consistent with equals</i>. For example, {@code * instanceOf(ArrayList.class)} will yield different results for the two equal * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. */ @GwtIncompatible("Class.isInstance") public static Predicate<Object> instanceOf(Class<?> clazz) { return new InstanceOfPredicate(clazz); } /** * Returns a predicate that evaluates to {@code true} if the class being * tested is assignable from the given class. The returned predicate * does not allow null inputs. * * @since 10.0 */ @GwtIncompatible("Class.isAssignableFrom") @Beta public static Predicate<Class<?>> assignableFrom(Class<?> clazz) { return new AssignableFromPredicate(clazz); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is a member of the given collection. It does not defensively * copy the collection passed in, so future changes to it will alter the * behavior of the predicate. * * <p>This method can technically accept any {@code Collection<?>}, but using * a typed collection helps prevent bugs. This approach doesn't block any * potential users since it is always possible to use {@code * Predicates.<Object>in()}. * * @param target the collection that may contain the function input */ public static <T> Predicate<T> in(Collection<? extends T> target) { return new InPredicate<T>(target); } /** * Returns the composition of a function and a predicate. For every {@code x}, * the generated predicate returns {@code predicate(function(x))}. * * @return the composition of the provided function and predicate */ public static <A, B> Predicate<A> compose( Predicate<B> predicate, Function<A, ? extends B> function) { return new CompositionPredicate<A, B>(predicate, function); } /** * Returns a predicate that evaluates to {@code true} if the * {@code CharSequence} being tested contains any match for the given * regular expression pattern. The test used is equivalent to * {@code Pattern.compile(pattern).matcher(arg).find()} * * @throws java.util.regex.PatternSyntaxException if the pattern is invalid * @since 3.0 */ @GwtIncompatible(value = "java.util.regex.Pattern") public static Predicate<CharSequence> containsPattern(String pattern) { return new ContainsPatternPredicate(pattern); } /** * Returns a predicate that evaluates to {@code true} if the * {@code CharSequence} being tested contains any match for the given * regular expression pattern. The test used is equivalent to * {@code pattern.matcher(arg).find()} * * @since 3.0 */ @GwtIncompatible(value = "java.util.regex.Pattern") public static Predicate<CharSequence> contains(Pattern pattern) { return new ContainsPatternPredicate(pattern); } // End public API, begin private implementation classes. // Package private for GWT serialization. enum ObjectPredicate implements Predicate<Object> { ALWAYS_TRUE { @Override public boolean apply(@Nullable Object o) { return true; } }, ALWAYS_FALSE { @Override public boolean apply(@Nullable Object o) { return false; } }, IS_NULL { @Override public boolean apply(@Nullable Object o) { return o == null; } }, NOT_NULL { @Override public boolean apply(@Nullable Object o) { return o != null; } }; @SuppressWarnings("unchecked") // these Object predicates work for any T <T> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** @see Predicates#not(Predicate) */ private static class NotPredicate<T> implements Predicate<T>, Serializable { final Predicate<T> predicate; NotPredicate(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public boolean apply(T t) { return !predicate.apply(t); } @Override public int hashCode() { return ~predicate.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof NotPredicate) { NotPredicate<?> that = (NotPredicate<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public String toString() { return "Not(" + predicate.toString() + ")"; } private static final long serialVersionUID = 0; } private static final Joiner COMMA_JOINER = Joiner.on(","); /** @see Predicates#and(Iterable) */ private static class AndPredicate<T> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private AndPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(T t) { for (int i = 0; i < components.size(); i++) { if (!components.get(i).apply(t)) { return false; } } return true; } @Override public int hashCode() { // 0x12472c2c is a random number to help avoid collisions with OrPredicate return components.hashCode() + 0x12472c2c; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof AndPredicate) { AndPredicate<?> that = (AndPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return "And(" + COMMA_JOINER.join(components) + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#or(Iterable) */ private static class OrPredicate<T> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private OrPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(T t) { for (int i = 0; i < components.size(); i++) { if (components.get(i).apply(t)) { return true; } } return false; } @Override public int hashCode() { // 0x053c91cf is a random number to help avoid collisions with AndPredicate return components.hashCode() + 0x053c91cf; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof OrPredicate) { OrPredicate<?> that = (OrPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return "Or(" + COMMA_JOINER.join(components) + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#equalTo(Object) */ private static class IsEqualToPredicate<T> implements Predicate<T>, Serializable { private final T target; private IsEqualToPredicate(T target) { this.target = target; } @Override public boolean apply(T t) { return target.equals(t); } @Override public int hashCode() { return target.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof IsEqualToPredicate) { IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public String toString() { return "IsEqualTo(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#instanceOf(Class) */ @GwtIncompatible("Class.isInstance") private static class InstanceOfPredicate implements Predicate<Object>, Serializable { private final Class<?> clazz; private InstanceOfPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(@Nullable Object o) { return clazz.isInstance(o); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof InstanceOfPredicate) { InstanceOfPredicate that = (InstanceOfPredicate) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "IsInstanceOf(" + clazz.getName() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#assignableFrom(Class) */ @GwtIncompatible("Class.isAssignableFrom") private static class AssignableFromPredicate implements Predicate<Class<?>>, Serializable { private final Class<?> clazz; private AssignableFromPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(Class<?> input) { return clazz.isAssignableFrom(input); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof AssignableFromPredicate) { AssignableFromPredicate that = (AssignableFromPredicate) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "IsAssignableFrom(" + clazz.getName() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#in(Collection) */ private static class InPredicate<T> implements Predicate<T>, Serializable { private final Collection<?> target; private InPredicate(Collection<?> target) { this.target = checkNotNull(target); } @Override public boolean apply(T t) { try { return target.contains(t); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof InPredicate) { InPredicate<?> that = (InPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public int hashCode() { return target.hashCode(); } @Override public String toString() { return "In(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#compose(Predicate, Function) */ private static class CompositionPredicate<A, B> implements Predicate<A>, Serializable { final Predicate<B> p; final Function<A, ? extends B> f; private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { this.p = checkNotNull(p); this.f = checkNotNull(f); } @Override public boolean apply(A a) { return p.apply(f.apply(a)); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof CompositionPredicate) { CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; return f.equals(that.f) && p.equals(that.p); } return false; } @Override public int hashCode() { return f.hashCode() ^ p.hashCode(); } @Override public String toString() { return p.toString() + "(" + f.toString() + ")"; } private static final long serialVersionUID = 0; } /** * @see Predicates#contains(Pattern) * @see Predicates#containsPattern(String) */ @GwtIncompatible("Only used by other GWT-incompatible code.") private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable { final Pattern pattern; ContainsPatternPredicate(Pattern pattern) { this.pattern = checkNotNull(pattern); } ContainsPatternPredicate(String patternStr) { this(Pattern.compile(patternStr)); } @Override public boolean apply(CharSequence t) { return pattern.matcher(t).find(); } @Override public int hashCode() { // Pattern uses Object.hashCode, so we have to reach // inside to build a hashCode consistent with equals. return Objects.hashCode(pattern.pattern(), pattern.flags()); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof ContainsPatternPredicate) { ContainsPatternPredicate that = (ContainsPatternPredicate) obj; // Pattern uses Object (identity) equality, so we have to reach // inside to compare individual fields. return Objects.equal(pattern.pattern(), that.pattern.pattern()) && Objects.equal(pattern.flags(), that.pattern.flags()); } return false; } @Override public String toString() { return Objects.toStringHelper(this) .add("pattern", pattern) .add("pattern.flags", Integer.toHexString(pattern.flags())) .toString(); } private static final long serialVersionUID = 0; } @SuppressWarnings("unchecked") private static <T> List<Predicate<? super T>> asList( Predicate<? super T> first, Predicate<? super T> second) { return Arrays.<Predicate<? super T>>asList(first, second); } private static <T> List<T> defensiveCopy(T... array) { return defensiveCopy(Arrays.asList(array)); } static <T> List<T> defensiveCopy(Iterable<T> iterable) { ArrayList<T> list = new ArrayList<T>(); for (T element : iterable) { list.add(checkNotNull(element)); } return list; } }
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; /** * Implemented by references that have code to run after garbage collection of their referents. * * @see FinalizableReferenceQueue * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public interface FinalizableReference { /** * Invoked on a background thread after the referent has been garbage collected unless security * restrictions prevented starting a background thread, in which case this method is invoked when * new references are created. */ void finalizeReferent(); }
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 java.io.Serializable; import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; /** * An immutable object that may contain a non-null reference to another object. Each * instance of this type either contains a non-null reference, or contains nothing (in * which case we say that the reference is "absent"); it is never said to "contain {@code * null}". * * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable * {@code T} reference. It allows you to represent "a {@code T} that must be present" and * a "a {@code T} that might be absent" as two distinct types in your program, which can * aid clarity. * * <p>Some uses of this class include * * <ul> * <li>As a method return type, as an alternative to returning {@code null} to indicate * that no value was available * <li>To distinguish between "unknown" (for example, not present in a map) and "known to * have no value" (present in the map, with value {@code Optional.absent()}) * <li>To wrap nullable references for storage in a collection that does not support * {@code null} (though there are * <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections"> * several other approaches to this</a> that should be considered first) * </ul> * * <p>A common alternative to using this class is to find or create a suitable * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the * type in question. * * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" * construct from other programming environments, though it may bear some similarities. * * <p>See the Guava User Guide article on <a * href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional"> * using {@code Optional}</a>. * * @param <T> the type of instance that can be contained. {@code Optional} is naturally * covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code * Optional<S>} for any supertype {@code S} of {@code T}. * @author Kurt Alfred Kluever * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible(serializable = true) public abstract class Optional<T> implements Serializable { /** * Returns an {@code Optional} instance with no contained reference. */ @SuppressWarnings("unchecked") public static <T> Optional<T> absent() { return (Optional<T>) Absent.INSTANCE; } /** * Returns an {@code Optional} instance containing the given non-null reference. */ public static <T> Optional<T> of(T reference) { return new Present<T>(checkNotNull(reference)); } /** * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that * reference; otherwise returns {@link Optional#absent}. */ public static <T> Optional<T> fromNullable(@Nullable T nullableReference) { return (nullableReference == null) ? Optional.<T>absent() : new Present<T>(nullableReference); } Optional() {} /** * Returns {@code true} if this holder contains a (non-null) instance. */ public abstract boolean isPresent(); /** * Returns the contained instance, which must be present. If the instance might be * absent, use {@link #or(Object)} or {@link #orNull} instead. * * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns * {@code false}) */ public abstract T get(); /** * Returns the contained instance if it is present; {@code defaultValue} otherwise. If * no default value should be required because the instance is known to be present, use * {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}. */ public abstract T or(T defaultValue); /** * Returns this {@code Optional} if it has a value present; {@code secondChoice} * otherwise. */ public abstract Optional<T> or(Optional<? extends T> secondChoice); /** * Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the * supplier returns {@code null}, a {@link NullPointerException} will be thrown. * * @throws NullPointerException if the supplier returns {@code null} */ public abstract T or(Supplier<? extends T> supplier); /** * Returns the contained instance if it is present; {@code null} otherwise. If the * instance is known to be present, use {@link #get()} instead. */ @Nullable public abstract T orNull(); /** * Returns an immutable singleton {@link Set} whose only element is the * contained instance if it is present; an empty immutable {@link Set} * otherwise. * * @since 11.0 */ public abstract Set<T> asSet(); /** * Returns {@code true} if {@code object} is an {@code Optional} instance, and either * the contained references are {@linkplain Object#equals equal} to each other or both * are absent. Note that {@code Optional} instances of differing parameterized types can * be equal. */ @Override public abstract boolean equals(@Nullable Object object); /** * Returns a hash code for this instance. */ @Override public abstract int hashCode(); /** * Returns a string representation for this instance. The form of this string * representation is unspecified. */ @Override public abstract String toString(); /** * Returns the value of each present instance from the supplied {@code optionals}, in order, * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are * evaluated lazily. * * @since 11.0 */ public static <T> Iterable<T> presentInstances(final Iterable<Optional<T>> optionals) { checkNotNull(optionals); return new Iterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { private final Iterator<Optional<T>> iterator = checkNotNull(optionals.iterator()); @Override protected T computeNext() { while (iterator.hasNext()) { Optional<T> optional = iterator.next(); if (optional.isPresent()) { return optional.get(); } } return endOfData(); } }; }; }; } 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.base; import com.google.common.annotations.Beta; 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 Controls: 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/off: 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 /** * @see #DC1 * * @since 8.0 */ public static final byte DC2 = 18; /** * @see #DC1 * * @since 8.0 */ public static final byte DC3 = 19; // aka XOFF /** * Transmission off. @see #XON * * @since 8.0 */ public static final byte XOFF = 19; // aka DC3 /** * @see #DC1 * * @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/Group/Record/Unit Separator: These 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; /** * @see #FS * * @since 8.0 */ public static final byte GS = 29; /** * @see #FS * * @since 8.0 */ public static final byte RS = 30; /** * @see #FS * * @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 */ @Beta public static final int MIN = 0; /** * The maximum value of an ASCII character. * * @since 9.0 */ @Beta public static final int 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) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; /** * Utility class for converting between various ASCII case formats. * * @author Mike Bostock * @since 1.0 */ @GwtCompatible public enum CaseFormat { /** * Hyphenated variable naming convention, e.g., "lower-hyphen". */ LOWER_HYPHEN(CharMatcher.is('-'), "-"), /** * C++ variable naming convention, e.g., "lower_underscore". */ LOWER_UNDERSCORE(CharMatcher.is('_'), "_"), /** * Java variable naming convention, e.g., "lowerCamel". */ LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), ""), /** * Java and C++ class naming convention, e.g., "UpperCamel". */ UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), ""), /** * Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE". */ UPPER_UNDERSCORE(CharMatcher.is('_'), "_"); private final CharMatcher wordBoundary; private final String wordSeparator; CaseFormat(CharMatcher wordBoundary, String wordSeparator) { this.wordBoundary = wordBoundary; this.wordSeparator = wordSeparator; } /** * Converts the specified {@code String s} from this format to the specified {@code format}. A * "best effort" approach is taken; if {@code s} does not conform to the assumed format, then the * behavior of this method is undefined but we make a reasonable effort at converting anyway. */ public String to(CaseFormat format, String s) { if (format == null) { throw new NullPointerException(); } if (s == null) { throw new NullPointerException(); } if (format == this) { return s; } /* optimize cases where no camel conversion is required */ switch (this) { case LOWER_HYPHEN: switch (format) { case LOWER_UNDERSCORE: return s.replace('-', '_'); case UPPER_UNDERSCORE: return Ascii.toUpperCase(s.replace('-', '_')); } break; case LOWER_UNDERSCORE: switch (format) { case LOWER_HYPHEN: return s.replace('_', '-'); case UPPER_UNDERSCORE: return Ascii.toUpperCase(s); } break; case UPPER_UNDERSCORE: switch (format) { case LOWER_HYPHEN: return Ascii.toLowerCase(s.replace('_', '-')); case LOWER_UNDERSCORE: return Ascii.toLowerCase(s); } break; } // otherwise, deal with camel conversion StringBuilder out = null; int i = 0; int j = -1; while ((j = wordBoundary.indexIn(s, ++j)) != -1) { if (i == 0) { // include some extra space for separators out = new StringBuilder(s.length() + 4 * wordSeparator.length()); out.append(format.normalizeFirstWord(s.substring(i, j))); } else { out.append(format.normalizeWord(s.substring(i, j))); } out.append(format.wordSeparator); i = j + wordSeparator.length(); } if (i == 0) { return format.normalizeFirstWord(s); } out.append(format.normalizeWord(s.substring(i))); return out.toString(); } private String normalizeFirstWord(String word) { switch (this) { case LOWER_CAMEL: return Ascii.toLowerCase(word); default: return normalizeWord(word); } } private String normalizeWord(String word) { switch (this) { case LOWER_HYPHEN: return Ascii.toLowerCase(word); case LOWER_UNDERSCORE: return Ascii.toLowerCase(word); case LOWER_CAMEL: return firstCharOnlyToUpper(word); case UPPER_CAMEL: return firstCharOnlyToUpper(word); case UPPER_UNDERSCORE: return Ascii.toUpperCase(word); } throw new RuntimeException("unknown case: " + this); } private static String firstCharOnlyToUpper(String word) { int length = word.length(); if (length == 0) { return word; } return new StringBuilder(length) .append(Ascii.toUpperCase(word.charAt(0))) .append(Ascii.toLowerCase(word.substring(1))) .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.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) 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 */ 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) 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.base; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.concurrent.TimeUnit; /** * An object that measures elapsed time in nanoseconds. It is useful to measure * elapsed time using this class instead of direct calls to {@link * System#nanoTime} for a few reasons: * * <ul> * <li>An alternate time source can be substituted, for testing or performance * reasons. * <li>As documented by {@code nanoTime}, the value returned has no absolute * meaning, and can only be interpreted as relative to another timestamp * returned by {@code nanoTime} at a different time. {@code Stopwatch} is a * more effective abstraction because it exposes only these relative values, * not the absolute ones. * </ul> * * <p>Basic usage: * <pre> * Stopwatch stopwatch = new Stopwatch().{@link #start start}(); * doSomething(); * stopwatch.{@link #stop stop}(); // optional * * long millis = stopwatch.{@link #elapsedMillis elapsedMillis}(); * * log.info("that took: " + stopwatch); // formatted string like "12.3 ms" * </pre> * * <p>Stopwatch methods are not idempotent; it is an error to start or stop a * stopwatch that is already in the desired state. * * <p>When testing code that uses this class, use the {@linkplain * #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker. * <!-- TODO(kevinb): restore the "such as" --> This allows you to * simulate any valid behavior of the stopwatch. * * <p><b>Note:</b> This class is not thread-safe. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible(emulated=true) public final class Stopwatch { private final Ticker ticker; private boolean isRunning; private long elapsedNanos; private long startTick; /** * Creates (but does not start) a new stopwatch using {@link System#nanoTime} * as its time source. */ public Stopwatch() { this(Ticker.systemTicker()); } /** * Creates (but does not start) a new stopwatch, using the specified time * source. */ public Stopwatch(Ticker ticker) { this.ticker = checkNotNull(ticker); } /** * Returns {@code true} if {@link #start()} has been called on this stopwatch, * and {@link #stop()} has not been called since the last call to {@code * start()}. */ public boolean isRunning() { return isRunning; } /** * Starts the stopwatch. * * @return this {@code Stopwatch} instance * @throws IllegalStateException if the stopwatch is already running. */ public Stopwatch start() { checkState(!isRunning); isRunning = true; startTick = ticker.read(); return this; } /** * Stops the stopwatch. Future reads will return the fixed duration that had * elapsed up to this point. * * @return this {@code Stopwatch} instance * @throws IllegalStateException if the stopwatch is already stopped. */ public Stopwatch stop() { long tick = ticker.read(); checkState(isRunning); isRunning = false; elapsedNanos += tick - startTick; return this; } /** * Sets the elapsed time for this stopwatch to zero, * and places it in a stopped state. * * @return this {@code Stopwatch} instance */ public Stopwatch reset() { elapsedNanos = 0; isRunning = false; return this; } private long elapsedNanos() { return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; } /** * Returns the current elapsed time shown on this stopwatch, expressed * in the desired time unit, with any fraction rounded down. * * <p>Note that the overhead of measurement can be more than a microsecond, so * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} * precision here. */ public long elapsedTime(TimeUnit desiredUnit) { return desiredUnit.convert(elapsedNanos(), NANOSECONDS); } /** * Returns the current elapsed time shown on this stopwatch, expressed * in milliseconds, with any fraction rounded down. This is identical to * {@code elapsedTime(TimeUnit.MILLISECONDS}. */ public long elapsedMillis() { return elapsedTime(MILLISECONDS); } /** * Returns a string representation of the current elapsed time; equivalent to * {@code toString(4)} (four significant figures). */ @GwtIncompatible("String.format()") @Override public String toString() { return toString(4); } /** * Returns a string representation of the current elapsed time, choosing an * appropriate unit and using the specified number of significant figures. * For example, at the instant when {@code elapsedTime(NANOSECONDS)} would * return {1234567}, {@code toString(4)} returns {@code "1.235 ms"}. */ @GwtIncompatible("String.format()") public String toString(int significantDigits) { long nanos = elapsedNanos(); TimeUnit unit = chooseUnit(nanos); double value = (double) nanos / NANOSECONDS.convert(1, unit); // Too bad this functionality is not exposed as a regular method call return String.format("%." + significantDigits + "g %s", value, abbreviate(unit)); } private static TimeUnit chooseUnit(long nanos) { if (SECONDS.convert(nanos, NANOSECONDS) > 0) { return SECONDS; } if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { return MILLISECONDS; } if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { return MICROSECONDS; } return NANOSECONDS; } private static String abbreviate(TimeUnit unit) { switch (unit) { case NANOSECONDS: return "ns"; case MICROSECONDS: return "\u03bcs"; // μs case MILLISECONDS: return "ms"; case SECONDS: return "s"; default: throw new AssertionError(); } } }
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) 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.util.Formatter; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code String} or {@code CharSequence} * instances. * * @author Kevin Bourrillion * @since 3.0 */ @GwtCompatible public final class Strings { private Strings() {} /** * Returns the given string if it is non-null; the empty string otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is non-null; {@code ""} if it is null */ public static String nullToEmpty(@Nullable String string) { return (string == null) ? "" : string; } /** * Returns the given string if it is nonempty; {@code null} otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is nonempty; {@code null} if it is * empty or null */ public static @Nullable String emptyToNull(@Nullable String string) { return isNullOrEmpty(string) ? null : string; } /** * Returns {@code true} if the given string is null or is the empty string. * * <p>Consider normalizing your string references with {@link #nullToEmpty}. * If you do, you can use {@link String#isEmpty()} instead of this * method, and you won't need special null-safe forms of methods like {@link * String#toUpperCase} either. Or, if you'd like to normalize "in the other * direction," converting empty strings to {@code null}, you can use {@link * #emptyToNull}. * * @param string a string reference to check * @return {@code true} if the string is null or is the empty string */ public static boolean isNullOrEmpty(@Nullable String string) { return string == null || string.length() == 0; // string.isEmpty() in Java 6 } /** * Returns a string, of length at least {@code minLength}, consisting of * {@code string} prepended with as many copies of {@code padChar} as are * necessary to reach that length. For example, * * <ul> * <li>{@code padStart("7", 3, '0')} returns {@code "007"} * <li>{@code padStart("2010", 3, '0')} returns {@code "2010"} * </ul> * * <p>See {@link Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the end of the result * @param minLength the minimum length the resulting string must have. Can be * zero or negative, in which case the input string is always returned. * @param padChar the character to insert at the beginning of the result until * the minimum length is reached * @return the padded string */ public static String padStart(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } sb.append(string); return sb.toString(); } /** * Returns a string, of length at least {@code minLength}, consisting of * {@code string} appended with as many copies of {@code padChar} as are * necessary to reach that length. For example, * * <ul> * <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"} * <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"} * </ul> * * <p>See {@link Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the beginning of the result * @param minLength the minimum length the resulting string must have. Can be * zero or negative, in which case the input string is always returned. * @param padChar the character to append to the end of the result until the * minimum length is reached * @return the padded string */ public static String padEnd(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); sb.append(string); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } return sb.toString(); } /** * Returns a string consisting of a specific number of concatenated copies of * an input string. For example, {@code repeat("hey", 3)} returns the string * {@code "heyheyhey"}. * * @param string any non-null string * @param count the number of times to repeat it; a nonnegative integer * @return a string containing {@code string} repeated {@code count} times * (the empty string if {@code count} is zero) * @throws IllegalArgumentException if {@code count} is negative */ public static String repeat(String string, int count) { checkNotNull(string); // eager for GWT. if (count <= 1) { checkArgument(count >= 0, "invalid count: %s", count); return (count == 0) ? "" : string; } // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark final int len = string.length(); final long longSize = (long) len * (long) count; final int size = (int) longSize; if (size != longSize) { throw new ArrayIndexOutOfBoundsException("Required array size too large: " + String.valueOf(longSize)); } final char[] array = new char[size]; string.getChars(0, len, array, 0); int n; for (n = len; n < size - n; n <<= 1) { System.arraycopy(array, 0, array, n, n); } System.arraycopy(array, 0, array, n, size - n); return new String(array); } /** * Returns the longest string {@code prefix} such that * {@code a.toString().startsWith(prefix) && b.toString().startsWith(prefix)}, * taking care not to split surrogate pairs. If {@code a} and {@code b} have * no common prefix, returns the empty string. * * @since 11.0 */ @Beta public static String commonPrefix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxPrefixLength = Math.min(a.length(), b.length()); int p = 0; while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) { p++; } if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) { p--; } return a.subSequence(0, p).toString(); } /** * Returns the longest string {@code suffix} such that * {@code a.toString().endsWith(suffix) && b.toString().endsWith(suffix)}, * taking care not to split surrogate pairs. If {@code a} and {@code b} have * no common suffix, returns the empty string. * * @since 11.0 */ @Beta public static String commonSuffix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxSuffixLength = Math.min(a.length(), b.length()); int s = 0; while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) { s++; } if (validSurrogatePairAt(a, a.length() - s - 1) || validSurrogatePairAt(b, b.length() - s - 1)) { s--; } return a.subSequence(a.length() - s, a.length()).toString(); } /** * True when a valid surrogate pair starts at the given {@code index} in the * given {@code string}. Out-of-range indexes return false. */ @VisibleForTesting static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1)); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Basic utility libraries and interfaces. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <h2>Contents</h2> * * <h3>String-related utilities</h3> * * <ul> * <li>{@link com.google.common.base.Ascii} * <li>{@link com.google.common.base.CaseFormat} * <li>{@link com.google.common.base.CharMatcher} * <li>{@link com.google.common.base.Charsets} * <li>{@link com.google.common.base.Joiner} * <li>{@link com.google.common.base.Splitter} * <li>{@link com.google.common.base.Strings} * </ul> * * <h3>Function types</h3> * * <ul> * <li>{@link com.google.common.base.Function}, * {@link com.google.common.base.Functions} * <li>{@link com.google.common.base.Predicate}, * {@link com.google.common.base.Predicates} * <li>{@link com.google.common.base.Equivalence}, * {@link com.google.common.base.Equivalences} * <li>{@link com.google.common.base.Supplier}, * {@link com.google.common.base.Suppliers} * </ul> * * <h3>Other</h3> * * <ul> * <li>{@link com.google.common.base.Defaults} * <li>{@link com.google.common.base.Enums} * <li>{@link com.google.common.base.Objects} * <li>{@link com.google.common.base.Optional} * <li>{@link com.google.common.base.Preconditions} * <li>{@link com.google.common.base.Stopwatch} * <li>{@link com.google.common.base.Throwables} * </ul> * */ @ParametersAreNonnullByDefault package com.google.common.base; import javax.annotation.ParametersAreNonnullByDefault;
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 java.io.Serializable; import javax.annotation.Nullable; /** * Utility methods for working with {@link Enum} instances. * * @author Steve McKay * * @since 9.0 */ @GwtCompatible @Beta public final class Enums { private Enums() {} /** * 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.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; /** * Soft 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 FinalizableSoftReference<T> extends SoftReference<T> implements FinalizableReference { /** * Constructs a new finalizable soft reference. * * @param referent to softly reference * @param queue that should finalize the referent */ protected FinalizableSoftReference(T referent, FinalizableReferenceQueue queue) { super(referent, queue.queue); queue.cleanUp(); } }
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) 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 static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** * A strategy for determining whether two instances are considered equivalent. Examples of * equivalences are the {@link Equivalences#identity() identity equivalence} and {@link * Equivalences#equals equals equivalence}. * * @author Bob Lee * @author Ben Yu * @author Gregory Kick * @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 4.0) */ @Beta @GwtCompatible public abstract class Equivalence<T> { /** * Constructor for use by subclasses. */ protected Equivalence() {} /** * Returns {@code true} if the given objects are considered equivalent. * * <p>The {@code equivalent} method implements an equivalence relation on object references: * * <ul> * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code * equivalent(x, x)} returns {@code true}. * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code * equivalent(x, y) == equivalent(y, x)}. * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if * {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code * true}, then {@code equivalent(x, z)} returns {@code true}. * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations * of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code * false} (provided that neither {@code x} nor {@code y} is modified). * </ul> */ public final boolean equivalent(@Nullable T a, @Nullable T b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return doEquivalent(a, b); } /** * Returns {@code true} if {@code a} and {@code b} are considered equivalent. * * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same * object and are not nulls. * * @since 10.0 (previously, subclasses would override equivalent()) */ protected abstract boolean doEquivalent(T a, T b); /** * Returns a hash code for {@code t}. * * <p>The {@code hash} has the following properties: * <ul> * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of * {@code hash(x}} consistently return the same value provided {@code x} remains unchanged * according to the definition of the equivalence. The hash need not remain consistent from * one execution of an application to another execution of the same application. * <li>It is <i>distributable accross equivalence</i>: for any references {@code x} and {@code y}, * if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary * that the hash be distributable accorss <i>inequivalence</i>. If {@code equivalence(x, y)} * is false, {@code hash(x) == hash(y)} may still be true. * <li>{@code hash(null)} is {@code 0}. * </ul> */ public final int hash(@Nullable T t) { if (t == null) { return 0; } return doHash(t); } /** * Returns a hash code for non-null object {@code t}. * * <p>Called by {@link #hash}. * * @since 10.0 (previously, subclasses would override hash()) */ protected abstract int doHash(T t); /** * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of * non-null objects {@code x} and {@code y}, {@code * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code * equivalence.equivalent(function.apply(a), function.apply(b))} is true. * * <p>For example: <pre> {@code * * Equivalence<Person> SAME_AGE = Equivalences.equals().onResultOf(GET_PERSON_AGE); * }</pre> * * <p>{@code function} will never be invoked with a null value. * * <p>Note that {@code function} must be consistent according to {@code this} equivalence * relation. That is, invoking {@link Function#apply} multiple times for a given value must return * equivalent results. * For example, {@code Equivalences.identity().onResultOf(Functions.toStringFunction())} is broken * because it's not guaranteed that {@link Object#toString}) always returns the same string * instance. * * @since 10.0 */ public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) { return new FunctionalEquivalence<F, T>(function, this); } /** * Returns a wrapper of {@code reference} that implements * {@link Wrapper#equals(Object) Object.equals()} such that * {@code wrap(this, a).equals(wrap(this, b))} if and only if {@code this.equivalent(a, b)}. * * @since 10.0 */ public final <S extends T> Wrapper<S> wrap(@Nullable S reference) { return new Wrapper<S>(this, reference); } /** * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an * {@link Equivalence}. * * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} * that tests equivalence using their lengths: * * <pre> {@code * equiv.wrap("a").equals(equiv.wrap("b")) // true * equiv.wrap("a").equals(equiv.wrap("hello")) // false * }</pre> * * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps. * * <pre> {@code * equiv.wrap(obj).equals(obj) // always false * }</pre> * * @since 10.0 */ @Beta public static final class Wrapper<T> implements Serializable { private final Equivalence<? super T> equivalence; @Nullable private final T reference; private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) { this.equivalence = checkNotNull(equivalence); this.reference = reference; } /** Returns the (possibly null) reference wrapped by this instance. */ @Nullable public T get() { return reference; } /** * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} * equivalence. */ @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } else if (obj instanceof Wrapper) { Wrapper<?> that = (Wrapper<?>) obj; /* * We cast to Equivalence<Object> here because we can't check the type of the reference held * by the other wrapper. But, by checking that the Equivalences are equal, we know that * whatever type it is, it is assignable to the type handled by this wrapper's equivalence. */ @SuppressWarnings("unchecked") Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; return equivalence.equals(that.equivalence) && equivalence.equivalent(this.reference, that.reference); } else { return false; } } /** * Returns the result of {@link Equivalence#hash(Object)} applied to the the wrapped reference. */ @Override public int hashCode() { return equivalence.hash(reference); } /** * Returns a string representation for this equivalence wrapper. The form of this string * representation is not specified. */ @Override public String toString() { return equivalence + ".wrap(" + reference + ")"; } private static final long serialVersionUID = 0; } /** * Returns an equivalence over iterables based on the equivalence of their elements. More * specifically, two iterables are considered equivalent if they both contain the same number of * elements, and each pair of corresponding elements is equivalent according to * {@code this}. Null iterables are equivalent to one another. * * <p>Note that this method performs a similar function for equivalences as {@link * com.google.common.collect.Ordering#lexicographical} does for orderings. * * @since 10.0 */ @GwtCompatible(serializable = true) public final <S extends T> Equivalence<Iterable<S>> pairwise() { // Ideally, the returned equivalence would support Iterable<? extends T>. However, // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. return new PairwiseEquivalence<S>(this); } /** * Returns a predicate that evaluates to true if and only if the input is * equivalent to {@code target} according to this equivalence relation. * * @since 10.0 */ public final Predicate<T> equivalentTo(@Nullable T target) { return new EquivalentToPredicate<T>(this, target); } private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable { private final Equivalence<T> equivalence; @Nullable private final T target; EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) { this.equivalence = checkNotNull(equivalence); this.target = target; } @Override public boolean apply(@Nullable T input) { return equivalence.equivalent(input, target); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj instanceof EquivalentToPredicate) { EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); } return false; } @Override public int hashCode() { return Objects.hashCode(equivalence, target); } @Override public String toString() { return equivalence + ".equivalentTo(" + target + ")"; } 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 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.CheckReturnValue; /** * An object that divides strings (or other instances of {@code CharSequence}) * into substrings, by recognizing a <i>separator</i> (a.k.a. "delimiter") * which can be expressed as a single character, literal string, regular * expression, {@code CharMatcher}, or by using a fixed substring length. This * class provides the complementary functionality to {@link Joiner}. * * <p>Here is the most basic example of {@code Splitter} usage: <pre> {@code * * Splitter.on(',').split("foo,bar")}</pre> * * This invocation returns an {@code Iterable<String>} containing {@code "foo"} * and {@code "bar"}, in that order. * * <p>By default {@code Splitter}'s behavior is very simplistic: <pre> {@code * * Splitter.on(',').split("foo,,bar, quux")}</pre> * * This returns an iterable containing {@code ["foo", "", "bar", " quux"]}. * Notice that the splitter does not assume that you want empty strings removed, * or that you wish to trim whitespace. If you want features like these, simply * ask for them: <pre> {@code * * private static final Splitter MY_SPLITTER = Splitter.on(',') * .trimResults() * .omitEmptyStrings();}</pre> * * Now {@code MY_SPLITTER.split("foo, ,bar, quux,")} returns an iterable * containing just {@code ["foo", "bar", "quux"]}. Note that the order in which * the configuration methods are called is never significant; for instance, * trimming is always applied first before checking for an empty result, * regardless of the order in which the {@link #trimResults()} and * {@link #omitEmptyStrings()} methods were invoked. * * <p><b>Warning: splitter instances are always immutable</b>; a configuration * method such as {@code omitEmptyStrings} has no effect on the instance it * is invoked on! You must store and use the new splitter instance returned by * the method. This makes splitters thread-safe, and safe to store as {@code * static final} constants (as illustrated above). <pre> {@code * * // Bad! Do not do this! * Splitter splitter = Splitter.on('/'); * splitter.trimResults(); // does nothing! * return splitter.split("wrong / wrong / wrong");}</pre> * * The separator recognized by the splitter does not have to be a single * literal character as in the examples above. See the methods {@link * #on(String)}, {@link #on(Pattern)} and {@link #on(CharMatcher)} for examples * of other ways to specify separators. * * <p><b>Note:</b> this class does not mimic any of the quirky behaviors of * similar JDK methods; for instance, it does not silently discard trailing * separators, as does {@link String#split(String)}, nor does it have a default * behavior of using five particular whitespace characters as separators, like * {@link java.util.StringTokenizer}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter"> * {@code Splitter}</a>. * * @author Julien Silland * @author Jesse Wilson * @author Kevin Bourrillion * @author Louis Wasserman * @since 1.0 */ @GwtCompatible(emulated = true) public final class Splitter { private final CharMatcher trimmer; private final boolean omitEmptyStrings; private final Strategy strategy; private final int limit; private Splitter(Strategy strategy) { this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE); } private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { this.strategy = strategy; this.omitEmptyStrings = omitEmptyStrings; this.trimmer = trimmer; this.limit = limit; } /** * Returns a splitter that uses the given single-character separator. For * example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable * containing {@code ["foo", "", "bar"]}. * * @param separator the character to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(char separator) { return on(CharMatcher.is(separator)); } /** * Returns a splitter that considers any single character matched by the * given {@code CharMatcher} to be a separator. For example, {@code * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an * iterable containing {@code ["foo", "", "bar", "quux"]}. * * @param separatorMatcher a {@link CharMatcher} that determines whether a * character is a separator * @return a splitter, with default settings, that uses this matcher */ public static Splitter on(final CharMatcher separatorMatcher) { checkNotNull(separatorMatcher); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( Splitter splitter, final CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override int separatorStart(int start) { return separatorMatcher.indexIn(toSplit, start); } @Override int separatorEnd(int separatorPosition) { return separatorPosition + 1; } }; } }); } /** * Returns a splitter that uses the given fixed string as a separator. For * example, {@code Splitter.on(", ").split("foo, bar, baz,qux")} returns an * iterable containing {@code ["foo", "bar", "baz,qux"]}. * * @param separator the literal, nonempty string to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(final String separator) { checkArgument(separator.length() != 0, "The separator may not be the empty string."); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int delimeterLength = separator.length(); positions: for (int p = start, last = toSplit.length() - delimeterLength; p <= last; p++) { for (int i = 0; i < delimeterLength; i++) { if (toSplit.charAt(i + p) != separator.charAt(i)) { continue positions; } } return p; } return -1; } @Override public int separatorEnd(int separatorPosition) { return separatorPosition + separator.length(); } }; } }); } /** * Returns a splitter that considers any subsequence matching {@code * pattern} to be a separator. For example, {@code * Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string * into lines whether it uses DOS-style or UNIX-style line terminators. * * @param separatorPattern the pattern that determines whether a subsequence * is a separator. This pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches the * empty string */ @GwtIncompatible("java.util.regex") public static Splitter on(final Pattern separatorPattern) { checkNotNull(separatorPattern); checkArgument(!separatorPattern.matcher("").matches(), "The pattern may not match the empty string: %s", separatorPattern); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( final Splitter splitter, CharSequence toSplit) { final Matcher matcher = separatorPattern.matcher(toSplit); return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { return matcher.find(start) ? matcher.start() : -1; } @Override public int separatorEnd(int separatorPosition) { return matcher.end(); } }; } }); } /** * Returns a splitter that considers any subsequence matching a given * pattern (regular expression) to be a separator. For example, {@code * Splitter.onPattern("\r?\n").split(entireFile)} splits a string into lines * whether it uses DOS-style or UNIX-style line terminators. This is * equivalent to {@code Splitter.on(Pattern.compile(pattern))}. * * @param separatorPattern the pattern that determines whether a subsequence * is a separator. This pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws java.util.regex.PatternSyntaxException if {@code separatorPattern} * is a malformed expression * @throws IllegalArgumentException if {@code separatorPattern} matches the * empty string */ @GwtIncompatible("java.util.regex") public static Splitter onPattern(String separatorPattern) { return on(Pattern.compile(separatorPattern)); } /** * Returns a splitter that divides strings into pieces of the given length. * For example, {@code Splitter.fixedLength(2).split("abcde")} returns an * iterable containing {@code ["ab", "cd", "e"]}. The last piece can be * smaller than {@code length} but will never be empty. * * @param length the desired length of pieces after splitting * @return a splitter, with default settings, that can split into fixed sized * pieces */ public static Splitter fixedLength(final int length) { checkArgument(length > 0, "The length may not be less than 1"); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( final Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int nextChunkStart = start + length; return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); } @Override public int separatorEnd(int separatorPosition) { return separatorPosition; } }; } }); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * automatically omits empty strings from the results. For example, {@code * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an * iterable containing only {@code ["a", "b", "c"]}. * * <p>If either {@code trimResults} option is also specified when creating a * splitter, that splitter always trims results first before checking for * emptiness. So, for example, {@code * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns * an empty iterable. * * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} * to return an empty iterable, but when using this option, it can (if the * input sequence consists of nothing but separators). * * @return a splitter with the desired configuration */ @CheckReturnValue public Splitter omitEmptyStrings() { return new Splitter(strategy, true, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter but * stops splitting after it reaches the limit. * The limit defines the maximum number of items returned by the iterator. * * <p>For example, * {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the * omitted strings do no count. Hence, * {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} * returns an iterable containing {@code ["a", "b", "c,d"}. * When trim is requested, all entries, including the last are trimmed. Hence * {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")} * results in @{code ["a", "b", "c , d"]}. * * @param limit the maximum number of items returns * @return a splitter with the desired configuration * @since 9.0 */ @CheckReturnValue public Splitter limit(int limit) { checkArgument(limit > 0, "must be greater than zero: %s", limit); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * automatically removes leading and trailing {@linkplain * CharMatcher#WHITESPACE whitespace} from each returned substring; equivalent * to {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable * containing {@code ["a", "b", "c"]}. * * @return a splitter with the desired configuration */ @CheckReturnValue public Splitter trimResults() { return trimResults(CharMatcher.WHITESPACE); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * removes all leading or trailing characters matching the given {@code * CharMatcher} from each returned substring. For example, {@code * Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} * returns an iterable containing {@code ["a ", "b_ ", "c"]}. * * @param trimmer a {@link CharMatcher} that determines whether a character * should be removed from the beginning/end of a subsequence * @return a splitter with the desired configuration */ // TODO(kevinb): throw if a trimmer was already specified! @CheckReturnValue public Splitter trimResults(CharMatcher trimmer) { checkNotNull(trimmer); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Splits {@code sequence} into string components and makes them available * through an {@link Iterator}, which may be lazily evaluated. * * @param sequence the sequence of characters to split * @return an iteration over the segments split from the parameter. */ public Iterable<String> split(final CharSequence sequence) { checkNotNull(sequence); return new Iterable<String>() { @Override public Iterator<String> iterator() { return spliterator(sequence); } }; } private Iterator<String> spliterator(CharSequence sequence) { return strategy.iterator(this, sequence); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified separator. * * @since 10.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(String separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified key-value * splitter. * * @since 10.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { return new MapSplitter(this, keyValueSplitter); } /** * An object that splits strings into maps as {@code Splitter} splits * iterables and lists. Like {@code Splitter}, it is thread-safe and * immutable. * * @since 10.0 */ @Beta public static final class MapSplitter { private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry"; private final Splitter outerSplitter; private final Splitter entrySplitter; private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) { this.outerSplitter = outerSplitter; // only "this" is passed this.entrySplitter = checkNotNull(entrySplitter); } /** * Splits {@code sequence} into substrings, splits each substring into * an entry, and returns an unmodifiable map with each of the entries. For * example, <code> * Splitter.on(';').trimResults().withKeyValueSeparator("=>") * .split("a=>b ; c=>b") * </code> will return a mapping from {@code "a"} to {@code "b"} and * {@code "c"} to {@code b}. * * <p>The returned map preserves the order of the entries from * {@code sequence}. * * @throws IllegalArgumentException if the specified sequence does not split * into valid map entries, or if there are duplicate keys */ public Map<String, String> split(CharSequence sequence) { Map<String, String> map = new LinkedHashMap<String, String>(); for (String entry : outerSplitter.split(sequence)) { Iterator<String> entryFields = entrySplitter.spliterator(entry); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String key = entryFields.next(); checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String value = entryFields.next(); map.put(key, value); checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); } return Collections.unmodifiableMap(map); } } private interface Strategy { Iterator<String> iterator(Splitter splitter, CharSequence toSplit); } private abstract static class SplittingIterator extends AbstractIterator<String> { final CharSequence toSplit; final CharMatcher trimmer; final boolean omitEmptyStrings; /** * Returns the first index in {@code toSplit} at or after {@code start} * that contains the separator. */ abstract int separatorStart(int start); /** * Returns the first index in {@code toSplit} after {@code * separatorPosition} that does not contain a separator. This method is only * invoked after a call to {@code separatorStart}. */ abstract int separatorEnd(int separatorPosition); int offset = 0; int limit; protected SplittingIterator(Splitter splitter, CharSequence toSplit) { this.trimmer = splitter.trimmer; this.omitEmptyStrings = splitter.omitEmptyStrings; this.limit = splitter.limit; this.toSplit = toSplit; } @Override protected String computeNext() { while (offset != -1) { int start = offset; int end; int separatorPosition = separatorStart(offset); if (separatorPosition == -1) { end = toSplit.length(); offset = -1; } else { end = separatorPosition; offset = separatorEnd(separatorPosition); } while (start < end && trimmer.matches(toSplit.charAt(start))) { start++; } while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } if (omitEmptyStrings && start == end) { continue; } if (limit == 1) { // The limit has been reached, return the rest of the string as the // final item. This is tested after empty string removal so that // empty strings do not count towards the limit. end = toSplit.length(); offset = -1; // Since we may have changed the end, we need to trim it again. while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } } else { limit--; } return toSplit.subSequence(start, end).toString(); } return endOfData(); } } }
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 javax.annotation.Nullable; /** * Determines a true or false value for a given input. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code * Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Predicate<T> { /** * Returns the result of applying this predicate to {@code input}. 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 (a, b)} implies that {@code predicate.apply(a) == * predicate.apply(b))}. * </ul> * * @throws NullPointerException if {@code input} is null and this predicate does not accept null * arguments */ boolean apply(@Nullable T input); /** * Indicates whether another object is equal to this predicate. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Predicate} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code this.apply(t) == that.apply(t)} for all {@code t} of type * {@code T}). Note that a {@code false} result from this method does not imply that the * predicates are known <i>not</i> to be interchangeable. */ @Override boolean equals(@Nullable Object object); }
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 javax.annotation.Nullable; /** * Determines an output value based on an input value. * * <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 Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Function<F, T> { /** * Returns the result of applying this function to {@code input}. 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 (a, b)} implies that {@code Objects.equal(function.apply(a), * function.apply(b))}. * </ul> * * @throws NullPointerException if {@code input} is null and this function does not accept null * arguments */ T apply(@Nullable F input); /** * Indicates whether another object is equal to this function. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Function} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code Objects.equal(this.apply(f), that.apply(f))} is true for all * {@code f} of type {@code F}. Note that a {@code false} result from this method does not imply * that the functions are known <i>not</i> to be interchangeable. */ @Override boolean equals(@Nullable Object object); }
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.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.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.CheckReturnValue; /** * Determines a true or false value for any Java {@code char} value, just as {@link Predicate} does * for any {@link Object}. Also offers basic text processing methods based on this function. * Implementations are strongly encouraged to be side-effect-free and immutable. * * <p>Throughout the documentation of this class, the phrase "matching character" is used to mean * "any character {@code c} for which {@code this.matches(c)} returns {@code true}". * * <p><b>Note:</b> This class deals only with {@code char} values; it does not understand * supplementary Unicode code points in the range {@code 0x10000} to {@code 0x10FFFF}. Such logical * characters are encoded into a {@code String} using surrogate pairs, and a {@code CharMatcher} * treats these just as two separate characters. * * <p>Example usages: <pre> * String trimmed = {@link #WHITESPACE WHITESPACE}.{@link #trimFrom trimFrom}(userInput); * if ({@link #ASCII ASCII}.{@link #matchesAllOf matchesAllOf}(s)) { ... }</pre> * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher"> * {@code CharMatcher}</a>. * * @author Kevin Bourrillion * @since 1.0 */ @Beta // Possibly change from chars to code points; decide constants vs. methods @GwtCompatible public abstract class CharMatcher implements Predicate<Character> { // Constants // Excludes 2000-2000a, which is handled as a range private static final String BREAKING_WHITESPACE_CHARS = "\t\n\013\f\r \u0085\u1680\u2028\u2029\u205f\u3000"; // Excludes 2007, which is handled as a gap in a pair of ranges private static final String NON_BREAKING_WHITESPACE_CHARS = "\u00a0\u180e\u202f"; /** * Determines whether a character is whitespace according to the latest Unicode standard, as * illustrated * <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>. * This is not the same definition used by other Java APIs. (See a * <a href="http://spreadsheets.google.com/pub?key=pd8dAQyHbdewRsnE5x5GzKQ">comparison of several * definitions of "whitespace"</a>.) * * <p><b>Note:</b> as the Unicode definition evolves, we will modify this constant to keep it up * to date. */ public static final CharMatcher WHITESPACE = anyOf(BREAKING_WHITESPACE_CHARS + NON_BREAKING_WHITESPACE_CHARS) .or(inRange('\u2000', '\u200a')) .withToString("CharMatcher.WHITESPACE") .precomputed(); /** * Determines whether a character is a breaking whitespace (that is, a whitespace which can be * interpreted as a break between words for formatting purposes). See {@link #WHITESPACE} for a * discussion of that term. * * @since 2.0 */ public static final CharMatcher BREAKING_WHITESPACE = anyOf(BREAKING_WHITESPACE_CHARS) .or(inRange('\u2000', '\u2006')) .or(inRange('\u2008', '\u200a')) .withToString("CharMatcher.BREAKING_WHITESPACE") .precomputed(); /** * Determines whether a character is ASCII, meaning that its code point is less than 128. */ public static final CharMatcher ASCII = inRange('\0', '\u007f') .withToString("CharMatcher.ASCII"); /** * Determines whether a character is a digit according to * <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>. */ public static final CharMatcher DIGIT; static { CharMatcher digit = inRange('0', '9'); String zeroes = "\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6\u0c66" + "\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946" + "\u19d0\u1b50\u1bb0\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10"; for (char base : zeroes.toCharArray()) { digit = digit.or(inRange(base, (char) (base + 9))); } DIGIT = digit.withToString("CharMatcher.DIGIT").precomputed(); } /** * Determines whether a character is a digit according to {@link Character#isDigit(char) Java's * definition}. If you only care to match ASCII digits, you can use {@code inRange('0', '9')}. */ public static final CharMatcher JAVA_DIGIT = new CharMatcher() { @Override public boolean matches(char c) { return Character.isDigit(c); } @Override public String toString() { return "CharMatcher.JAVA_DIGIT"; } }; /** * Determines whether a character is a letter according to {@link Character#isLetter(char) Java's * definition}. If you only care to match letters of the Latin alphabet, you can use {@code * inRange('a', 'z').or(inRange('A', 'Z'))}. */ public static final CharMatcher JAVA_LETTER = new CharMatcher() { @Override public boolean matches(char c) { return Character.isLetter(c); } @Override public String toString() { return "CharMatcher.JAVA_LETTER"; } }; /** * Determines whether a character is a letter or digit according to {@link * Character#isLetterOrDigit(char) Java's definition}. */ public static final CharMatcher JAVA_LETTER_OR_DIGIT = new CharMatcher() { @Override public boolean matches(char c) { return Character.isLetterOrDigit(c); } @Override public String toString() { return "CharMatcher.JAVA_LETTER_OR_DIGIT"; } }; /** * Determines whether a character is upper case according to {@link Character#isUpperCase(char) * Java's definition}. */ public static final CharMatcher JAVA_UPPER_CASE = new CharMatcher() { @Override public boolean matches(char c) { return Character.isUpperCase(c); } @Override public String toString() { return "CharMatcher.JAVA_UPPER_CASE"; } }; /** * Determines whether a character is lower case according to {@link Character#isLowerCase(char) * Java's definition}. */ public static final CharMatcher JAVA_LOWER_CASE = new CharMatcher() { @Override public boolean matches(char c) { return Character.isLowerCase(c); } @Override public String toString() { return "CharMatcher.JAVA_LOWER_CASE"; } }; /** * Determines whether a character is an ISO control character as specified by {@link * Character#isISOControl(char)}. */ public static final CharMatcher JAVA_ISO_CONTROL = inRange('\u0000', '\u001f').or(inRange('\u007f', '\u009f')) .withToString("CharMatcher.JAVA_ISO_CONTROL"); /** * Determines whether a character is invisible; that is, if its Unicode category is any of * SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR, CONTROL, FORMAT, SURROGATE, and * PRIVATE_USE according to ICU4J. */ public static final CharMatcher INVISIBLE = inRange('\u0000', '\u0020') .or(inRange('\u007f', '\u00a0')) .or(is('\u00ad')) .or(inRange('\u0600', '\u0603')) .or(anyOf("\u06dd\u070f\u1680\u17b4\u17b5\u180e")) .or(inRange('\u2000', '\u200f')) .or(inRange('\u2028', '\u202f')) .or(inRange('\u205f', '\u2064')) .or(inRange('\u206a', '\u206f')) .or(is('\u3000')) .or(inRange('\ud800', '\uf8ff')) .or(anyOf("\ufeff\ufff9\ufffa\ufffb")) .withToString("CharMatcher.INVISIBLE") .precomputed(); /** * Determines whether a character is single-width (not double-width). When in doubt, this matcher * errs on the side of returning {@code false} (that is, it tends to assume a character is * double-width). * * <p><b>Note:</b> as the reference file evolves, we will modify this constant to keep it up to * date. */ public static final CharMatcher SINGLE_WIDTH = inRange('\u0000', '\u04f9') .or(is('\u05be')) .or(inRange('\u05d0', '\u05ea')) .or(is('\u05f3')) .or(is('\u05f4')) .or(inRange('\u0600', '\u06ff')) .or(inRange('\u0750', '\u077f')) .or(inRange('\u0e00', '\u0e7f')) .or(inRange('\u1e00', '\u20af')) .or(inRange('\u2100', '\u213a')) .or(inRange('\ufb50', '\ufdff')) .or(inRange('\ufe70', '\ufeff')) .or(inRange('\uff61', '\uffdc')) .withToString("CharMatcher.SINGLE_WIDTH") .precomputed(); /** Matches any character. */ public static final CharMatcher ANY = new CharMatcher() { @Override public boolean matches(char c) { return true; } @Override public int indexIn(CharSequence sequence) { return (sequence.length() == 0) ? -1 : 0; } @Override public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); Preconditions.checkPositionIndex(start, length); return (start == length) ? -1 : start; } @Override public int lastIndexIn(CharSequence sequence) { return sequence.length() - 1; } @Override public boolean matchesAllOf(CharSequence sequence) { checkNotNull(sequence); return true; } @Override public boolean matchesNoneOf(CharSequence sequence) { return sequence.length() == 0; } @Override public String removeFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } @Override public String replaceFrom(CharSequence sequence, char replacement) { char[] array = new char[sequence.length()]; Arrays.fill(array, replacement); return new String(array); } @Override public String replaceFrom(CharSequence sequence, CharSequence replacement) { StringBuilder retval = new StringBuilder(sequence.length() * replacement.length()); for (int i = 0; i < sequence.length(); i++) { retval.append(replacement); } return retval.toString(); } @Override public String collapseFrom(CharSequence sequence, char replacement) { return (sequence.length() == 0) ? "" : String.valueOf(replacement); } @Override public String trimFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } @Override public int countIn(CharSequence sequence) { return sequence.length(); } @Override public CharMatcher and(CharMatcher other) { return checkNotNull(other); } @Override public CharMatcher or(CharMatcher other) { checkNotNull(other); return this; } @Override public CharMatcher negate() { return NONE; } @Override public CharMatcher precomputed() { return this; } @Override public String toString() { return "CharMatcher.ANY"; } }; /** Matches no characters. */ public static final CharMatcher NONE = new CharMatcher() { @Override public boolean matches(char c) { return false; } @Override public int indexIn(CharSequence sequence) { checkNotNull(sequence); return -1; } @Override public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); Preconditions.checkPositionIndex(start, length); return -1; } @Override public int lastIndexIn(CharSequence sequence) { checkNotNull(sequence); return -1; } @Override public boolean matchesAllOf(CharSequence sequence) { return sequence.length() == 0; } @Override public boolean matchesNoneOf(CharSequence sequence) { checkNotNull(sequence); return true; } @Override public String removeFrom(CharSequence sequence) { return sequence.toString(); } @Override public String replaceFrom(CharSequence sequence, char replacement) { return sequence.toString(); } @Override public String replaceFrom(CharSequence sequence, CharSequence replacement) { checkNotNull(replacement); return sequence.toString(); } @Override public String collapseFrom(CharSequence sequence, char replacement) { return sequence.toString(); } @Override public String trimFrom(CharSequence sequence) { return sequence.toString(); } @Override public int countIn(CharSequence sequence) { checkNotNull(sequence); return 0; } @Override public CharMatcher and(CharMatcher other) { checkNotNull(other); return this; } @Override public CharMatcher or(CharMatcher other) { return checkNotNull(other); } @Override public CharMatcher negate() { return ANY; } @Override void setBits(LookupTable table) {} @Override public CharMatcher precomputed() { return this; } @Override public String toString() { return "CharMatcher.NONE"; } }; // Static factories /** * Returns a {@code char} matcher that matches only one specified character. */ public static CharMatcher is(final char match) { return new CharMatcher() { @Override public boolean matches(char c) { return c == match; } @Override public String replaceFrom(CharSequence sequence, char replacement) { return sequence.toString().replace(match, replacement); } @Override public CharMatcher and(CharMatcher other) { return other.matches(match) ? this : NONE; } @Override public CharMatcher or(CharMatcher other) { return other.matches(match) ? other : super.or(other); } @Override public CharMatcher negate() { return isNot(match); } @Override void setBits(LookupTable table) { table.set(match); } @Override public CharMatcher precomputed() { return this; } @Override public String toString() { return new StringBuilder("CharMatcher.is(") .append(Integer.toHexString(match)) .append(")") .toString(); } }; } /** * Returns a {@code char} matcher that matches any character except the one specified. * * <p>To negate another {@code CharMatcher}, use {@link #negate()}. */ public static CharMatcher isNot(final char match) { return new CharMatcher() { @Override public boolean matches(char c) { return c != match; } @Override public CharMatcher and(CharMatcher other) { return other.matches(match) ? super.and(other) : other; } @Override public CharMatcher or(CharMatcher other) { return other.matches(match) ? ANY : this; } @Override public CharMatcher negate() { return is(match); } @Override public String toString() { return new StringBuilder("CharMatcher.isNot(") .append(Integer.toHexString(match)) .append(")") .toString(); } }; } /** * Returns a {@code char} matcher that matches any character present in the given character * sequence. */ public static CharMatcher anyOf(final CharSequence sequence) { switch (sequence.length()) { case 0: return NONE; case 1: return is(sequence.charAt(0)); case 2: final char match1 = sequence.charAt(0); final char match2 = sequence.charAt(1); return new CharMatcher() { @Override public boolean matches(char c) { return c == match1 || c == match2; } @Override void setBits(LookupTable table) { table.set(match1); table.set(match2); } @Override public CharMatcher precomputed() { return this; } }; } final char[] chars = sequence.toString().toCharArray(); Arrays.sort(chars); // not worth collapsing duplicates return new CharMatcher() { @Override public boolean matches(char c) { return Arrays.binarySearch(chars, c) >= 0; } @Override void setBits(LookupTable table) { for (char c : chars) { table.set(c); } } @Override public String toString() { return new StringBuilder("CharMatcher.anyOf(\"").append(chars).append("\")").toString(); } }; } /** * Returns a {@code char} matcher that matches any character not present in the given character * sequence. */ public static CharMatcher noneOf(CharSequence sequence) { return anyOf(sequence).negate(); } /** * Returns a {@code char} matcher that matches any character in a given range (both endpoints are * inclusive). For example, to match any lowercase letter of the English alphabet, use {@code * CharMatcher.inRange('a', 'z')}. * * @throws IllegalArgumentException if {@code endInclusive < startInclusive} */ public static CharMatcher inRange(final char startInclusive, final char endInclusive) { checkArgument(endInclusive >= startInclusive); return new CharMatcher() { @Override public boolean matches(char c) { return startInclusive <= c && c <= endInclusive; } @Override void setBits(LookupTable table) { char c = startInclusive; while (true) { table.set(c); if (c++ == endInclusive) { break; } } } @Override public CharMatcher precomputed() { return this; } @Override public String toString() { return new StringBuilder("CharMatcher.inRange(") .append(Integer.toHexString(startInclusive)) .append(", ") .append(Integer.toHexString(endInclusive)) .append(")") .toString(); } }; } /** * Returns a matcher with identical behavior to the given {@link Character}-based predicate, but * which operates on primitive {@code char} instances instead. */ public static CharMatcher forPredicate(final Predicate<? super Character> predicate) { checkNotNull(predicate); if (predicate instanceof CharMatcher) { return (CharMatcher) predicate; } return new CharMatcher() { @Override public boolean matches(char c) { return predicate.apply(c); } @Override public boolean apply(Character character) { return predicate.apply(checkNotNull(character)); } @Override public String toString() { return new StringBuilder("CharMatcher.forPredicate(") .append(predicate) .append(')') .toString(); } }; } // Constructors /** * Constructor for use by subclasses. */ protected CharMatcher() {} // Abstract methods /** Determines a true or false value for the given character. */ public abstract boolean matches(char c); // Non-static factories /** * Returns a matcher that matches any character not matched by this matcher. */ public CharMatcher negate() { final CharMatcher original = this; return new CharMatcher() { @Override public boolean matches(char c) { return !original.matches(c); } @Override public boolean matchesAllOf(CharSequence sequence) { return original.matchesNoneOf(sequence); } @Override public boolean matchesNoneOf(CharSequence sequence) { return original.matchesAllOf(sequence); } @Override public int countIn(CharSequence sequence) { return sequence.length() - original.countIn(sequence); } @Override public CharMatcher negate() { return original; } @Override public String toString() { return original + ".negate()"; } }; } /** * Returns a matcher that matches any character matched by both this matcher and {@code other}. */ public CharMatcher and(CharMatcher other) { return new And(Arrays.asList(this, checkNotNull(other))); } private static class And extends CharMatcher { List<CharMatcher> components; And(List<CharMatcher> components) { this.components = components; // Skip defensive copy (private) } @Override public boolean matches(char c) { for (CharMatcher matcher : components) { if (!matcher.matches(c)) { return false; } } return true; } @Override public CharMatcher and(CharMatcher other) { List<CharMatcher> newComponents = new ArrayList<CharMatcher>(components); newComponents.add(checkNotNull(other)); return new And(newComponents); } @Override public String toString() { StringBuilder builder = new StringBuilder("CharMatcher.and("); Joiner.on(", ").appendTo(builder, components); return builder.append(')').toString(); } } /** * Returns a matcher that matches any character matched by either this matcher or {@code other}. */ public CharMatcher or(CharMatcher other) { return new Or(Arrays.asList(this, checkNotNull(other))); } private static class Or extends CharMatcher { List<CharMatcher> components; Or(List<CharMatcher> components) { this.components = components; // Skip defensive copy (private) } @Override public boolean matches(char c) { for (CharMatcher matcher : components) { if (matcher.matches(c)) { return true; } } return false; } @Override public CharMatcher or(CharMatcher other) { List<CharMatcher> newComponents = new ArrayList<CharMatcher>(components); newComponents.add(checkNotNull(other)); return new Or(newComponents); } @Override void setBits(LookupTable table) { for (CharMatcher matcher : components) { matcher.setBits(table); } } @Override public String toString() { StringBuilder builder = new StringBuilder("CharMatcher.or("); Joiner.on(", ").appendTo(builder, components); return builder.append(')').toString(); } } /** * Returns a {@code char} matcher functionally equivalent to this one, but which may be faster to * query than the original; your mileage may vary. Precomputation takes time and is likely to be * worthwhile only if the precomputed matcher is queried many thousands of times. * * <p>This method has no effect (returns {@code this}) when called in GWT: it's unclear whether a * precomputed matcher is faster, but it certainly consumes more memory, which doesn't seem like a * worthwhile tradeoff in a browser. */ public CharMatcher precomputed() { return Platform.precomputeCharMatcher(this); } /** * This is the actual implementation of {@link #precomputed}, but we bounce calls through a method * on {@link Platform} so that we can have different behavior in GWT. * * <p>The default precomputation is to cache the configuration of the original matcher in an * eight-kilobyte bit array. In some situations this produces a matcher which is faster to query * than the original. * * <p>The default implementation creates a new bit array and passes it to {@link * #setBits(LookupTable)}. */ CharMatcher precomputedInternal() { final LookupTable table = new LookupTable(); setBits(table); final CharMatcher outer = this; return new CharMatcher() { @Override public boolean matches(char c) { return table.get(c); } // TODO(kevinb): make methods like negate() smart? @Override public CharMatcher precomputed() { return this; } @Override public String toString() { return outer.toString(); } }; } CharMatcher withToString(final String toString) { final CharMatcher delegate = this; return new CharMatcher() { @Override public boolean matches(char c) { return delegate.matches(c); } @Override void setBits(LookupTable table) { delegate.setBits(table); } @Override public String toString() { return toString; } }; } /** * For use by implementors; sets the bit corresponding to each character ('\0' to '{@literal * \}uFFFF') that matches this matcher in the given bit array, leaving all other bits untouched. * * <p>The default implementation loops over every possible character value, invoking {@link * #matches} for each one. */ void setBits(LookupTable table) { char c = Character.MIN_VALUE; while (true) { if (matches(c)) { table.set(c); } if (c++ == Character.MAX_VALUE) { break; } } } /** * A bit array with one bit per {@code char} value, used by {@link CharMatcher#precomputed}. * * <p>TODO(kevinb): possibly share a common BitArray class with BloomFilter and others... a * simpler java.util.BitSet. */ private static final class LookupTable { int[] data = new int[2048]; void set(char index) { data[index >> 5] |= (1 << index); } boolean get(char index) { return (data[index >> 5] & (1 << index)) != 0; } } // Text processing routines /** * Returns {@code true} if a character sequence contains at least one matching character. * Equivalent to {@code !matchesNoneOf(sequence)}. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code true} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches at least one character in the sequence * @since 8.0 */ public boolean matchesAnyOf(CharSequence sequence) { return !matchesNoneOf(sequence); } /** * Returns {@code true} if a character sequence contains only matching characters. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code false} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches every character in the sequence, including when * the sequence is empty */ public boolean matchesAllOf(CharSequence sequence) { for (int i = sequence.length() - 1; i >= 0; i--) { if (!matches(sequence.charAt(i))) { return false; } } return true; } /** * Returns {@code true} if a character sequence contains no matching characters. Equivalent to * {@code !matchesAnyOf(sequence)}. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code false} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches every character in the sequence, including when * the sequence is empty */ public boolean matchesNoneOf(CharSequence sequence) { return indexIn(sequence) == -1; } // TODO(kevinb): add matchesAnyOf() /** * Returns the index of the first matching character in a character sequence, or {@code -1} if no * matching character is present. * * <p>The default implementation iterates over the sequence in forward order calling {@link * #matches} for each character. * * @param sequence the character sequence to examine from the beginning * @return an index, or {@code -1} if no character matches */ public int indexIn(CharSequence sequence) { int length = sequence.length(); for (int i = 0; i < length; i++) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the index of the first matching character in a character sequence, starting from a * given position, or {@code -1} if no character matches after that position. * * <p>The default implementation iterates over the sequence in forward order, beginning at {@code * start}, calling {@link #matches} for each character. * * @param sequence the character sequence to examine * @param start the first index to examine; must be nonnegative and no greater than {@code * sequence.length()} * @return the index of the first matching character, guaranteed to be no less than {@code start}, * or {@code -1} if no character matches * @throws IndexOutOfBoundsException if start is negative or greater than {@code * sequence.length()} */ public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); Preconditions.checkPositionIndex(start, length); for (int i = start; i < length; i++) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the index of the last matching character in a character sequence, or {@code -1} if no * matching character is present. * * <p>The default implementation iterates over the sequence in reverse order calling {@link * #matches} for each character. * * @param sequence the character sequence to examine from the end * @return an index, or {@code -1} if no character matches */ public int lastIndexIn(CharSequence sequence) { for (int i = sequence.length() - 1; i >= 0; i--) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the number of matching characters found in a character sequence. */ public int countIn(CharSequence sequence) { int count = 0; for (int i = 0; i < sequence.length(); i++) { if (matches(sequence.charAt(i))) { count++; } } return count; } /** * Returns a string containing all non-matching characters of a character sequence, in order. For * example: <pre> {@code * * CharMatcher.is('a').removeFrom("bazaar")}</pre> * * ... returns {@code "bzr"}. */ @CheckReturnValue public String removeFrom(CharSequence sequence) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); int spread = 1; // This unusual loop comes from extensive benchmarking OUT: while (true) { pos++; while (true) { if (pos == chars.length) { break OUT; } if (matches(chars[pos])) { break; } chars[pos - spread] = chars[pos]; pos++; } spread++; } return new String(chars, 0, pos - spread); } /** * Returns a string containing all matching characters of a character sequence, in order. For * example: <pre> {@code * * CharMatcher.is('a').retainFrom("bazaar")}</pre> * * ... returns {@code "aaa"}. */ @CheckReturnValue public String retainFrom(CharSequence sequence) { return negate().removeFrom(sequence); } /** * Returns a string copy of the input character sequence, with each character that matches this * matcher replaced by a given replacement character. For example: <pre> {@code * * CharMatcher.is('a').replaceFrom("radar", 'o')}</pre> * * ... returns {@code "rodor"}. * * <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching * character, then iterates the remainder of the sequence calling {@link #matches(char)} for each * character. * * @param sequence the character sequence to replace matching characters in * @param replacement the character to append to the result string in place of each matching * character in {@code sequence} * @return the new string */ @CheckReturnValue public String replaceFrom(CharSequence sequence, char replacement) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); chars[pos] = replacement; for (int i = pos + 1; i < chars.length; i++) { if (matches(chars[i])) { chars[i] = replacement; } } return new String(chars); } /** * Returns a string copy of the input character sequence, with each character that matches this * matcher replaced by a given replacement sequence. For example: <pre> {@code * * CharMatcher.is('a').replaceFrom("yaha", "oo")}</pre> * * ... returns {@code "yoohoo"}. * * <p><b>Note:</b> If the replacement is a fixed string with only one character, you are better * off calling {@link #replaceFrom(CharSequence, char)} directly. * * @param sequence the character sequence to replace matching characters in * @param replacement the characters to append to the result string in place of each matching * character in {@code sequence} * @return the new string */ @CheckReturnValue public String replaceFrom(CharSequence sequence, CharSequence replacement) { int replacementLen = replacement.length(); if (replacementLen == 0) { return removeFrom(sequence); } if (replacementLen == 1) { return replaceFrom(sequence, replacement.charAt(0)); } String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } int len = string.length(); StringBuilder buf = new StringBuilder((len * 3 / 2) + 16); int oldpos = 0; do { buf.append(string, oldpos, pos); buf.append(replacement); oldpos = pos + 1; pos = indexIn(string, oldpos); } while (pos != -1); buf.append(string, oldpos, len); return buf.toString(); } /** * Returns a substring of the input character sequence that omits all characters this matcher * matches from the beginning and from the end of the string. For example: <pre> {@code * * CharMatcher.anyOf("ab").trimFrom("abacatbab")}</pre> * * ... returns {@code "cat"}. * * <p>Note that: <pre> {@code * * CharMatcher.inRange('\0', ' ').trimFrom(str)}</pre> * * ... is equivalent to {@link String#trim()}. */ @CheckReturnValue public String trimFrom(CharSequence sequence) { int len = sequence.length(); int first; int last; for (first = 0; first < len; first++) { if (!matches(sequence.charAt(first))) { break; } } for (last = len - 1; last > first; last--) { if (!matches(sequence.charAt(last))) { break; } } return sequence.subSequence(first, last + 1).toString(); } /** * Returns a substring of the input character sequence that omits all characters this matcher * matches from the beginning of the string. For example: <pre> {@code * * CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")}</pre> * * ... returns {@code "catbab"}. */ @CheckReturnValue public String trimLeadingFrom(CharSequence sequence) { int len = sequence.length(); int first; for (first = 0; first < len; first++) { if (!matches(sequence.charAt(first))) { break; } } return sequence.subSequence(first, len).toString(); } /** * Returns a substring of the input character sequence that omits all characters this matcher * matches from the end of the string. For example: <pre> {@code * * CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")}</pre> * * ... returns {@code "abacat"}. */ @CheckReturnValue public String trimTrailingFrom(CharSequence sequence) { int len = sequence.length(); int last; for (last = len - 1; last >= 0; last--) { if (!matches(sequence.charAt(last))) { break; } } return sequence.subSequence(0, last + 1).toString(); } /** * Returns a string copy of the input character sequence, with each group of consecutive * characters that match this matcher replaced by a single replacement character. For example: * <pre> {@code * * CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')}</pre> * * ... returns {@code "b-p-r"}. * * <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching * character, then iterates the remainder of the sequence calling {@link #matches(char)} for each * character. * * @param sequence the character sequence to replace matching groups of characters in * @param replacement the character to append to the result string in place of each group of * matching characters in {@code sequence} * @return the new string */ @CheckReturnValue public String collapseFrom(CharSequence sequence, char replacement) { int first = indexIn(sequence); if (first == -1) { return sequence.toString(); } // TODO(kevinb): see if this implementation can be made faster StringBuilder builder = new StringBuilder(sequence.length()) .append(sequence.subSequence(0, first)) .append(replacement); boolean in = true; for (int i = first + 1; i < sequence.length(); i++) { char c = sequence.charAt(i); if (apply(c)) { if (!in) { builder.append(replacement); in = true; } } else { builder.append(c); in = false; } } return builder.toString(); } /** * Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that * groups of matching characters at the start or end of the sequence are removed without * replacement. */ @CheckReturnValue public String trimAndCollapseFrom(CharSequence sequence, char replacement) { int first = negate().indexIn(sequence); if (first == -1) { return ""; // everything matches. nothing's left. } StringBuilder builder = new StringBuilder(sequence.length()); boolean inMatchingGroup = false; for (int i = first; i < sequence.length(); i++) { char c = sequence.charAt(i); if (apply(c)) { inMatchingGroup = true; } else { if (inMatchingGroup) { builder.append(replacement); inMatchingGroup = false; } builder.append(c); } } return builder.toString(); } // Predicate interface /** * Returns {@code true} if this matcher matches the given character. * * @throws NullPointerException if {@code character} is null */ @Override public boolean apply(Character character) { return matches(character); } /** * Returns a string representation of this {@code CharMatcher}, such as * {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}. */ @Override public String toString() { return super.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.base; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * Simple static methods to be called at the start of your own methods to verify * correct arguments and state. This allows constructs such as * <pre> * if (count <= 0) { * throw new IllegalArgumentException("must be positive: " + count); * }</pre> * * to be replaced with the more compact * <pre> * checkArgument(count > 0, "must be positive: %s", count);</pre> * * Note that the sense of the expression is inverted; with {@code Preconditions} * you declare what you expect to be <i>true</i>, just as you do with an * <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html"> * {@code assert}</a> or a JUnit {@code assertTrue} call. * * <p><b>Warning:</b> only the {@code "%s"} specifier is recognized as a * placeholder in these messages, not the full range of {@link * String#format(String, Object[])} specifiers. * * <p>Take care not to confuse precondition checking with other similar types * of checks! Precondition exceptions -- including those provided here, but also * {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link * UnsupportedOperationException} and others -- are used to signal that the * <i>calling method</i> has made an error. This tells the caller that it should * not have invoked the method when it did, with the arguments it did, or * perhaps ever. Postcondition or other invariant failures should not throw * these types of exceptions. * * <p>See the Guava User Guide on <a href= * "http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained"> * using {@code Preconditions}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Preconditions { private Preconditions() {} /** * Ensures the truth of an expression involving one or more parameters to the * calling method. * * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } } /** * Ensures the truth of an expression involving one or more parameters to the * calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will * be converted to a string using {@link String#valueOf(Object)} * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument( boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving one or more parameters to the * calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the * check fail. The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. * @throws IllegalArgumentException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code * errorMessageTemplate} or {@code errorMessageArgs} is null (don't let * this happen) */ public static void checkArgument(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException( format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will * be converted to a string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState( boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the * check fail. The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. * @throws IllegalStateException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code * errorMessageTemplate} or {@code errorMessageArgs} is null (don't let * this happen) */ public static void checkState(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException( format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures that an object reference passed as a parameter to the calling * method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling * method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will * be converted to a string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling * method is not null. * * @param reference an object reference * @param errorMessageTemplate a template for the exception message should the * check fail. The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException( format(errorMessageTemplate, errorMessageArgs)); } return reference; } /* * All recent hotspots (as of 2009) *really* like to have the natural code * * if (guardExpression) { * throw new BadException(messageExpression); * } * * refactored so that messageExpression is moved to a separate * String-returning method. * * if (guardExpression) { * throw new BadException(badMsg(...)); * } * * The alternative natural refactorings into void or Exception-returning * methods are much slower. This is a big deal - we're talking factors of * 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer * bug, which should be fixed, but that's a separate, big project). * * The coding pattern above is heavily used in java.util, e.g. in ArrayList. * There is a RangeCheckMicroBenchmark in the JDK that was used to test this. * * But the methods in this class want to throw different exceptions, * depending on the args, so it appears that this pattern is not directly * applicable. But we can use the ridiculous, devious trick of throwing an * exception in the middle of the construction of another exception. * Hotspot is fine with that. */ /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, * list or string of size {@code size}. An element index may range from zero, * inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list * or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not * less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size) { return checkElementIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, * list or string of size {@code size}. An element index may range from zero, * inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list * or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not * less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex( int index, int size, @Nullable String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); } return index; } private static String badElementIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index >= size return format("%s (%s) must be less than size (%s)", desc, index, size); } } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, * list or string of size {@code size}. A position index may range from zero * to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list * or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is * greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, * list or string of size {@code size}. A position index may range from zero * to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list * or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is * greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex( int index, int size, @Nullable String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); } return index; } private static String badPositionIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index > size return format("%s (%s) must not be greater than size (%s)", desc, index, size); } } /** * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> * in an array, list or string of size {@code size}, and are in order. A * position index may range from zero to {@code size}, inclusive. * * @param start a user-supplied index identifying a starting position in an * array, list or string * @param end a user-supplied index identifying a ending position in an array, * list or string * @param size the size of that array, list or string * @throws IndexOutOfBoundsException if either index is negative or is * greater than {@code size}, or if {@code end} is less than {@code start} * @throws IllegalArgumentException if {@code size} is negative */ public static void checkPositionIndexes(int start, int end, int size) { // Carefully optimized for execution by hotspot (explanatory comment above) if (start < 0 || end < start || end > size) { throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); } } private static String badPositionIndexes(int start, int end, int size) { if (start < 0 || start > size) { return badPositionIndex(start, size, "start index"); } if (end < 0 || end > size) { return badPositionIndex(end, size, "end index"); } // end < start return format("end index (%s) must not be less than start index (%s)", end, start); } /** * Substitutes each {@code %s} in {@code template} with an argument. These * are matched by position - the first {@code %s} gets {@code args[0]}, etc. * If there are more arguments than placeholders, the unmatched arguments will * be appended to the end of the formatted message in square braces. * * @param template a non-null string containing 0 or more {@code %s} * placeholders. * @param args the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. */ @VisibleForTesting static String format(String template, @Nullable Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder( template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; /** * Contains static factory methods for creating {@code Equivalence} instances. * * <p>All methods return serializable instances. * * @author Bob Lee * @author Kurt Alfred Kluever * @author Gregory Kick * @since 4.0 */ @Beta @GwtCompatible public final class Equivalences { private Equivalences() {} /** * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns * {@code 0} if passed a null value. * * @since 8.0 (present null-friendly behavior) * @since 4.0 (otherwise) */ public static Equivalence<Object> equals() { return Equals.INSTANCE; } /** * Returns an equivalence that uses {@code ==} to compare values and {@link * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} * returns {@code true} if {@code a == b}, including in the case that a and b are both null. */ public static Equivalence<Object> identity() { return Identity.INSTANCE; } private static final class Equals extends Equivalence<Object> implements Serializable { static final Equals INSTANCE = new Equals(); @Override protected boolean doEquivalent(Object a, Object b) { return a.equals(b); } @Override public int doHash(Object o) { return o.hashCode(); } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } private static final class Identity extends Equivalence<Object> implements Serializable { static final Identity INSTANCE = new Identity(); @Override protected boolean doEquivalent(Object a, Object b) { return false; } @Override protected int doHash(Object o) { return System.identityHashCode(o); } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.annotation.Nullable; /** * Helper functions that can operate on any {@code Object}. * * <p>See the Guava User Guide on <a * href="http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained">writing * {@code Object} methods with {@code Objects}</a>. * * @author Laurence Gonsalves * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Objects { private Objects() {} /** * Determines whether two possibly-null objects are equal. Returns: * * <ul> * <li>{@code true} if {@code a} and {@code b} are both null. * <li>{@code true} if {@code a} and {@code b} are both non-null and they are * equal according to {@link Object#equals(Object)}. * <li>{@code false} in all other situations. * </ul> * * <p>This assumes that any non-null objects passed to this function conform * to the {@code equals()} contract. */ public static boolean equal(@Nullable Object a, @Nullable Object b) { return a == b || (a != null && a.equals(b)); } /** * Generates a hash code for multiple values. The hash code is generated by * calling {@link Arrays#hashCode(Object[])}. * * <p>This is useful for implementing {@link Object#hashCode()}. For example, * in an object that has three properties, {@code x}, {@code y}, and * {@code z}, one could write: * <pre> * public int hashCode() { * return Objects.hashCode(getX(), getY(), getZ()); * }</pre> * * <b>Warning</b>: When a single object is supplied, the returned hash code * does not equal the hash code of that object. */ public static int hashCode(@Nullable Object... objects) { return Arrays.hashCode(objects); } /** * Creates an instance of {@link ToStringHelper}. * * <p>This is helpful for implementing {@link Object#toString()}. * Specification by example: <pre> {@code * // Returns "ClassName{}" * Objects.toStringHelper(this) * .toString(); * * // Returns "ClassName{x=1}" * Objects.toStringHelper(this) * .add("x", 1) * .toString(); * * // Returns "MyObject{x=1}" * Objects.toStringHelper("MyObject") * .add("x", 1) * .toString(); * * // Returns "ClassName{x=1, y=foo}" * Objects.toStringHelper(this) * .add("x", 1) * .add("y", "foo") * .toString(); * }} * * // Returns "ClassName{x=1}" * Objects.toStringHelper(this) * .omitNullValues() * .add("x", 1) * .add("y", null) * .toString(); * }}</pre> * * <p>Note that in GWT, class names are often obfuscated. * * @param self the object to generate the string for (typically {@code this}), * used only for its class name * @since 2.0 */ public static ToStringHelper toStringHelper(Object self) { return new ToStringHelper(simpleName(self.getClass())); } /** * Creates an instance of {@link ToStringHelper} in the same manner as * {@link Objects#toStringHelper(Object)}, but using the name of {@code clazz} * instead of using an instance's {@link Object#getClass()}. * * <p>Note that in GWT, class names are often obfuscated. * * @param clazz the {@link Class} of the instance * @since 7.0 (source-compatible since 2.0) */ public static ToStringHelper toStringHelper(Class<?> clazz) { return new ToStringHelper(simpleName(clazz)); } /** * Creates an instance of {@link ToStringHelper} in the same manner as * {@link Objects#toStringHelper(Object)}, but using {@code className} instead * of using an instance's {@link Object#getClass()}. * * @param className the name of the instance type * @since 7.0 (source-compatible since 2.0) */ public static ToStringHelper toStringHelper(String className) { return new ToStringHelper(className); } /** * {@link Class#getSimpleName()} is not GWT compatible yet, so we * provide our own implementation. */ private static String simpleName(Class<?> clazz) { String name = clazz.getName(); // the nth anonymous class has a class name ending in "Outer$n" // and local inner classes have names ending in "Outer.$1Inner" name = name.replaceAll("\\$[0-9]+", "\\$"); // we want the name of the inner class all by its lonesome int start = name.lastIndexOf('$'); // if this isn't an inner class, just find the start of the // top level class name. if (start == -1) { start = name.lastIndexOf('.'); } return name.substring(start + 1); } /** * Returns the first of two given parameters that is not {@code null}, if * either is, or otherwise throws a {@link NullPointerException}. * * <p><b>Note:</b> if {@code first} is represented as an {@code Optional<T>}, * this can be accomplished with {@code first.or(second)}. That approach also * allows for lazy evaluation of the fallback instance, using * {@code first.or(Supplier)}. * * @return {@code first} if {@code first} is not {@code null}, or * {@code second} if {@code first} is {@code null} and {@code second} is * not {@code null} * @throws NullPointerException if both {@code first} and {@code second} were * {@code null} * @since 3.0 */ public static <T> T firstNonNull(@Nullable T first, @Nullable T second) { return first != null ? first : checkNotNull(second); } /** * Support class for {@link Objects#toStringHelper}. * * @author Jason Lee * @since 2.0 */ public static final class ToStringHelper { private final String className; private final List<ValueHolder> valueHolders = new LinkedList<ValueHolder>(); private boolean omitNullValues = false; /** * Use {@link Objects#toStringHelper(Object)} to create an instance. */ private ToStringHelper(String className) { this.className = checkNotNull(className); } /** * When called, the formatted output returned by {@link #toString()} will * ignore {@code null} values. * * @since 12.0 */ public ToStringHelper omitNullValues() { omitNullValues = true; return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. If {@code value} is {@code null}, the string {@code "null"} * is used, unless {@link #omitNullValues()} is called, in which case this * name/value pair will not be added. */ public ToStringHelper add(String name, @Nullable Object value) { checkNotNull(name); addHolder(value).builder.append(name).append('=').append(value); return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, boolean value) { checkNameAndAppend(name).append(value); return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, char value) { checkNameAndAppend(name).append(value); return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, double value) { checkNameAndAppend(name).append(value); return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, float value) { checkNameAndAppend(name).append(value); return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, int value) { checkNameAndAppend(name).append(value); return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, long value) { checkNameAndAppend(name).append(value); return this; } private StringBuilder checkNameAndAppend(String name) { checkNotNull(name); return addHolder().builder.append(name).append('='); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, Object)} instead * and give value a readable name. */ public ToStringHelper addValue(@Nullable Object value) { addHolder(value).builder.append(value); return this; } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, boolean)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(boolean value) { addHolder().builder.append(value); return this; } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, char)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(char value) { addHolder().builder.append(value); return this; } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, double)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(double value) { addHolder().builder.append(value); return this; } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, float)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(float value) { addHolder().builder.append(value); return this; } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, int)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(int value) { addHolder().builder.append(value); return this; } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, long)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(long value) { addHolder().builder.append(value); return this; } /** * Returns a string in the format specified by {@link * Objects#toStringHelper(Object)}. */ @Override public String toString() { // create a copy to keep it consistent in case value changes boolean omitNullValuesSnapshot = omitNullValues; boolean needsSeparator = false; StringBuilder builder = new StringBuilder(32).append(className) .append('{'); for (ValueHolder valueHolder : valueHolders) { if (!omitNullValuesSnapshot || !valueHolder.isNull) { if (needsSeparator) { builder.append(", "); } else { needsSeparator = true; } // must explicitly cast it, otherwise GWT tests might fail because // it tries to access StringBuilder.append(StringBuilder), which is // a private method // TODO(user): change once 5904010 is fixed CharSequence sequence = valueHolder.builder; builder.append(sequence); } } return builder.append('}').toString(); } private ValueHolder addHolder() { ValueHolder valueHolder = new ValueHolder(); valueHolders.add(valueHolder); return valueHolder; } private ValueHolder addHolder(@Nullable Object value) { ValueHolder valueHolder = addHolder(); valueHolder.isNull = (value == null); return valueHolder; } private static final class ValueHolder { final StringBuilder builder = new StringBuilder(); boolean isNull; } } }
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.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>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 */ public final class Charsets { private Charsets() {} /** * US-ASCII: seven-bit ASCII, the Basic Latin block of the Unicode character set (ISO646-US). */ public static final Charset US_ASCII = Charset.forName("US-ASCII"); /** * ISO-8859-1: ISO Latin Alphabet Number 1 (ISO-LATIN-1). */ 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. */ public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); /** * UTF-16LE: sixteen-bit UCS Transformation Format, little-endian byte order. */ 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. */ 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) 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 java.io.Serializable; import javax.annotation.Nullable; /** * Equivalence applied on functional result. * * @author Bob Lee * @since 10.0 */ @Beta @GwtCompatible final class FunctionalEquivalence<F, T> extends Equivalence<F> implements Serializable { private static final long serialVersionUID = 0; private final Function<F, ? extends T> function; private final Equivalence<T> resultEquivalence; FunctionalEquivalence( Function<F, ? extends T> function, Equivalence<T> resultEquivalence) { this.function = checkNotNull(function); this.resultEquivalence = checkNotNull(resultEquivalence); } @Override protected boolean doEquivalent(F a, F b) { return resultEquivalence.equivalent(function.apply(a), function.apply(b)); } @Override protected int doHash(F a) { return resultEquivalence.hash(function.apply(a)); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof FunctionalEquivalence) { FunctionalEquivalence<?, ?> that = (FunctionalEquivalence<?, ?>) obj; return function.equals(that.function) && resultEquivalence.equals(that.resultEquivalence); } return false; } @Override public int hashCode() { return Objects.hashCode(function, resultEquivalence); } @Override public String toString() { return resultEquivalence + ".onResultOf(" + function + ")"; } }
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.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.IOException; import java.util.AbstractList; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a * {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns * them as a {@link String}. Example: <pre> {@code * * Joiner joiner = Joiner.on("; ").skipNulls(); * . . . * return joiner.join("Harry", null, "Ron", "Hermione");}</pre> * * This returns the string {@code "Harry; Ron; Hermione"}. Note that all input elements are * converted to strings using {@link Object#toString()} before being appended. * * <p>If neither {@link #skipNulls()} nor {@link #useForNull(String)} is specified, the joining * methods will throw {@link NullPointerException} if any given element is null. * * <p><b>Warning: joiner instances are always immutable</b>; a configuration method such as {@code * useForNull} has no effect on the instance it is invoked on! You must store and use the new joiner * instance returned by the method. This makes joiners thread-safe, and safe to store as {@code * static final} constants. <pre> {@code * * // Bad! Do not do this! * Joiner joiner = Joiner.on(','); * joiner.skipNulls(); // does nothing! * return joiner.join("wrong", null, "wrong");}</pre> * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Joiner">{@code Joiner}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public class Joiner { /** * Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(String separator) { return new Joiner(separator); } /** * Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(char separator) { return new Joiner(String.valueOf(separator)); } private final String separator; private Joiner(String separator) { this.separator = checkNotNull(separator); } private Joiner(Joiner prototype) { this.separator = prototype.separator; } /** * <b>Deprecated.</b> * * @since 11.0 * @deprecated use {@link #appendTo(Appendable, Iterator)} by casting {@code parts} to * {@code Iterator<?>}, or better yet, by implementing only {@code Iterator} and not * {@code Iterable}. <b>This method is scheduled for deletion in June 2013.</b> */ @Beta @Deprecated public final <A extends Appendable, I extends Object & Iterable<?> & Iterator<?>> A appendTo(A appendable, I parts) throws IOException { return appendTo(appendable, (Iterator<?>) parts); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. */ public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { return appendTo(appendable, parts.iterator()); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. * * @since 11.0 */ @Beta public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { checkNotNull(appendable); if (parts.hasNext()) { appendable.append(toString(parts.next())); while (parts.hasNext()) { appendable.append(separator); appendable.append(toString(parts.next())); } } return appendable; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. */ public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException { return appendTo(appendable, Arrays.asList(parts)); } /** * Appends to {@code appendable} the string representation of each of the remaining arguments. */ public final <A extends Appendable> A appendTo( A appendable, @Nullable Object first, @Nullable Object second, Object... rest) throws IOException { return appendTo(appendable, iterable(first, second, rest)); } /** * <b>Deprecated.</b> * * @since 11.0 * @deprecated use {@link #appendTo(StringBuilder, Iterator)} by casting {@code parts} to * {@code Iterator<?>}, or better yet, by implementing only {@code Iterator} and not * {@code Iterable}. <b>This method is scheduled for deletion in June 2013.</b> */ @Beta @Deprecated public final <I extends Object & Iterable<?> & Iterator<?>> StringBuilder appendTo(StringBuilder builder, I parts) { return appendTo(builder, (Iterator<?>) parts); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. */ public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) { return appendTo(builder, parts.iterator()); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ @Beta public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) { try { appendTo((Appendable) builder, parts); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. */ public final StringBuilder appendTo(StringBuilder builder, Object[] parts) { return appendTo(builder, Arrays.asList(parts)); } /** * Appends to {@code builder} the string representation of each of the remaining arguments. * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not * throw {@link IOException}. */ public final StringBuilder appendTo( StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) { return appendTo(builder, iterable(first, second, rest)); } /** * <b>Deprecated.</b> * * @since 11.0 * @deprecated use {@link #join(Iterator)} by casting {@code parts} to * {@code Iterator<?>}, or better yet, by implementing only {@code Iterator} and not * {@code Iterable}. <b>This method is scheduled for deletion in June 2013.</b> */ @Beta @Deprecated public final <I extends Object & Iterable<?> & Iterator<?>> String join(I parts) { return join((Iterator<?>) parts); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public final String join(Iterable<?> parts) { return join(parts.iterator()); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. * * @since 11.0 */ @Beta public final String join(Iterator<?> parts) { return appendTo(new StringBuilder(), parts).toString(); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public final String join(Object[] parts) { return join(Arrays.asList(parts)); } /** * Returns a string containing the string representation of each argument, using the previously * configured separator between each. */ public final String join(@Nullable Object first, @Nullable Object second, Object... rest) { return join(iterable(first, second, rest)); } /** * Returns a joiner with the same behavior as this one, except automatically substituting {@code * nullText} for any provided null elements. */ @CheckReturnValue public Joiner useForNull(final String nullText) { checkNotNull(nullText); return new Joiner(this) { @Override CharSequence toString(Object part) { return (part == null) ? nullText : Joiner.this.toString(part); } @Override public Joiner useForNull(String nullText) { checkNotNull(nullText); // weird: just to satisfy NullPointerTester. throw new UnsupportedOperationException("already specified useForNull"); } @Override public Joiner skipNulls() { throw new UnsupportedOperationException("already specified useForNull"); } }; } /** * Returns a joiner with the same behavior as this joiner, except automatically skipping over any * provided null elements. */ @CheckReturnValue public Joiner skipNulls() { return new Joiner(this) { @Override public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { checkNotNull(appendable, "appendable"); checkNotNull(parts, "parts"); while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(Joiner.this.toString(part)); break; } } while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(separator); appendable.append(Joiner.this.toString(part)); } } return appendable; } @Override public Joiner useForNull(String nullText) { checkNotNull(nullText); // weird: just to satisfy NullPointerTester. throw new UnsupportedOperationException("already specified skipNulls"); } @Override public MapJoiner withKeyValueSeparator(String kvs) { checkNotNull(kvs); // weird: just to satisfy NullPointerTester. throw new UnsupportedOperationException("can't use .skipNulls() with maps"); } }; } /** * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as * this {@code Joiner} otherwise. */ @CheckReturnValue public MapJoiner withKeyValueSeparator(String keyValueSeparator) { return new MapJoiner(this, keyValueSeparator); } /** * An object that joins map entries in the same manner as {@code Joiner} joins iterables and * arrays. Like {@code Joiner}, it is thread-safe and immutable. * * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code * Multimap} entries in two distinct modes: * * <ul> * <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a * {@code MapJoiner} method that accepts entries as input, and receive output of the form * {@code key1=A&key1=B&key2=C}. * <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code MapJoiner} * method that accepts a map as input, and receive output of the form {@code * key1=[A, B]&key2=C}. * </ul> * * @since 2.0 (imported from Google Collections Library) */ public final static class MapJoiner { private final Joiner joiner; private final String keyValueSeparator; private MapJoiner(Joiner joiner, String keyValueSeparator) { this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull this.keyValueSeparator = checkNotNull(keyValueSeparator); } /** * Appends the string representation of each entry of {@code map}, using the previously * configured separator and key-value separator, to {@code appendable}. */ public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException { return appendTo(appendable, map.entrySet()); } /** * Appends the string representation of each entry of {@code map}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}. */ public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) { return appendTo(builder, map.entrySet()); } /** * Returns a string containing the string representation of each entry of {@code map}, using the * previously configured separator and key-value separator. */ public String join(Map<?, ?> map) { return join(map.entrySet()); } /** * <b>Deprecated.</b> * * @since 11.0 * @deprecated use {@link #appendTo(Appendable, Iterator)} by casting {@code entries} to * {@code Iterator<? extends Entry<?, ?>>}, or better yet, by implementing only * {@code Iterator} and not {@code Iterable}. <b>This method is scheduled for deletion * in June 2013.</b> */ @Beta @Deprecated public <A extends Appendable, I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> A appendTo(A appendable, I entries) throws IOException { Iterator<? extends Entry<?, ?>> iterator = entries; return appendTo(appendable, iterator); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code appendable}. * * @since 10.0 */ @Beta public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries) throws IOException { return appendTo(appendable, entries.iterator()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code appendable}. * * @since 11.0 */ @Beta public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts) throws IOException { checkNotNull(appendable); if (parts.hasNext()) { Entry<?, ?> entry = parts.next(); appendable.append(joiner.toString(entry.getKey())); appendable.append(keyValueSeparator); appendable.append(joiner.toString(entry.getValue())); while (parts.hasNext()) { appendable.append(joiner.separator); Entry<?, ?> e = parts.next(); appendable.append(joiner.toString(e.getKey())); appendable.append(keyValueSeparator); appendable.append(joiner.toString(e.getValue())); } } return appendable; } /** * <b>Deprecated.</b> * * @since 11.0 * @deprecated use {@link #appendTo(StringBuilder, Iterator)} by casting {@code entries} to * {@code Iterator<? extends Entry<?, ?>>}, or better yet, by implementing only * {@code Iterator} and not {@code Iterable}. <b>This method is scheduled for deletion * in June 2013.</b> */ @Beta @Deprecated public <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> StringBuilder appendTo(StringBuilder builder, I entries) throws IOException { Iterator<? extends Entry<?, ?>> iterator = entries; return appendTo(builder, iterator); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 10.0 */ @Beta public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) { return appendTo(builder, entries.iterator()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ @Beta public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) { try { appendTo((Appendable) builder, entries); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * <b>Deprecated.</b> * * @since 11.0 * @deprecated use {@link #join(Iterator)} by casting {@code entries} to * {@code Iterator<? extends Entry<?, ?>>}, or better yet, by implementing only * {@code Iterator} and not {@code Iterable}. <b>This method is scheduled for deletion * in June 2013.</b> */ @Beta @Deprecated public <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> String join(I entries) throws IOException { Iterator<? extends Entry<?, ?>> iterator = entries; return join(iterator); } /** * Returns a string containing the string representation of each entry in {@code entries}, using * the previously configured separator and key-value separator. * * @since 10.0 */ @Beta public String join(Iterable<? extends Entry<?, ?>> entries) { return join(entries.iterator()); } /** * Returns a string containing the string representation of each entry in {@code entries}, using * the previously configured separator and key-value separator. * * @since 11.0 */ @Beta public String join(Iterator<? extends Entry<?, ?>> entries) { return appendTo(new StringBuilder(), entries).toString(); } /** * Returns a map joiner with the same behavior as this one, except automatically substituting * {@code nullText} for any provided null keys or values. */ @CheckReturnValue public MapJoiner useForNull(String nullText) { return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator); } } CharSequence toString(Object part) { checkNotNull(part); // checkNotNull for GWT (do not optimize). return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); } private static Iterable<Object> iterable( final Object first, final Object second, final Object[] rest) { checkNotNull(rest); return new AbstractList<Object>() { @Override public int size() { return rest.length + 2; } @Override public Object get(int index) { switch (index) { case 0: return first; case 1: return second; default: return rest[index - 2]; } } }; } }
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 com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; @GwtCompatible(serializable = true) final class PairwiseEquivalence<T> extends Equivalence<Iterable<T>> implements Serializable { final Equivalence<? super T> elementEquivalence; PairwiseEquivalence(Equivalence<? super T> elementEquivalence) { this.elementEquivalence = Preconditions.checkNotNull(elementEquivalence); } @Override protected boolean doEquivalent(Iterable<T> iterableA, Iterable<T> iterableB) { Iterator<T> iteratorA = iterableA.iterator(); Iterator<T> iteratorB = iterableB.iterator(); while (iteratorA.hasNext() && iteratorB.hasNext()) { if (!elementEquivalence.equivalent(iteratorA.next(), iteratorB.next())) { return false; } } return !iteratorA.hasNext() && !iteratorB.hasNext(); } @Override protected int doHash(Iterable<T> iterable) { int hash = 78721; for (T element : iterable) { hash = hash * 24943 + elementEquivalence.hash(element); } return hash; } @Override public boolean equals(@Nullable Object object) { if (object instanceof PairwiseEquivalence) { PairwiseEquivalence<?> that = (PairwiseEquivalence<?>) object; return this.elementEquivalence.equals(that.elementEquivalence); } return false; } @Override public int hashCode() { return elementEquivalence.hashCode() ^ 0x46a3eb07; } @Override public String toString() { return elementEquivalence + ".pairwise()"; } private static final long serialVersionUID = 1; }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.NoSuchElementException; /** * Note this class is a copy of * {@link com.google.common.collect.AbstractIterator} (for dependency reasons). */ @GwtCompatible abstract class AbstractIterator<T> implements Iterator<T> { private State state = State.NOT_READY; protected AbstractIterator() {} private enum State { READY, NOT_READY, DONE, FAILED, } private T next; protected abstract T computeNext(); 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; } @Override public final void remove() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * Useful suppliers. * * <p>All methods return serializable suppliers as long as they're given * serializable parameters. * * @author Laurence Gonsalves * @author Harry Heymann * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Suppliers { private Suppliers() {} /** * Returns a new supplier which is the composition of the provided function * and supplier. In other words, the new supplier's value will be computed by * retrieving the value from {@code supplier}, and then applying * {@code function} to that value. Note that the resulting supplier will not * call {@code supplier} or invoke {@code function} until it is called. */ public static <F, T> Supplier<T> compose( Function<? super F, T> function, Supplier<F> supplier) { Preconditions.checkNotNull(function); Preconditions.checkNotNull(supplier); return new SupplierComposition<F, T>(function, supplier); } private static class SupplierComposition<F, T> implements Supplier<T>, Serializable { final Function<? super F, T> function; final Supplier<F> supplier; SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) { this.function = function; this.supplier = supplier; } @Override public T get() { return function.apply(supplier.get()); } private static final long serialVersionUID = 0; } /** * Returns a supplier which caches the instance retrieved during the first * call to {@code get()} and returns that value on subsequent calls to * {@code get()}. See: * <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form * does not contain the cached value, which will be recalculated when {@code * get()} is called on the reserialized instance. * * <p>If {@code delegate} is an instance created by an earlier call to {@code * memoize}, it is returned directly. */ public static <T> Supplier<T> memoize(Supplier<T> delegate) { return (delegate instanceof MemoizingSupplier) ? delegate : new MemoizingSupplier<T>(Preconditions.checkNotNull(delegate)); } @VisibleForTesting static class MemoizingSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; transient volatile boolean initialized; // "value" does not need to be volatile; visibility piggy-backs // on volatile read of "initialized". transient T value; MemoizingSupplier(Supplier<T> delegate) { this.delegate = delegate; } @Override public T get() { // A 2-field variant of Double Checked Locking. if (!initialized) { synchronized (this) { if (!initialized) { T t = delegate.get(); value = t; initialized = true; return t; } } } return value; } private static final long serialVersionUID = 0; } /** * Returns a supplier that caches the instance supplied by the delegate and * removes the cached value after the specified time has passed. Subsequent * calls to {@code get()} return the cached value if the expiration time has * not passed. After the expiration time, a new value is retrieved, cached, * and returned. See: * <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form * does not contain the cached value, which will be recalculated when {@code * get()} is called on the reserialized instance. * * @param duration the length of time after a value is created that it * should stop being returned by subsequent {@code get()} calls * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is not positive * @since 2.0 */ public static <T> Supplier<T> memoizeWithExpiration( Supplier<T> delegate, long duration, TimeUnit unit) { return new ExpiringMemoizingSupplier<T>(delegate, duration, unit); } @VisibleForTesting static class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; final long durationNanos; transient volatile T value; // The special value 0 means "not yet initialized". transient volatile long expirationNanos; ExpiringMemoizingSupplier( Supplier<T> delegate, long duration, TimeUnit unit) { this.delegate = Preconditions.checkNotNull(delegate); this.durationNanos = unit.toNanos(duration); Preconditions.checkArgument(duration > 0); } @Override public T get() { // Another variant of Double Checked Locking. // // We use two volatile reads. We could reduce this to one by // putting our fields into a holder class, but (at least on x86) // the extra memory consumption and indirection are more // expensive than the extra volatile reads. long nanos = expirationNanos; long now = Platform.systemNanoTime(); if (nanos == 0 || now - nanos >= 0) { synchronized (this) { if (nanos == expirationNanos) { // recheck for lost race T t = delegate.get(); value = t; nanos = now + durationNanos; // In the very unlikely event that nanos is 0, set it to 1; // no one will notice 1 ns of tardiness. expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } return value; } private static final long serialVersionUID = 0; } /** * Returns a supplier that always supplies {@code instance}. */ public static <T> Supplier<T> ofInstance(@Nullable T instance) { return new SupplierOfInstance<T>(instance); } private static class SupplierOfInstance<T> implements Supplier<T>, Serializable { final T instance; SupplierOfInstance(@Nullable T instance) { this.instance = instance; } @Override public T get() { return instance; } private static final long serialVersionUID = 0; } /** * Returns a supplier whose {@code get()} method synchronizes on * {@code delegate} before calling it, making it thread-safe. */ public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) { return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate)); } private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; ThreadSafeSupplier(Supplier<T> delegate) { this.delegate = delegate; } @Override public T get() { synchronized (delegate) { return delegate.get(); } } private static final long serialVersionUID = 0; } /** * Returns a function that accepts a supplier and returns the result of * invoking {@link Supplier#get} on that supplier. * * @since 8.0 */ @Beta @SuppressWarnings("unchecked") // SupplierFunction works for any T. public static <T> Function<Supplier<T>, T> supplierFunction() { return (Function) SupplierFunction.INSTANCE; } private enum SupplierFunction implements Function<Supplier<?>, Object> { INSTANCE; @Override public Object apply(Supplier<?> input) { return input.get(); } } }
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 orNull() instead of 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 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) 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} not containing a reference. */ @GwtCompatible final class Absent extends Optional<Object> { static final Absent INSTANCE = new Absent(); @Override public boolean isPresent() { return false; } @Override public Object get() { throw new IllegalStateException("value is absent"); } @Override public Object or(Object defaultValue) { return checkNotNull(defaultValue, "use orNull() instead of or(null)"); } @SuppressWarnings("unchecked") // safe covariant cast @Override public Optional<Object> or(Optional<?> secondChoice) { return (Optional) checkNotNull(secondChoice); } @Override public Object or(Supplier<?> supplier) { return checkNotNull(supplier.get(), "use orNull() instead of a Supplier that returns null"); } @Override @Nullable public Object orNull() { return null; } @Override public Set<Object> asSet() { return Collections.emptySet(); } @Override public boolean equals(@Nullable Object object) { return object == this; } @Override public int hashCode() { return 0x598df91c; } @Override public String toString() { return "Optional.absent()"; } private Object readResolve() { return INSTANCE; } 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.base.internal; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** * Thread that finalizes referents. All references should implement * {@code com.google.common.base.FinalizableReference}. * * <p>While this class is public, we consider it to be *internal* and not part * of our published API. It is public so we can access it reflectively across * class loaders in secure environments. * * <p>This class can't depend on other Google Collections code. If we were * to load this class in the same class loader as the rest of * Google Collections, this thread would keep an indirect strong reference * to the class loader and prevent it from being garbage collected. This * poses a problem for environments where you want to throw away the class * loader. For example, dynamically reloading a web application or unloading * an OSGi bundle. * * <p>{@code com.google.common.base.FinalizableReferenceQueue} loads this class * in its own class loader. That way, this class doesn't prevent the main * class loader from getting garbage collected, and this class can detect when * the main class loader has been garbage collected and stop itself. */ public class Finalizer extends Thread { private static final Logger logger = Logger.getLogger(Finalizer.class.getName()); /** Name of FinalizableReference.class. */ private static final String FINALIZABLE_REFERENCE = "com.google.common.base.FinalizableReference"; /** * Starts the Finalizer thread. FinalizableReferenceQueue calls this method * reflectively. * * @param finalizableReferenceClass FinalizableReference.class * @param frq reference to instance of FinalizableReferenceQueue that started * this thread * @return ReferenceQueue which Finalizer will poll */ public static ReferenceQueue<Object> startFinalizer( Class<?> finalizableReferenceClass, Object frq) { /* * We use FinalizableReference.class for two things: * * 1) To invoke FinalizableReference.finalizeReferent() * * 2) To detect when FinalizableReference's class loader has to be garbage * collected, at which point, Finalizer can stop running */ if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) { throw new IllegalArgumentException( "Expected " + FINALIZABLE_REFERENCE + "."); } Finalizer finalizer = new Finalizer(finalizableReferenceClass, frq); finalizer.start(); return finalizer.queue; } private final WeakReference<Class<?>> finalizableReferenceClassReference; private final PhantomReference<Object> frqReference; private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>(); private static final Field inheritableThreadLocals = getInheritableThreadLocalsField(); /** Constructs a new finalizer thread. */ private Finalizer(Class<?> finalizableReferenceClass, Object frq) { super(Finalizer.class.getName()); this.finalizableReferenceClassReference = new WeakReference<Class<?>>(finalizableReferenceClass); // Keep track of the FRQ that started us so we know when to stop. this.frqReference = new PhantomReference<Object>(frq, queue); setDaemon(true); try { if (inheritableThreadLocals != null) { inheritableThreadLocals.set(this, null); } } catch (Throwable t) { logger.log(Level.INFO, "Failed to clear thread local values inherited" + " by reference finalizer thread.", t); } // TODO(fry): Priority? } /** * Loops continuously, pulling references off the queue and cleaning them up. */ @SuppressWarnings("InfiniteLoopStatement") @Override public void run() { try { while (true) { try { cleanUp(queue.remove()); } catch (InterruptedException e) { /* ignore */ } } } catch (ShutDown shutDown) { /* ignore */ } } /** * Cleans up a single reference. Catches and logs all throwables. */ private void cleanUp(Reference<?> reference) throws ShutDown { Method finalizeReferentMethod = getFinalizeReferentMethod(); do { /* * This is for the benefit of phantom references. Weak and soft * references will have already been cleared by this point. */ reference.clear(); if (reference == frqReference) { /* * The client no longer has a reference to the * FinalizableReferenceQueue. We can stop. */ throw new ShutDown(); } try { finalizeReferentMethod.invoke(reference); } catch (Throwable t) { logger.log(Level.SEVERE, "Error cleaning up after reference.", t); } /* * Loop as long as we have references available so as not to waste * CPU looking up the Method over and over again. */ } while ((reference = queue.poll()) != null); } /** * Looks up FinalizableReference.finalizeReferent() method. */ private Method getFinalizeReferentMethod() throws ShutDown { Class<?> finalizableReferenceClass = finalizableReferenceClassReference.get(); if (finalizableReferenceClass == null) { /* * FinalizableReference's class loader was reclaimed. While there's a * chance that other finalizable references could be enqueued * subsequently (at which point the class loader would be resurrected * by virtue of us having a strong reference to it), we should pretty * much just shut down and make sure we don't keep it alive any longer * than necessary. */ throw new ShutDown(); } try { return finalizableReferenceClass.getMethod("finalizeReferent"); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } public static Field getInheritableThreadLocalsField() { try { Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocals.setAccessible(true); return inheritableThreadLocals; } catch (Throwable t) { logger.log(Level.INFO, "Couldn't access Thread.inheritableThreadLocals." + " Reference finalizer threads will inherit thread local" + " values."); return null; } } /** Indicates that it's time to shut down the Finalizer. */ @SuppressWarnings("serial") // Never serialized or thrown out of this class. private static class ShutDown extends Exception { } }
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.io.FileNotFoundException; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.logging.Level; import java.util.logging.Logger; /** * A reference queue with an associated background thread that dequeues references and invokes * {@link FinalizableReference#finalizeReferent()} on them. * * <p>Keep a strong reference to this object until all of the associated referents have been * finalized. If this object is garbage collected earlier, the backing thread will not invoke {@code * finalizeReferent()} on the remaining references. * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public class FinalizableReferenceQueue { /* * The Finalizer thread keeps a phantom reference to this object. When the client (for example, a * map built by MapMaker) no longer has a strong reference to this object, the garbage collector * will reclaim it and enqueue the phantom reference. The enqueued reference will trigger the * Finalizer to stop. * * If this library is loaded in the system class loader, FinalizableReferenceQueue can load * Finalizer directly with no problems. * * If this library is loaded in an application class loader, it's important that Finalizer not * have a strong reference back to the class loader. Otherwise, you could have a graph like this: * * Finalizer Thread runs instance of -> Finalizer.class loaded by -> Application class loader * which loaded -> ReferenceMap.class which has a static -> FinalizableReferenceQueue instance * * Even if no other references to classes from the application class loader remain, the Finalizer * thread keeps an indirect strong reference to the queue in ReferenceMap, which keeps the * Finalizer running, and as a result, the application class loader can never be reclaimed. * * This means that dynamically loaded web applications and OSGi bundles can't be unloaded. * * If the library is loaded in an application class loader, we try to break the cycle by loading * Finalizer in its own independent class loader: * * System class loader -> Application class loader -> ReferenceMap -> FinalizableReferenceQueue * -> etc. -> Decoupled class loader -> Finalizer * * Now, Finalizer no longer keeps an indirect strong reference to the static * FinalizableReferenceQueue field in ReferenceMap. The application class loader can be reclaimed * at which point the Finalizer thread will stop and its decoupled class loader can also be * reclaimed. * * If any of this fails along the way, we fall back to loading Finalizer directly in the * application class loader. */ private static final Logger logger = Logger.getLogger(FinalizableReferenceQueue.class.getName()); private static final String FINALIZER_CLASS_NAME = "com.google.common.base.internal.Finalizer"; /** Reference to Finalizer.startFinalizer(). */ private static final Method startFinalizer; static { Class<?> finalizer = loadFinalizer( new SystemLoader(), new DecoupledLoader(), new DirectLoader()); startFinalizer = getStartFinalizer(finalizer); } /** * The actual reference queue that our background thread will poll. */ final ReferenceQueue<Object> queue; /** * Whether or not the background thread started successfully. */ final boolean threadStarted; /** * Constructs a new queue. */ @SuppressWarnings("unchecked") public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. ReferenceQueue<Object> queue; boolean threadStarted = false; try { queue = (ReferenceQueue<Object>) startFinalizer.invoke(null, FinalizableReference.class, this); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log(Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); queue = new ReferenceQueue<Object>(); } this.queue = queue; this.threadStarted = threadStarted; } /** * Repeatedly dequeues references from the queue and invokes {@link * FinalizableReference#finalizeReferent()} on them until the queue is empty. This method is a * no-op if the background thread was created successfully. */ void cleanUp() { if (threadStarted) { return; } Reference<?> reference; while ((reference = queue.poll()) != null) { /* * This is for the benefit of phantom references. Weak and soft references will have already * been cleared by this point. */ reference.clear(); try { ((FinalizableReference) reference).finalizeReferent(); } catch (Throwable t) { logger.log(Level.SEVERE, "Error cleaning up after reference.", t); } } } /** * Iterates through the given loaders until it finds one that can load Finalizer. * * @return Finalizer.class */ private static Class<?> loadFinalizer(FinalizerLoader... loaders) { for (FinalizerLoader loader : loaders) { Class<?> finalizer = loader.loadFinalizer(); if (finalizer != null) { return finalizer; } } throw new AssertionError(); } /** * Loads Finalizer.class. */ interface FinalizerLoader { /** * Returns Finalizer.class or null if this loader shouldn't or can't load it. * * @throws SecurityException if we don't have the appropriate privileges */ Class<?> loadFinalizer(); } /** * Tries to load Finalizer from the system class loader. If Finalizer is in the system class path, * we needn't create a separate loader. */ static class SystemLoader implements FinalizerLoader { @Override public Class<?> loadFinalizer() { ClassLoader systemLoader; try { systemLoader = ClassLoader.getSystemClassLoader(); } catch (SecurityException e) { logger.info("Not allowed to access system class loader."); return null; } if (systemLoader != null) { try { return systemLoader.loadClass(FINALIZER_CLASS_NAME); } catch (ClassNotFoundException e) { // Ignore. Finalizer is simply in a child class loader. return null; } } else { return null; } } } /** * Try to load Finalizer in its own class loader. If Finalizer's thread had a direct reference to * our class loader (which could be that of a dynamically loaded web application or OSGi bundle), * it would prevent our class loader from getting garbage collected. */ static class DecoupledLoader implements FinalizerLoader { private static final String LOADING_ERROR = "Could not load Finalizer in its own class loader." + "Loading Finalizer in the current class loader instead. As a result, you will not be able" + "to garbage collect this class loader. To support reclaiming this class loader, either" + "resolve the underlying issue, or move Google Collections to your system class path."; @Override public Class<?> loadFinalizer() { try { /* * We use URLClassLoader because it's the only concrete class loader implementation in the * JDK. If we used our own ClassLoader subclass, Finalizer would indirectly reference this * class loader: * * Finalizer.class -> CustomClassLoader -> CustomClassLoader.class -> This class loader * * System class loader will (and must) be the parent. */ ClassLoader finalizerLoader = newLoader(getBaseUrl()); return finalizerLoader.loadClass(FINALIZER_CLASS_NAME); } catch (Exception e) { logger.log(Level.WARNING, LOADING_ERROR, e); return null; } } /** * Gets URL for base of path containing Finalizer.class. */ URL getBaseUrl() throws IOException { // Find URL pointing to Finalizer.class file. String finalizerPath = FINALIZER_CLASS_NAME.replace('.', '/') + ".class"; URL finalizerUrl = getClass().getClassLoader().getResource(finalizerPath); if (finalizerUrl == null) { throw new FileNotFoundException(finalizerPath); } // Find URL pointing to base of class path. String urlString = finalizerUrl.toString(); if (!urlString.endsWith(finalizerPath)) { throw new IOException("Unsupported path style: " + urlString); } urlString = urlString.substring(0, urlString.length() - finalizerPath.length()); return new URL(finalizerUrl, urlString); } /** Creates a class loader with the given base URL as its classpath. */ URLClassLoader newLoader(URL base) { return new URLClassLoader(new URL[] {base}); } } /** * Loads Finalizer directly using the current class loader. We won't be able to garbage collect * this class loader, but at least the world doesn't end. */ static class DirectLoader implements FinalizerLoader { @Override public Class<?> loadFinalizer() { try { return Class.forName(FINALIZER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } } /** * Looks up Finalizer.startFinalizer(). */ static Method getStartFinalizer(Class<?> finalizer) { try { return finalizer.getMethod("startFinalizer", Class.class, Object.class); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } }
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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * A time source; returns a time value representing the number of nanoseconds * elapsed since some fixed but arbitrary point in time. * * @author Kevin Bourrillion * @since 10.0 * (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 9.0) */ @Beta @GwtCompatible public abstract class Ticker { /** * Constructor for use by subclasses. */ protected Ticker() {} /** * Returns the number of nanoseconds elapsed since this ticker's fixed * point of reference. */ public abstract long read(); /** * A ticker that reads the current time using {@link System#nanoTime}. * * @since 10.0 */ public static Ticker systemTicker() { return SYSTEM_TICKER; } private static final Ticker SYSTEM_TICKER = new Ticker() { @Override public long read() { return Platform.systemNanoTime(); } }; }
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.checkNotNull; import com.google.common.annotations.Beta; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; /** * Static utility methods pertaining to instances of {@link Throwable}. * * <p>See the Guava User Guide entry on <a href= * "http://code.google.com/p/guava-libraries/wiki/ThrowablesExplained"> * Throwables</a>. * * @author Kevin Bourrillion * @author Ben Yu * @since 1.0 */ public final class Throwables { private Throwables() {} /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@code declaredType}. Example usage: * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfInstanceOf(t, IOException.class); * Throwables.propagateIfInstanceOf(t, SQLException.class); * throw Throwables.propagate(t); * } * </pre> */ public static <X extends Throwable> void propagateIfInstanceOf( @Nullable Throwable throwable, Class<X> declaredType) throws X { // Check for null is needed to avoid frequent JNI calls to isInstance(). if (throwable != null && declaredType.isInstance(throwable)) { throw declaredType.cast(throwable); } } /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@link RuntimeException} or {@link Error}. Example usage: * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfPossible(t); * throw new RuntimeException("unexpected", t); * } * </pre> */ public static void propagateIfPossible(@Nullable Throwable throwable) { propagateIfInstanceOf(throwable, Error.class); propagateIfInstanceOf(throwable, RuntimeException.class); } /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@link RuntimeException}, {@link Error}, or * {@code declaredType}. Example usage: * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfPossible(t, OtherException.class); * throw new RuntimeException("unexpected", t); * } * </pre> * * @param throwable the Throwable to possibly propagate * @param declaredType the single checked exception type declared by the * calling method */ public static <X extends Throwable> void propagateIfPossible( @Nullable Throwable throwable, Class<X> declaredType) throws X { propagateIfInstanceOf(throwable, declaredType); propagateIfPossible(throwable); } /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@link RuntimeException}, {@link Error}, {@code declaredType1}, * or {@code declaredType2}. In the unlikely case that you have three or more * declared checked exception types, you can handle them all by invoking these * methods repeatedly. See usage example in {@link * #propagateIfPossible(Throwable, Class)}. * * @param throwable the Throwable to possibly propagate * @param declaredType1 any checked exception type declared by the calling * method * @param declaredType2 any other checked exception type declared by the * calling method */ public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(@Nullable Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) throws X1, X2 { checkNotNull(declaredType2); propagateIfInstanceOf(throwable, declaredType1); propagateIfPossible(throwable, declaredType2); } /** * Propagates {@code throwable} as-is if it is an instance of * {@link RuntimeException} or {@link Error}, or else as a last resort, wraps * it in a {@code RuntimeException} then propagates. * <p> * This method always throws an exception. The {@code RuntimeException} return * type is only for client code to make Java type system happy in case a * return value is required by the enclosing method. Example usage: * <pre> * T doSomething() { * try { * return someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * return handle(e); * } catch (Throwable t) { * throw Throwables.propagate(t); * } * } * </pre> * * @param throwable the Throwable to propagate * @return nothing will ever be returned; this return type is only for your * convenience, as illustrated in the example above */ public static RuntimeException propagate(Throwable throwable) { propagateIfPossible(checkNotNull(throwable)); throw new RuntimeException(throwable); } /** * Returns the innermost cause of {@code throwable}. The first throwable in a * chain provides context from when the error or exception was initially * detected. Example usage: * <pre> * assertEquals("Unable to assign a customer id", * Throwables.getRootCause(e).getMessage()); * </pre> */ public static Throwable getRootCause(Throwable throwable) { Throwable cause; while ((cause = throwable.getCause()) != null) { throwable = cause; } return throwable; } /** * Gets a {@code Throwable} cause chain as a list. The first entry in the * list will be {@code throwable} followed by its cause hierarchy. Note * that this is a snapshot of the cause chain and will not reflect * any subsequent changes to the cause chain. * * <p>Here's an example of how it can be used to find specific types * of exceptions in the cause chain: * * <pre> * Iterables.filter(Throwables.getCausalChain(e), IOException.class)); * </pre> * * @param throwable the non-null {@code Throwable} to extract causes from * @return an unmodifiable list containing the cause chain starting with * {@code throwable} */ @Beta // TODO(kevinb): decide best return type public static List<Throwable> getCausalChain(Throwable throwable) { checkNotNull(throwable); List<Throwable> causes = new ArrayList<Throwable>(4); while (throwable != null) { causes.add(throwable); throwable = throwable.getCause(); } return Collections.unmodifiableList(causes); } /** * Returns a string containing the result of * {@link Throwable#toString() toString()}, followed by the full, recursive * stack trace of {@code throwable}. Note that you probably should not be * parsing the resulting string; if you need programmatic access to the stack * frames, you can call {@link Throwable#getStackTrace()}. */ public static String getStackTraceAsString(Throwable throwable) { StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.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.base; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; /** * Phantom 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}. * * <p>Unlike a normal phantom reference, this reference will be cleared automatically. * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public abstract class FinalizablePhantomReference<T> extends PhantomReference<T> implements FinalizableReference { /** * Constructs a new finalizable phantom reference. * * @param referent to phantom reference * @param queue that should finalize the referent */ protected FinalizablePhantomReference(T referent, FinalizableReferenceQueue queue) { super(referent, queue.queue); queue.cleanUp(); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.CheckForNull; /** * Static utility methods derived from Android's {@code Integer.java}. */ final class AndroidInteger { /** * See {@link Ints#tryParse(String)} for the public interface. */ @CheckForNull static Integer tryParse(String string) { return tryParse(string, 10); } /** * See {@link Ints#tryParse(String, int)} for the public interface. */ @CheckForNull static Integer tryParse(String string, int radix) { checkNotNull(string); checkArgument(radix >= Character.MIN_RADIX, "Invalid radix %s, min radix is %s", radix, Character.MIN_RADIX); checkArgument(radix <= Character.MAX_RADIX, "Invalid radix %s, max radix is %s", radix, Character.MAX_RADIX); int length = string.length(), i = 0; if (length == 0) { return null; } boolean negative = string.charAt(i) == '-'; if (negative && ++i == length) { return null; } return tryParse(string, i, radix, negative); } @CheckForNull private static Integer tryParse(String string, int offset, int radix, boolean negative) { int max = Integer.MIN_VALUE / radix; int result = 0, length = string.length(); while (offset < length) { int digit = Character.digit(string.charAt(offset++), radix); if (digit == -1) { return null; } if (max > result) { return null; } int next = result * radix - digit; if (next > result) { return null; } result = next; } if (!negative) { result = -result; if (result < 0) { return null; } } // For GWT where ints do not overflow if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) { return null; } return result; } private AndroidInteger() {} }
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.primitives; 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.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code int} primitives, that are not * already found in either {@link Integer} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Ints { private Ints() {} /** * The number of bytes required to represent a primitive {@code int} * value. */ public static final int BYTES = Integer.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Integer) value).hashCode()}. * * @param value a primitive {@code int} value * @return a hash code for the value */ public static int hashCode(int value) { return value; } /** * Returns the {@code int} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code int} type * @return the {@code int} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE} */ public static int checkedCast(long value) { int result = (int) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the * {@code int} type, {@link Integer#MAX_VALUE} if it is too large, * or {@link Integer#MIN_VALUE} if it is too small */ public static int saturatedCast(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } /** * Compares the two specified {@code int} values. The sign of the value * returned is the same as that of {@code ((Integer) a).compareTo(b)}. * * @param a the first {@code int} to compare * @param b the second {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(int[] array, int target) { for (int value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(int[] array, int target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( int[] array, int target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(int[] array, int[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(int[] array, int target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( int[] array, int target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static int min(int... array) { checkArgument(array.length > 0); int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static int max(int... array) { checkArgument(array.length > 0); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new int[] {a, b}, new int[] {}, new * int[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code int} arrays * @return a single array containing all the values from the source arrays, in * order */ public static int[] concat(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } int[] result = new int[length]; int pos = 0; for (int[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 4-element byte * array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}. * For example, the input value {@code 0x12131415} would yield the byte array * {@code {0x12, 0x13, 0x14, 0x15}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(int value) { return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}; } /** * Returns the {@code int} value whose big-endian representation is stored in * the first 4 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array {@code * {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code * 0x12131415}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements */ @GwtIncompatible("doesn't work") public static int fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); } /** * Returns the {@code int} value whose byte representation is the given 4 * bytes, in big-endian order; equivalent to {@code Ints.fromByteArray(new * byte[] {b1, b2, b3, b4})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static int[] ensureCapacity( int[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static int[] copyOf(int[] original, int length) { int[] copy = new int[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code int} values separated * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code int} arrays * lexicographically. That is, it compares, using {@link * #compare(int, int)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(int[], int[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Ints.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Integer} instances into a new array of * primitive {@code int} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Integer} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static int[] toArray(Collection<Integer> collection) { if (collection instanceof IntArrayAsList) { return ((IntArrayAsList) collection).toIntArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Integer) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Integer} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Integer> asList(int... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new IntArrayAsList(backingArray); } @GwtCompatible private static class IntArrayAsList extends AbstractList<Integer> implements RandomAccess, Serializable { final int[] array; final int start; final int end; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Integer get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.indexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.lastIndexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Integer set(int index, Integer element) { checkElementIndex(index, size()); int oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Integer> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof IntArrayAsList) { IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Ints.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } int[] toIntArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); int[] result = new int[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } /** * Parses the specified string as a signed decimal integer value. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the * minus sign. * * <p>Unlike {@link Integer#parseInt(String)}, this method returns * {@code null} instead of throwing an exception if parsing fails. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even * under JDK 7, despite the change to {@link Integer#parseInt(String)} for * that version. * * @param string the string representation of an integer value * @return the integer value represented by {@code string}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as an integer * value * @since 11.0 */ @Beta @CheckForNull @GwtIncompatible("TODO") public static Integer tryParse(String string) { return AndroidInteger.tryParse(string, 10); } }
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.primitives; 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.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code char} primitives, that are not * already found in either {@link Character} or {@link Arrays}. * * <p>All the operations in this class treat {@code char} values strictly * numerically; they are neither Unicode-aware nor locale-dependent. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Chars { private Chars() {} /** * The number of bytes required to represent a primitive {@code char} * value. */ public static final int BYTES = Character.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Character) value).hashCode()}. * * @param value a primitive {@code char} value * @return a hash code for the value */ public static int hashCode(char value) { return value; } /** * Returns the {@code char} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code char} type * @return the {@code char} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Character#MAX_VALUE} or less than {@link Character#MIN_VALUE} */ public static char checkedCast(long value) { char result = (char) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code char} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code char} if it is in the range of the * {@code char} type, {@link Character#MAX_VALUE} if it is too large, * or {@link Character#MIN_VALUE} if it is too small */ public static char saturatedCast(long value) { if (value > Character.MAX_VALUE) { return Character.MAX_VALUE; } if (value < Character.MIN_VALUE) { return Character.MIN_VALUE; } return (char) value; } /** * Compares the two specified {@code char} values. The sign of the value * returned is the same as that of {@code ((Character) a).compareTo(b)}. * * @param a the first {@code char} to compare * @param b the second {@code char} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(char a, char b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(char[] array, char target) { for (char value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(char[] array, char target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( char[] array, char target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(char[] array, char[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(char[] array, char target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( char[] array, char target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char min(char... array) { checkArgument(array.length > 0); char min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char max(char... array) { checkArgument(array.length > 0); char max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new char[] {a, b}, new char[] {}, new * char[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code char} arrays * @return a single array containing all the values from the source arrays, in * order */ public static char[] concat(char[]... arrays) { int length = 0; for (char[] array : arrays) { length += array.length; } char[] result = new char[length]; int pos = 0; for (char[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte * array; equivalent to {@code * ByteBuffer.allocate(2).putChar(value).array()}. For example, the input * value {@code '\\u5432'} would yield the byte array {@code {0x54, 0x32}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(char value) { return new byte[] { (byte) (value >> 8), (byte) value}; } /** * Returns the {@code char} value whose big-endian representation is * stored in the first 2 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getChar()}. For example, the input byte array * {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 * elements */ @GwtIncompatible("doesn't work") public static char fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code char} value whose byte representation is the given 2 * bytes, in big-endian order; equivalent to {@code Chars.fromByteArray(new * byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static char fromBytes(byte b1, byte b2) { return (char) ((b1 << 8) | (b2 & 0xFF)); } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static char[] ensureCapacity( char[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static char[] copyOf(char[] original, int length) { char[] copy = new char[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code char} values separated * by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code char} values, possibly empty */ public static String join(String separator, char... array) { checkNotNull(separator); int len = array.length; if (len == 0) { return ""; } StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); builder.append(array[0]); for (int i = 1; i < len; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code char} arrays * lexicographically. That is, it compares, using {@link * #compare(char, char)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < ['a'] < ['a', 'b'] < ['b']}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(char[], char[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<char[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<char[]> { INSTANCE; @Override public int compare(char[] left, char[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Chars.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Character} instances into a new array of * primitive {@code char} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Character} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static char[] toArray(Collection<Character> collection) { if (collection instanceof CharArrayAsList) { return ((CharArrayAsList) collection).toCharArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; char[] array = new char[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Character) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Character} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Character> asList(char... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new CharArrayAsList(backingArray); } @GwtCompatible private static class CharArrayAsList extends AbstractList<Character> implements RandomAccess, Serializable { final char[] array; final int start; final int end; CharArrayAsList(char[] array) { this(array, 0, array.length); } CharArrayAsList(char[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Character get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.indexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.lastIndexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Character set(int index, Character element) { checkElementIndex(index, size()); char oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Character> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new CharArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof CharArrayAsList) { CharArrayAsList that = (CharArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Chars.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 3); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } char[] toCharArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); char[] result = new char[size]; System.arraycopy(array, start, result, 0, size); return result; } 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.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import sun.misc.Unsafe; import java.lang.reflect.Field; import java.nio.ByteOrder; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Comparator; /** * Static utility methods pertaining to {@code byte} primitives that interpret * values as <i>unsigned</i> (that is, any negative value {@code b} is treated * as the positive value {@code 256 + b}). The corresponding methods that treat * the values as signed are found in {@link SignedBytes}, and the methods for * which signedness is not an issue are in {@link Bytes}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @author Martin Buchholz * @author Hiroshi Yamauchi * @since 1.0 */ public final class UnsignedBytes { private UnsignedBytes() {} /** * The largest power of two that can be represented as an unsigned {@code byte}. * * @since 10.0 */ public static final byte MAX_POWER_OF_TWO = (byte) (1 << 7); /** * Returns the value of the given byte as an integer, when treated as * unsigned. That is, returns {@code value + 256} if {@code value} is * negative; {@code value} itself otherwise. * * @since 6.0 */ public static int toInt(byte value) { return value & 0xFF; } /** * Returns the {@code byte} value that, when treated as unsigned, is equal to * {@code value}, if possible. * * @param value a value between 0 and 255 inclusive * @return the {@code byte} value that, when treated as unsigned, equals * {@code value} * @throws IllegalArgumentException if {@code value} is negative or greater * than 255 */ public static byte checkedCast(long value) { checkArgument(value >> 8 == 0, "out of range: %s", value); return (byte) value; } /** * Returns the {@code byte} value that, when treated as unsigned, is nearest * in value to {@code value}. * * @param value any {@code long} value * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if * {@code value <= 0}, and {@code value} cast to {@code byte} otherwise */ public static byte saturatedCast(long value) { if (value > 255) { return (byte) 255; // -1 } if (value < 0) { return (byte) 0; } return (byte) value; } /** * Compares the two specified {@code byte} values, treating them as unsigned * values between 0 and 255 inclusive. For example, {@code (byte) -127} is * considered greater than {@code (byte) 127} because it is seen as having * the value of positive {@code 129}. * * @param a the first {@code byte} to compare * @param b the second {@code byte} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(byte a, byte b) { return toInt(a) - toInt(b); } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte min(byte... array) { checkArgument(array.length > 0); int min = toInt(array[0]); for (int i = 1; i < array.length; i++) { int next = toInt(array[i]); if (next < min) { min = next; } } return (byte) min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is greater than or equal * to every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte max(byte... array) { checkArgument(array.length > 0); int max = toInt(array[0]); for (int i = 1; i < array.length; i++) { int next = toInt(array[i]); if (next > max) { max = next; } } return (byte) max; } /** * Returns a string containing the supplied {@code byte} values separated by * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2, * (byte) 255)} returns the string {@code "1:2:255"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code byte} values, possibly empty */ public static String join(String separator, byte... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(toInt(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toInt(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two {@code byte} arrays * lexicographically. That is, it compares, using {@link * #compare(byte, byte)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] < * [0x01, 0x80] < [0x02]}. Values are treated as unsigned. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<byte[]> lexicographicalComparator() { return LexicographicalComparatorHolder.BEST_COMPARATOR; } @VisibleForTesting static Comparator<byte[]> lexicographicalComparatorJavaImpl() { return LexicographicalComparatorHolder.PureJavaComparator.INSTANCE; } /** * Provides a lexicographical comparator implementation; either a Java * implementation or a faster implementation based on {@link Unsafe}. * * <p>Uses reflection to gracefully fall back to the Java implementation if * {@code Unsafe} isn't available. */ @VisibleForTesting static class LexicographicalComparatorHolder { static final String UNSAFE_COMPARATOR_NAME = LexicographicalComparatorHolder.class.getName() + "$UnsafeComparator"; static final Comparator<byte[]> BEST_COMPARATOR = getBestComparator(); @VisibleForTesting enum UnsafeComparator implements Comparator<byte[]> { INSTANCE; static final boolean littleEndian = ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); /* * The following static final fields exist for performance reasons. * * In UnsignedBytesBenchmark, accessing the following objects via static * final fields is the fastest (more than twice as fast as the Java * implementation, vs ~1.5x with non-final static fields, on x86_32) * under the Hotspot server compiler. The reason is obviously that the * non-final fields need to be reloaded inside the loop. * * And, no, defining (final or not) local variables out of the loop still * isn't as good because the null check on the theUnsafe object remains * inside the loop and BYTE_ARRAY_BASE_OFFSET doesn't get * constant-folded. * * The compiler can treat static final fields as compile-time constants * and can constant-fold them while (final or not) local variables are * run time values. */ static final Unsafe theUnsafe; /** The offset to the first element in a byte array. */ static final int BYTE_ARRAY_BASE_OFFSET; static { theUnsafe = (Unsafe) AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return f.get(null); } catch (NoSuchFieldException e) { // It doesn't matter what we throw; // it's swallowed in getBestComparator(). throw new Error(); } catch (IllegalAccessException e) { throw new Error(); } } }); BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class); // sanity check - this should never fail if (theUnsafe.arrayIndexScale(byte[].class) != 1) { throw new AssertionError(); } } @Override public int compare(byte[] left, byte[] right) { int minLength = Math.min(left.length, right.length); int minWords = minLength / Longs.BYTES; /* * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a * time is no slower than comparing 4 bytes at a time even on 32-bit. * On the other hand, it is substantially faster on 64-bit. */ for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) { long lw = theUnsafe.getLong(left, BYTE_ARRAY_BASE_OFFSET + (long) i); long rw = theUnsafe.getLong(right, BYTE_ARRAY_BASE_OFFSET + (long) i); long diff = lw ^ rw; if (diff != 0) { if (!littleEndian) { return UnsignedLongs.compare(lw, rw); } // Use binary search int n = 0; int y; int x = (int) diff; if (x == 0) { x = (int) (diff >>> 32); n = 32; } y = x << 16; if (y == 0) { n += 16; } else { x = y; } y = x << 8; if (y == 0) { n += 8; } return (int) (((lw >>> n) & 0xFFL) - ((rw >>> n) & 0xFFL)); } } // The epilogue to cover the last (minLength % 8) elements. for (int i = minWords * Longs.BYTES; i < minLength; i++) { int result = UnsignedBytes.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } enum PureJavaComparator implements Comparator<byte[]> { INSTANCE; @Override public int compare(byte[] left, byte[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = UnsignedBytes.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns the Unsafe-using Comparator, or falls back to the pure-Java * implementation if unable to do so. */ static Comparator<byte[]> getBestComparator() { try { Class<?> theClass = Class.forName(UNSAFE_COMPARATOR_NAME); // yes, UnsafeComparator does implement Comparator<byte[]> @SuppressWarnings("unchecked") Comparator<byte[]> comparator = (Comparator<byte[]>) theClass.getEnumConstants()[0]; return comparator; } catch (Throwable t) { // ensure we really catch *everything* return lexicographicalComparatorJavaImpl(); } } } }
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.primitives; 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.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code long} primitives, that are not * already found in either {@link Long} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Longs { private Longs() {} /** * The number of bytes required to represent a primitive {@code long} * value. */ public static final int BYTES = Long.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code long}. * * @since 10.0 */ public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Long) value).hashCode()}. * * <p>This method always return the value specified by {@link * Long#hashCode()} in java, which might be different from * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()} * in GWT does not obey the JRE contract. * * @param value a primitive {@code long} value * @return a hash code for the value */ public static int hashCode(long value) { return (int) (value ^ (value >>> 32)); } /** * Compares the two specified {@code long} values. The sign of the value * returned is the same as that of {@code ((Long) a).compareTo(b)}. * * @param a the first {@code long} to compare * @param b the second {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(long[] array, long target) { for (long value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(long[] array, long target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( long[] array, long target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(long[] array, long[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(long[] array, long target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( long[] array, long target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new long[] {a, b}, new long[] {}, new * long[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code long} arrays * @return a single array containing all the values from the source arrays, in * order */ public static long[] concat(long[]... arrays) { int length = 0; for (long[] array : arrays) { length += array.length; } long[] result = new long[length]; int pos = 0; for (long[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in an 8-element byte * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}. * For example, the input value {@code 0x1213141516171819L} would yield the * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(long value) { return new byte[] { (byte) (value >> 56), (byte) (value >> 48), (byte) (value >> 40), (byte) (value >> 32), (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}; } /** * Returns the {@code long} value whose big-endian representation is * stored in the first 8 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the * {@code long} value {@code 0x1213141516171819L}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 8 * elements */ @GwtIncompatible("doesn't work") public static long fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]) ; } /** * Returns the {@code long} value whose byte representation is the given 8 * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static long[] ensureCapacity( long[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static long[] copyOf(long[] original, int length) { long[] copy = new long[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code long} values separated * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 10); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code long} arrays * lexicographically. That is, it compares, using {@link * #compare(long, long)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < [1L] < [1L, 2L] < [2L]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(long[], long[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Longs.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Long} instances into a new array of * primitive {@code long} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Long} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static long[] toArray(Collection<Long> collection) { if (collection instanceof LongArrayAsList) { return ((LongArrayAsList) collection).toLongArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; long[] array = new long[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Long) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Long} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Long> asList(long... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new LongArrayAsList(backingArray); } @GwtCompatible private static class LongArrayAsList extends AbstractList<Long> implements RandomAccess, Serializable { final long[] array; final int start; final int end; LongArrayAsList(long[] array) { this(array, 0, array.length); } LongArrayAsList(long[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Long get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.indexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.lastIndexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Long set(int index, Long element) { checkElementIndex(index, size()); long oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Long> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new LongArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof LongArrayAsList) { LongArrayAsList that = (LongArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Longs.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 10); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } long[] toLongArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); long[] result = new long[size]; System.arraycopy(array, start, result, 0, size); return result; } 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.primitives; 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.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code short} primitives, that are not * already found in either {@link Short} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Shorts { private Shorts() {} /** * The number of bytes required to represent a primitive {@code short} * value. */ public static final int BYTES = Short.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code short}. * * @since 10.0 */ public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Short) value).hashCode()}. * * @param value a primitive {@code short} value * @return a hash code for the value */ public static int hashCode(short value) { return value; } /** * Returns the {@code short} value that is equal to {@code value}, if * possible. * * @param value any value in the range of the {@code short} type * @return the {@code short} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Short#MAX_VALUE} or less than {@link Short#MIN_VALUE} */ public static short checkedCast(long value) { short result = (short) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code short} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code short} if it is in the range of the * {@code short} type, {@link Short#MAX_VALUE} if it is too large, * or {@link Short#MIN_VALUE} if it is too small */ public static short saturatedCast(long value) { if (value > Short.MAX_VALUE) { return Short.MAX_VALUE; } if (value < Short.MIN_VALUE) { return Short.MIN_VALUE; } return (short) value; } /** * Compares the two specified {@code short} values. The sign of the value * returned is the same as that of {@code ((Short) a).compareTo(b)}. * * @param a the first {@code short} to compare * @param b the second {@code short} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(short a, short b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(short[] array, short target) { for (short value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(short[] array, short target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( short[] array, short target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(short[] array, short[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(short[] array, short target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( short[] array, short target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static short min(short... array) { checkArgument(array.length > 0); short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static short max(short... array) { checkArgument(array.length > 0); short max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new short[] {a, b}, new short[] {}, new * short[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code short} arrays * @return a single array containing all the values from the source arrays, in * order */ public static short[] concat(short[]... arrays) { int length = 0; for (short[] array : arrays) { length += array.length; } short[] result = new short[length]; int pos = 0; for (short[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte * array; equivalent to {@code * ByteBuffer.allocate(2).putShort(value).array()}. For example, the input * value {@code (short) 0x1234} would yield the byte array {@code {0x12, * 0x34}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(short value) { return new byte[] { (byte) (value >> 8), (byte) value}; } /** * Returns the {@code short} value whose big-endian representation is * stored in the first 2 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array * {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 * elements */ @GwtIncompatible("doesn't work") public static short fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code short} value whose byte representation is the given 2 * bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new * byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static short fromBytes(byte b1, byte b2) { return (short) ((b1 << 8) | (b2 & 0xFF)); } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static short[] ensureCapacity( short[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static short[] copyOf(short[] original, int length) { short[] copy = new short[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code short} values separated * by {@code separator}. For example, {@code join("-", (short) 1, (short) 2, * (short) 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code short} values, possibly empty */ public static String join(String separator, short... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 6); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code short} arrays * lexicographically. That is, it compares, using {@link * #compare(short, short)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [(short) 1] < * [(short) 1, (short) 2] < [(short) 2]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(short[], short[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<short[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<short[]> { INSTANCE; @Override public int compare(short[] left, short[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Shorts.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Short} instances into a new array of * primitive {@code short} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Short} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static short[] toArray(Collection<Short> collection) { if (collection instanceof ShortArrayAsList) { return ((ShortArrayAsList) collection).toShortArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; short[] array = new short[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Short) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Short} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Short> asList(short... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new ShortArrayAsList(backingArray); } @GwtCompatible private static class ShortArrayAsList extends AbstractList<Short> implements RandomAccess, Serializable { final short[] array; final int start; final int end; ShortArrayAsList(short[] array) { this(array, 0, array.length); } ShortArrayAsList(short[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Short get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.indexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.lastIndexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Short set(int index, Short element) { checkElementIndex(index, size()); short oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Short> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new ShortArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof ShortArrayAsList) { ShortArrayAsList that = (ShortArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Shorts.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 6); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } short[] toShortArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); short[] result = new short[size]; System.arraycopy(array, start, result, 0, size); return result; } 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.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Arrays; import java.util.Comparator; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * Static utility methods pertaining to {@code int} primitives that interpret values as * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value * {@code 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well * as signed versions of methods for which signedness is an issue. * * <p>In addition, this class provides several static methods for converting an {@code int} to a * {@code String} and a {@code String} to an {@code int} that treat the {@code int} as an unsigned * number. * * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned * {@code int} values. When possible, it is recommended that the {@link UnsignedInteger} wrapper * class be used, at a small efficiency penalty, to enforce the distinction in the type system. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @since 11.0 */ @Beta @GwtCompatible public final class UnsignedInts { static final long INT_MASK = 0xffffffffL; private UnsignedInts() {} static int flip(int value) { return value ^ Integer.MIN_VALUE; } /** * Compares the two specified {@code int} values, treating them as unsigned values between * {@code 0} and {@code 2^32 - 1} inclusive. * * @param a the first unsigned {@code int} to compare * @param b the second unsigned {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return Ints.compare(flip(a), flip(b)); } /** * Returns the value of the given {@code int} as a {@code long}, when treated as unsigned. */ public static long toLong(int value) { return value & INT_MASK; } /** * Returns the least value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code int} values * @return the value present in {@code array} that is less than or equal to every other value in * the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static int min(int... array) { checkArgument(array.length > 0); int min = flip(array[0]); for (int i = 1; i < array.length; i++) { int next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } /** * Returns the greatest value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code int} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static int max(int... array) { checkArgument(array.length > 0); int max = flip(array[0]); for (int i = 1; i < array.length; i++) { int next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } /** * Returns a string containing the supplied unsigned {@code int} values separated by * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting * string (but not at the start or end) * @param array an array of unsigned {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two arrays of unsigned {@code int} values lexicographically. * That is, it compares, using {@link #compare(int, int)}), the first pair of values that follow * any common prefix, or when one array is a prefix of the other, treats the shorter array as the * lesser. For example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> Lexicographical order * article at Wikipedia</a> */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedInts.compare(left[i], right[i]); } } return left.length - right.length; } } /** * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static int divide(int dividend, int divisor) { return (int) (toLong(dividend) / toLong(divisor)); } /** * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static int remainder(int dividend, int divisor) { return (int) (toLong(dividend) % toLong(divisor)); } /** * Returns the unsigned {@code int} value represented by the given decimal string. * * @throws NumberFormatException if the string does not contain a valid unsigned integer, or if * the value represented is too large to fit in an unsigned {@code int}. * @throws NullPointerException if {@code s} is null */ public static int parseUnsignedInt(String s) { return parseUnsignedInt(s, 10); } /** * Returns the unsigned {@code int} value represented by a string with the given radix. * * @param string the string containing the unsigned integer representation to be parsed. * @param radix the radix to use while parsing {@code s}; must be between * {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}. * @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or * if supplied radix is invalid. */ public static int parseUnsignedInt(String string, int radix) { checkNotNull(string); long result = Long.parseLong(string, radix); if ((result & INT_MASK) != result) { throw new NumberFormatException("Input " + string + " in base " + radix + " is not in the range of an unsigned integer"); } return (int) result; } /** * Returns a string representation of x, where x is treated as unsigned. */ public static String toString(int x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated * as unsigned. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static String toString(int x, int radix) { long asLong = x & INT_MASK; return Long.toString(asLong, radix); } }
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. */ /** * Static utilities for working with the eight primitive types and {@code void}, * and value types for treating them as unsigned. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * <h2>Contents</h2> * * <h3>General static utilities</h3> * * <ul> * <li>{@link com.google.common.primitives.Primitives} * </ul> * * <h3>Per-type static utilities</h3> * * <ul> * <li>{@link com.google.common.primitives.Booleans} * <li>{@link com.google.common.primitives.Bytes} * <ul> * <li>{@link com.google.common.primitives.SignedBytes} * <li>{@link com.google.common.primitives.UnsignedBytes} * </ul> * <li>{@link com.google.common.primitives.Chars} * <li>{@link com.google.common.primitives.Doubles} * <li>{@link com.google.common.primitives.Floats} * <li>{@link com.google.common.primitives.Ints} * <ul> * <li>{@link com.google.common.primitives.UnsignedInts} * </ul> * <li>{@link com.google.common.primitives.Longs} * <ul> * <li>{@link com.google.common.primitives.UnsignedLongs} * </ul> * <li>{@link com.google.common.primitives.Shorts} * </ul> * * <h3>Value types</h3> * <ul> * <li>{@link com.google.common.primitives.UnsignedInteger} * <li>{@link com.google.common.primitives.UnsignedLong} * </ul> */ @ParametersAreNonnullByDefault package com.google.common.primitives; import javax.annotation.ParametersAreNonnullByDefault;
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.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * Static utility methods pertaining to {@code long} primitives that interpret values as * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value * {@code 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as * well as signed versions of methods for which signedness is an issue. * * <p>In addition, this class provides several static methods for converting a {@code long} to a * {@code String} and a {@code String} to a {@code long} that treat the {@code long} as an unsigned * number. * * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned * {@code long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper * class be used, at a small efficiency penalty, to enforce the distinction in the type system. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @author Brian Milch * @author Colin Evans * @since 10.0 */ @Beta @GwtCompatible public final class UnsignedLongs { private UnsignedLongs() {} public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 /** * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on * longs, that is, {@code a <= b} as unsigned longs if and only if {@code rotate(a) <= rotate(b)} * as signed longs. */ private static long flip(long a) { return a ^ Long.MIN_VALUE; } /** * Compares the two specified {@code long} values, treating them as unsigned values between * {@code 0} and {@code 2^64 - 1} inclusive. * * @param a the first unsigned {@code long} to compare * @param b the second unsigned {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); } /** * Returns the least value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is less than or equal to every other value in * the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } /** * Returns the greatest value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } /** * Returns a string containing the supplied unsigned {@code long} values separated by * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting * string (but not at the start or end) * @param array an array of unsigned {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two arrays of unsigned {@code long} values * lexicographically. That is, it compares, using {@link #compare(long, long)}), the first pair of * values that follow any common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with * {@link Arrays#equals(long[], long[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order * article at Wikipedia</a> */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedLongs.compare(left[i], right[i]); } } return left.length - right.length; } } /** * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static long divide(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return 0; // dividend < divisor } else { return 1; // dividend >= divisor } } // Optimization - use signed division if dividend < 2^63 if (dividend >= 0) { return dividend / divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); } /** * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 * @since 11.0 */ public static long remainder(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return dividend; // dividend < divisor } else { return dividend - divisor; // dividend >= divisor } } // Optimization - use signed modulus if dividend < 2^63 if (dividend >= 0) { return dividend % divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } /** * Returns the unsigned {@code long} value represented by the given decimal string. * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value */ public static long parseUnsignedLong(String s) { return parseUnsignedLong(s, 10); } /** * Returns the unsigned {@code long} value represented by a string with the given radix. * * @param s the string containing the unsigned {@code long} representation to be parsed. * @param radix the radix to use while parsing {@code s} * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static long parseUnsignedLong(String s, int radix) { checkNotNull(s); if (s.length() == 0) { throw new NumberFormatException("empty string"); } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException("illegal radix:" + radix); } int max_safe_pos = maxSafeDigits[radix] - 1; long value = 0; for (int pos = 0; pos < s.length(); pos++) { int digit = Character.digit(s.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(s); } if (pos > max_safe_pos && overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + s); } value = (value * radix) + digit; } return value; } /** * Returns true if (current * radix) + digit is a number too large to be represented by an * unsigned long. This is useful for detecting overflow while parsing a string representation of * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give * undefined results or an ArrayIndexOutOfBoundsException. */ private static boolean overflowInParse(long current, int digit, int radix) { if (current >= 0) { if (current < maxValueDivs[radix]) { return false; } if (current > maxValueDivs[radix]) { return true; } // current == maxValueDivs[radix] return (digit > maxValueMods[radix]); } // current < 0: high bit is set return true; } /** * Returns a string representation of x, where x is treated as unsigned. */ public static String toString(long x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated * as unsigned. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static String toString(long x, int radix) { checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); if (x == 0) { // Simply return "0" return "0"; } else { char[] buf = new char[64]; int i = buf.length; if (x < 0) { // Split x into high-order and low-order halves. // Individual digits are generated from the bottom half into which // bits are moved continously from the top half. long top = x >>> 32; long bot = (x & 0xffffffffl) + ((top % radix) << 32); top /= radix; while ((bot > 0) || (top > 0)) { buf[--i] = Character.forDigit((int) (bot % radix), radix); bot = (bot / radix) + ((top % radix) << 32); top /= radix; } } else { // Simple modulo/division approach while (x > 0) { buf[--i] = Character.forDigit((int) (x % radix), radix); x /= radix; } } // Generate string return new String(buf, i, buf.length - i); } } // calculated as 0xffffffffffffffff / radix private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; static { BigInteger overflow = new BigInteger("10000000000000000", 16); for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { maxValueDivs[i] = divide(MAX_VALUE, i); maxValueMods[i] = (int) remainder(MAX_VALUE, i); maxSafeDigits[i] = overflow.toString(i).length() - 1; } } }
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.primitives; 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.checkPositionIndexes; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.POSITIVE_INFINITY; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code double} primitives, that are not * already found in either {@link Double} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible public final class Doubles { private Doubles() {} /** * The number of bytes required to represent a primitive {@code double} * value. * * @since 10.0 */ public static final int BYTES = Double.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Double) value).hashCode()}. * * @param value a primitive {@code double} value * @return a hash code for the value */ public static int hashCode(double value) { return ((Double) value).hashCode(); // TODO(kevinb): do it this way when we can (GWT problem): // long bits = Double.doubleToLongBits(value); // return (int)(bits ^ (bits >>> 32)); } /** * Compares the two specified {@code double} values. The sign of the value * returned is the same as that of <code>((Double) a).{@linkplain * Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is * treated as greater than all other values, and {@code 0.0 > -0.0}. * * @param a the first {@code double} to compare * @param b the second {@code double} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(double a, double b) { return Double.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is * equivalent to, but not necessarily implemented as, * {@code !(Double.isInfinite(value) || Double.isNaN(value))}. * * @since 10.0 */ public static boolean isFinite(double value) { return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. Note that this always returns {@code false} when {@code * target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(double[] array, double target) { for (double value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(double[] array, double target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( double[] array, double target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains * {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(double[] array, double[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(double[] array, double target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( double[] array, double target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of * comparison as {@link Math#min(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static double min(double... array) { checkArgument(array.length > 0); double min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules * of comparison as {@link Math#max(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static double max(double... array) { checkArgument(array.length > 0); double max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new double[] {a, b}, new double[] {}, new * double[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code double} arrays * @return a single array containing all the values from the source arrays, in * order */ public static double[] concat(double[]... arrays) { int length = 0; for (double[] array : arrays) { length += array.length; } double[] result = new double[length]; int pos = 0; for (double[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static double[] ensureCapacity( double[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static double[] copyOf(double[] original, int length) { double[] copy = new double[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code double} values, converted * to strings as specified by {@link Double#toString(double)}, and separated * by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns * the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Double#toString(double)} formats {@code double} * differently in GWT sometimes. In the previous example, it returns the string * {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code double} values, possibly empty */ public static String join(String separator, double... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code double} arrays * lexicographically. That is, it compares, using {@link * #compare(double, double)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(double[], double[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<double[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<double[]> { INSTANCE; @Override public int compare(double[] left, double[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Doubles.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Double} instances into a new array of * primitive {@code double} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Double} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static double[] toArray(Collection<Double> collection) { if (collection instanceof DoubleArrayAsList) { return ((DoubleArrayAsList) collection).toDoubleArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; double[] array = new double[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Double) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Double} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code * NaN}, or if {@code NaN} is used as a parameter to any of its methods. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Double> asList(double... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new DoubleArrayAsList(backingArray); } @GwtCompatible private static class DoubleArrayAsList extends AbstractList<Double> implements RandomAccess, Serializable { final double[] array; final int start; final int end; DoubleArrayAsList(double[] array) { this(array, 0, array.length); } DoubleArrayAsList(double[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Double get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Double) && Doubles.indexOf(array, (Double) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.indexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.lastIndexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Double set(int index, Double element) { checkElementIndex(index, size()); double oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Double> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof DoubleArrayAsList) { DoubleArrayAsList that = (DoubleArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Doubles.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } double[] toDoubleArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); double[] result = new double[size]; System.arraycopy(array, start, result, 0, size); return result; } 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.primitives; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Contains static utility methods pertaining to primitive types and their * corresponding wrapper types. * * @author Kevin Bourrillion * @since 1.0 */ public final class Primitives { private Primitives() {} /** A map from primitive types to their corresponding wrapper types. */ private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE; /** A map from wrapper types to their corresponding primitive types. */ private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPE; // Sad that we can't use a BiMap. :( static { Map<Class<?>, Class<?>> primToWrap = new HashMap<Class<?>, Class<?>>(16); Map<Class<?>, Class<?>> wrapToPrim = new HashMap<Class<?>, Class<?>>(16); add(primToWrap, wrapToPrim, boolean.class, Boolean.class); add(primToWrap, wrapToPrim, byte.class, Byte.class); add(primToWrap, wrapToPrim, char.class, Character.class); add(primToWrap, wrapToPrim, double.class, Double.class); add(primToWrap, wrapToPrim, float.class, Float.class); add(primToWrap, wrapToPrim, int.class, Integer.class); add(primToWrap, wrapToPrim, long.class, Long.class); add(primToWrap, wrapToPrim, short.class, Short.class); add(primToWrap, wrapToPrim, void.class, Void.class); PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap); WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim); } private static void add(Map<Class<?>, Class<?>> forward, Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) { forward.put(key, value); backward.put(value, key); } /** * Returns an immutable set of all nine primitive types (including {@code * void}). Note that a simpler way to test whether a {@code Class} instance * is a member of this set is to call {@link Class#isPrimitive}. * * @since 3.0 */ public static Set<Class<?>> allPrimitiveTypes() { return PRIMITIVE_TO_WRAPPER_TYPE.keySet(); } /** * Returns an immutable set of all nine primitive-wrapper types (including * {@link Void}). * * @since 3.0 */ public static Set<Class<?>> allWrapperTypes() { return WRAPPER_TO_PRIMITIVE_TYPE.keySet(); } /** * Returns {@code true} if {@code type} is one of the nine * primitive-wrapper types, such as {@link Integer}. * * @see Class#isPrimitive */ public static boolean isWrapperType(Class<?> type) { return WRAPPER_TO_PRIMITIVE_TYPE.containsKey(checkNotNull(type)); } /** * Returns the corresponding wrapper type of {@code type} if it is a primitive * type; otherwise returns {@code type} itself. Idempotent. * <pre> * wrap(int.class) == Integer.class * wrap(Integer.class) == Integer.class * wrap(String.class) == String.class * </pre> */ public static <T> Class<T> wrap(Class<T> type) { checkNotNull(type); // cast is safe: long.class and Long.class are both of type Class<Long> @SuppressWarnings("unchecked") Class<T> wrapped = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE.get(type); return (wrapped == null) ? type : wrapped; } /** * Returns the corresponding primitive type of {@code type} if it is a * wrapper type; otherwise returns {@code type} itself. Idempotent. * <pre> * unwrap(Integer.class) == int.class * unwrap(int.class) == int.class * unwrap(String.class) == String.class * </pre> */ public static <T> Class<T> unwrap(Class<T> type) { checkNotNull(type); // cast is safe: long.class and Long.class are both of type Class<Long> @SuppressWarnings("unchecked") Class<T> unwrapped = (Class<T>) WRAPPER_TO_PRIMITIVE_TYPE.get(type); return (unwrapped == null) ? type : unwrapped; } }
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.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.primitives.UnsignedInts.INT_MASK; import static com.google.common.primitives.UnsignedInts.compare; import static com.google.common.primitives.UnsignedInts.toLong; import java.math.BigInteger; import javax.annotation.Nullable; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; /** * A wrapper class for unsigned {@code int} values, supporting arithmetic operations. * * <p>In some cases, when speed is more important than code readability, it may be faster simply to * treat primitive {@code int} values as unsigned, using the methods from {@link UnsignedInts}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @since 11.0 */ @Beta @GwtCompatible(emulated = true) public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> { public static final UnsignedInteger ZERO = asUnsigned(0); public static final UnsignedInteger ONE = asUnsigned(1); public static final UnsignedInteger MAX_VALUE = asUnsigned(-1); private final int value; private UnsignedInteger(int value) { this.value = value & 0xffffffff; } /** * Returns an {@code UnsignedInteger} that, when treated as signed, is * equal to {@code value}. */ public static UnsignedInteger asUnsigned(int value) { return new UnsignedInteger(value); } /** * Returns an {@code UnsignedInteger} that is equal to {@code value}, * if possible. The inverse operation of {@link #longValue()}. */ public static UnsignedInteger valueOf(long value) { checkArgument((value & INT_MASK) == value, "value (%s) is outside the range for an unsigned integer value", value); return asUnsigned((int) value); } /** * Returns a {@code UnsignedInteger} representing the same value as the specified * {@link BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}. * * @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32} */ public static UnsignedInteger valueOf(BigInteger value) { checkNotNull(value); checkArgument(value.signum() >= 0 && value.bitLength() <= Integer.SIZE, "value (%s) is outside the range for an unsigned integer value", value); return asUnsigned(value.intValue()); } /** * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed * as an unsigned {@code int} value. * * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int} * value */ public static UnsignedInteger valueOf(String string) { return valueOf(string, 10); } /** * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed * as an unsigned {@code int} value in the specified radix. * * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int} * value */ public static UnsignedInteger valueOf(String string, int radix) { return asUnsigned(UnsignedInts.parseUnsignedInt(string, radix)); } /** * Returns the result of adding this and {@code val}. If the result would have more than 32 bits, * returns the low 32 bits of the result. */ public UnsignedInteger add(UnsignedInteger val) { checkNotNull(val); return asUnsigned(this.value + val.value); } /** * Returns the result of subtracting this and {@code val}. If the result would be negative, * returns the low 32 bits of the result. */ public UnsignedInteger subtract(UnsignedInteger val) { checkNotNull(val); return asUnsigned(this.value - val.value); } /** * Returns the result of multiplying this and {@code val}. If the result would have more than 32 * bits, returns the low 32 bits of the result. */ @GwtIncompatible("Does not truncate correctly") public UnsignedInteger multiply(UnsignedInteger val) { checkNotNull(val); return asUnsigned(value * val.value); } /** * Returns the result of dividing this by {@code val}. */ public UnsignedInteger divide(UnsignedInteger val) { checkNotNull(val); return asUnsigned(UnsignedInts.divide(value, val.value)); } /** * Returns the remainder of dividing this by {@code val}. */ public UnsignedInteger remainder(UnsignedInteger val) { checkNotNull(val); return asUnsigned(UnsignedInts.remainder(value, val.value)); } /** * Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse * operation to {@link #asUnsigned}. * * <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value * will be equal to {@code this - 2^32}. */ @Override public int intValue() { return value; } /** * Returns the value of this {@code UnsignedInteger} as a {@code long}. */ @Override public long longValue() { return toLong(value); } /** * Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening * primitive conversion from {@code int} to {@code float}, and correctly rounded. */ @Override public float floatValue() { return longValue(); } /** * Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening * primitive conversion from {@code int} to {@code double}, and correctly rounded. */ @Override public double doubleValue() { return longValue(); } /** * Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}. */ public BigInteger bigIntegerValue() { return BigInteger.valueOf(longValue()); } /** * Compares this unsigned integer to another unsigned integer. * Returns {@code 0} if they are equal, a negative number if {@code this < other}, * and a positive number if {@code this > other}. */ @Override public int compareTo(UnsignedInteger other) { checkNotNull(other); return compare(value, other.value); } @Override public int hashCode() { return value; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof UnsignedInteger) { UnsignedInteger other = (UnsignedInteger) obj; return value == other.value; } return false; } /** * Returns a string representation of the {@code UnsignedInteger} value, in base 10. */ @Override public String toString() { return toString(10); } /** * Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}. * If {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix * {@code 10} is used. */ public String toString(int radix) { return UnsignedInts.toString(value, radix); } }
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.primitives; 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.checkPositionIndexes; import static java.lang.Float.NEGATIVE_INFINITY; import static java.lang.Float.POSITIVE_INFINITY; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code float} primitives, that are not * already found in either {@link Float} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible public final class Floats { private Floats() {} /** * The number of bytes required to represent a primitive {@code float} * value. * * @since 10.0 */ public static final int BYTES = Float.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Float) value).hashCode()}. * * @param value a primitive {@code float} value * @return a hash code for the value */ public static int hashCode(float value) { // TODO(kevinb): is there a better way, that's still gwt-safe? return ((Float) value).hashCode(); } /** * Compares the two specified {@code float} values using {@link * Float#compare(float, float)}. You may prefer to invoke that method * directly; this method exists only for consistency with the other utilities * in this package. * * @param a the first {@code float} to compare * @param b the second {@code float} to compare * @return the result of invoking {@link Float#compare(float, float)} */ public static int compare(float a, float b) { return Float.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is * equivalent to, but not necessarily implemented as, * {@code !(Float.isInfinite(value) || Float.isNaN(value))}. * * @since 10.0 */ public static boolean isFinite(float value) { return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. Note that this always returns {@code false} when {@code * target} is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(float[] array, float target) { for (float value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(float[] array, float target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( float[] array, float target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains * {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(float[] array, float[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(float[] array, float target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( float[] array, float target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of * comparison as {@link Math#min(float, float)}. * * @param array a <i>nonempty</i> array of {@code float} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static float min(float... array) { checkArgument(array.length > 0); float min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules * of comparison as {@link Math#min(float, float)}. * * @param array a <i>nonempty</i> array of {@code float} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static float max(float... array) { checkArgument(array.length > 0); float max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new float[] {a, b}, new float[] {}, new * float[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code float} arrays * @return a single array containing all the values from the source arrays, in * order */ public static float[] concat(float[]... arrays) { int length = 0; for (float[] array : arrays) { length += array.length; } float[] result = new float[length]; int pos = 0; for (float[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static float[] ensureCapacity( float[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static float[] copyOf(float[] original, int length) { float[] copy = new float[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code float} values, converted * to strings as specified by {@link Float#toString(float)}, and separated by * {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)} * returns the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Float#toString(float)} formats {@code float} * differently in GWT. In the previous example, it returns the string {@code * "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code float} values, possibly empty */ public static String join(String separator, float... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code float} arrays * lexicographically. That is, it compares, using {@link * #compare(float, float)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] * < [2.0f]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(float[], float[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<float[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<float[]> { INSTANCE; @Override public int compare(float[] left, float[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Floats.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Float} instances into a new array of * primitive {@code float} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Float} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static float[] toArray(Collection<Float> collection) { if (collection instanceof FloatArrayAsList) { return ((FloatArrayAsList) collection).toFloatArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; float[] array = new float[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Float) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Float} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code * NaN}, or if {@code NaN} is used as a parameter to any of its methods. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Float> asList(float... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new FloatArrayAsList(backingArray); } @GwtCompatible private static class FloatArrayAsList extends AbstractList<Float> implements RandomAccess, Serializable { final float[] array; final int start; final int end; FloatArrayAsList(float[] array) { this(array, 0, array.length); } FloatArrayAsList(float[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Float get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Float) { int i = Floats.indexOf(array, (Float) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Float) { int i = Floats.lastIndexOf(array, (Float) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Float set(int index, Float element) { checkElementIndex(index, size()); float oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Float> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new FloatArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof FloatArrayAsList) { FloatArrayAsList that = (FloatArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Floats.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } float[] toFloatArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); float[] result = new float[size]; System.arraycopy(array, start, result, 0, size); return result; } 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.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; /** * Static utility methods pertaining to {@code byte} primitives that * interpret values as signed. The corresponding methods that treat the values * as unsigned are found in {@link UnsignedBytes}, and the methods for which * signedness is not an issue are in {@link Bytes}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ // TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT // javadoc? @GwtCompatible public final class SignedBytes { private SignedBytes() {} /** * The largest power of two that can be represented as a signed {@code byte}. * * @since 10.0 */ public static final byte MAX_POWER_OF_TWO = 1 << 6; /** * Returns the {@code byte} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code byte} type * @return the {@code byte} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE} */ public static byte checkedCast(long value) { byte result = (byte) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code byte} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code byte} if it is in the range of the * {@code byte} type, {@link Byte#MAX_VALUE} if it is too large, * or {@link Byte#MIN_VALUE} if it is too small */ public static byte saturatedCast(long value) { if (value > Byte.MAX_VALUE) { return Byte.MAX_VALUE; } if (value < Byte.MIN_VALUE) { return Byte.MIN_VALUE; } return (byte) value; } /** * Compares the two specified {@code byte} values. The sign of the value * returned is the same as that of {@code ((Byte) a).compareTo(b)}. * * @param a the first {@code byte} to compare * @param b the second {@code byte} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(byte a, byte b) { return a - b; // safe due to restricted range } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte min(byte... array) { checkArgument(array.length > 0); byte min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte max(byte... array) { checkArgument(array.length > 0); byte max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns a string containing the supplied {@code byte} values separated * by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)} * returns the string {@code "1:2:-1"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code byte} values, possibly empty */ public static String join(String separator, byte... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code byte} arrays * lexicographically. That is, it compares, using {@link * #compare(byte, byte)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] < * [0x01, 0x7F] < [0x02]}. Values are treated as signed. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<byte[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<byte[]> { INSTANCE; @Override public int compare(byte[] left, byte[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = SignedBytes.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } }
Java