code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.testing.features;
import com.google.common.annotations.GwtCompatible;
import java.util.Set;
/**
* Thrown when requirements on a tester method or class conflict with
* each other.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public class ConflictingRequirementsException extends Exception {
private Set<Feature<?>> conflicts;
private Object source;
public ConflictingRequirementsException(
String message, Set<Feature<?>> conflicts, Object source) {
super(message);
this.conflicts = conflicts;
this.source = source;
}
public Set<Feature<?>> getConflicts() {
return conflicts;
}
public Object getSource() {
return source;
}
@Override public String getMessage() {
return super.getMessage() + " (source: " + source + ")";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.annotations.GwtCompatible;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this to meta-annotate XxxFeature.Require annotations, so that those
* annotations can be used to decide whether to apply a test to a given
* class-under-test.
* <br>
* This is needed because annotations can't implement interfaces, which is also
* why reflection is used to extract values from the properties of the various
* annotations.
*
* <p>This class is GWT compatible.
*
* @see CollectionFeature.Require
*
* @author George van den Driessche
*/
@Target(value = {java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@GwtCompatible
public @interface TesterAnnotation {
}
| 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.testing.features;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
/**
* When describing the features of the collection produced by a given generator
* (i.e. in a call to {@link
* com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder#withFeatures(Feature...)}),
* this annotation specifies each of the different sizes for which a test suite
* should be built. (In a typical case, the features should include {@link
* CollectionSize#ANY}.) These semantics are thus a little different
* from those of other Collection-related features such as {@link
* CollectionFeature} or {@link SetFeature}.
* <p>
* However, when {@link CollectionSize.Require} is used to annotate a test it
* behaves normally (i.e. it requires the collection instance under test to be
* a certain size for the test to run). Note that this means a test should not
* require more than one CollectionSize, since a particular collection instance
* can only be one size at once.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
@GwtCompatible
public enum CollectionSize implements Feature<Collection>,
Comparable<CollectionSize> {
/** Test an empty collection. */
ZERO(0),
/** Test a one-element collection. */
ONE(1),
/** Test a three-element collection. */
SEVERAL(3),
/*
* TODO: add VERY_LARGE, noting that we currently assume that the fourth
* sample element is not in any collection
*/
ANY(
ZERO,
ONE,
SEVERAL
);
private final Set<Feature<? super Collection>> implied;
private final Integer numElements;
CollectionSize(int numElements) {
this.implied = Collections.emptySet();
this.numElements = numElements;
}
CollectionSize(Feature<? super Collection> ... implied) {
// Keep the order here, so that PerCollectionSizeTestSuiteBuilder
// gives a predictable order of test suites.
this.implied = Helpers.copyToSet(implied);
this.numElements = null;
}
@Override
public Set<Feature<? super Collection>> getImpliedFeatures() {
return implied;
}
public int getNumElements() {
if (numElements == null) {
throw new IllegalStateException(
"A compound CollectionSize doesn't specify a number of elements.");
}
return numElements;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
CollectionSize[] value() default {};
CollectionSize[] absent() default {};
}
}
| 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.testing;
import static com.google.common.collect.testing.Helpers.orderEntriesByKey;
import com.google.common.annotations.GwtCompatible;
import java.util.List;
import java.util.Map.Entry;
/**
* Implementation helper for {@link TestMapGenerator} for use with sorted maps of strings.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@GwtCompatible
public abstract class TestStringSortedMapGenerator extends TestStringMapGenerator {
@Override
public Iterable<Entry<String, String>> order(List<Entry<String, String>> insertionOrder) {
return orderEntriesByKey(insertionOrder);
}
}
| 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.testing;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements.Strings;
import java.util.List;
import java.util.Set;
/**
* Create string sets for collection tests.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public abstract class TestStringSetGenerator implements TestSetGenerator<String>
{
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Set<String> create(Object... elements) {
String[] array = new String[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (String) e;
}
return create(array);
}
protected abstract Set<String> create(String[] elements);
@Override
public String[] createArray(int length) {
return new String[length];
}
/**
* {@inheritDoc}
*
* <p>By default, returns the supplied elements in their given order; however,
* generators for containers with a known order other than insertion order
* must override this method.
*
* <p>Note: This default implementation is overkill (but valid) for an
* unordered container. An equally valid implementation for an unordered
* container is to throw an exception. The chosen implementation, however, has
* the advantage of working for insertion-ordered containers, as well.
*/
@Override
public List<String> order(List<String> insertionOrder) {
return insertionOrder;
}
}
| 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.testing;
import com.google.common.annotations.GwtCompatible;
/**
* A non-empty tester for {@link java.util.Iterator}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public final class ExampleIteratorTester<E>
extends AbstractTester<TestIteratorGenerator<E>> {
public void testSomethingAboutIterators() {
assertTrue(true);
}
}
| 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.testing;
import static com.google.common.collect.testing.Helpers.castOrCopyToList;
import static com.google.common.collect.testing.Helpers.equal;
import static com.google.common.collect.testing.Helpers.mapEntry;
import static java.util.Collections.sort;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.DerivedCollectionGenerators.SortedMapSubmapTestMapGenerator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
/**
* Derived suite generators, split out of the suite builders so that they are available to GWT.
*
* @author George van den Driessche
*/
@GwtCompatible
public final class DerivedCollectionGenerators {
public static class MapEntrySetGenerator<K, V>
implements TestSetGenerator<Map.Entry<K, V>>, DerivedGenerator {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
public MapEntrySetGenerator(
OneSizeTestContainerGenerator<
Map<K, V>, Map.Entry<K, V>> mapGenerator) {
this.mapGenerator = mapGenerator;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return mapGenerator.samples();
}
@Override
public Set<Map.Entry<K, V>> create(Object... elements) {
return mapGenerator.create(elements).entrySet();
}
@Override
public Map.Entry<K, V>[] createArray(int length) {
return mapGenerator.createArray(length);
}
@Override
public Iterable<Map.Entry<K, V>> order(
List<Map.Entry<K, V>> insertionOrder) {
return mapGenerator.order(insertionOrder);
}
public OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> getInnerGenerator() {
return mapGenerator;
}
}
// TODO: investigate some API changes to SampleElements that would tidy up
// parts of the following classes.
public static class MapKeySetGenerator<K, V>
implements TestSetGenerator<K>, DerivedGenerator {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
private final SampleElements<K> samples;
public MapKeySetGenerator(
OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator) {
this.mapGenerator = mapGenerator;
final SampleElements<Map.Entry<K, V>> mapSamples =
this.mapGenerator.samples();
this.samples = new SampleElements<K>(
mapSamples.e0.getKey(),
mapSamples.e1.getKey(),
mapSamples.e2.getKey(),
mapSamples.e3.getKey(),
mapSamples.e4.getKey());
}
@Override
public SampleElements<K> samples() {
return samples;
}
@Override
public Set<K> create(Object... elements) {
@SuppressWarnings("unchecked")
K[] keysArray = (K[]) elements;
// Start with a suitably shaped collection of entries
Collection<Map.Entry<K, V>> originalEntries =
mapGenerator.getSampleElements(elements.length);
// Create a copy of that, with the desired value for each key
Collection<Map.Entry<K, V>> entries =
new ArrayList<Entry<K, V>>(elements.length);
int i = 0;
for (Map.Entry<K, V> entry : originalEntries) {
entries.add(Helpers.mapEntry(keysArray[i++], entry.getValue()));
}
return mapGenerator.create(entries.toArray()).keySet();
}
@Override
public K[] createArray(int length) {
// TODO: with appropriate refactoring of OneSizeGenerator, we can perhaps
// tidy this up and get rid of the casts here and in
// MapValueCollectionGenerator.
return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@Override
public Iterable<K> order(List<K> insertionOrder) {
V v = ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()).samples().e0.getValue();
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (K element : insertionOrder) {
entries.add(mapEntry(element, v));
}
List<K> keys = new ArrayList<K>();
for (Entry<K, V> entry : mapGenerator.order(entries)) {
keys.add(entry.getKey());
}
return keys;
}
public OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> getInnerGenerator() {
return mapGenerator;
}
}
public static class MapValueCollectionGenerator<K, V>
implements TestCollectionGenerator<V>, DerivedGenerator {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
private final SampleElements<V> samples;
public MapValueCollectionGenerator(
OneSizeTestContainerGenerator<
Map<K, V>, Map.Entry<K, V>> mapGenerator) {
this.mapGenerator = mapGenerator;
final SampleElements<Map.Entry<K, V>> mapSamples =
this.mapGenerator.samples();
this.samples = new SampleElements<V>(
mapSamples.e0.getValue(),
mapSamples.e1.getValue(),
mapSamples.e2.getValue(),
mapSamples.e3.getValue(),
mapSamples.e4.getValue());
}
@Override
public SampleElements<V> samples() {
return samples;
}
@Override
public Collection<V> create(Object... elements) {
@SuppressWarnings("unchecked")
V[] valuesArray = (V[]) elements;
// Start with a suitably shaped collection of entries
Collection<Map.Entry<K, V>> originalEntries =
mapGenerator.getSampleElements(elements.length);
// Create a copy of that, with the desired value for each value
Collection<Map.Entry<K, V>> entries =
new ArrayList<Entry<K, V>>(elements.length);
int i = 0;
for (Map.Entry<K, V> entry : originalEntries) {
entries.add(Helpers.mapEntry(entry.getKey(), valuesArray[i++]));
}
return mapGenerator.create(entries.toArray()).values();
}
@Override
public V[] createArray(int length) {
//noinspection UnnecessaryLocalVariable
final V[] vs = ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createValueArray(length);
return vs;
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
final List<Entry<K, V>> orderedEntries =
castOrCopyToList(mapGenerator.order(castOrCopyToList(mapGenerator.getSampleElements(5))));
sort(insertionOrder, new Comparator<V>() {
@Override public int compare(V left, V right) {
// The indexes are small enough for the subtraction trick to be safe.
return indexOfEntryWithValue(left) - indexOfEntryWithValue(right);
}
int indexOfEntryWithValue(V value) {
for (int i = 0; i < orderedEntries.size(); i++) {
if (equal(orderedEntries.get(i).getValue(), value)) {
return i;
}
}
throw new IllegalArgumentException("Map.values generator can order only sample values");
}
});
return insertionOrder;
}
public OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> getInnerGenerator() {
return mapGenerator;
}
}
// TODO(cpovirk): could something like this be used elsewhere, e.g., ReserializedListGenerator?
static class ForwardingTestMapGenerator<K, V> implements TestMapGenerator<K, V> {
TestMapGenerator<K, V> delegate;
ForwardingTestMapGenerator(TestMapGenerator<K, V> delegate) {
this.delegate = delegate;
}
@Override
public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) {
return delegate.order(insertionOrder);
}
@Override
public K[] createKeyArray(int length) {
return delegate.createKeyArray(length);
}
@Override
public V[] createValueArray(int length) {
return delegate.createValueArray(length);
}
@Override
public SampleElements<Entry<K, V>> samples() {
return delegate.samples();
}
@Override
public Map<K, V> create(Object... elements) {
return delegate.create(elements);
}
@Override
public Entry<K, V>[] createArray(int length) {
return delegate.createArray(length);
}
}
/**
* Two bounds (from and to) define how to build a subMap.
*/
public enum Bound {
INCLUSIVE,
EXCLUSIVE,
NO_BOUND;
}
/*
* TODO(cpovirk): surely we can find a less ugly solution than a class that accepts 3 parameters,
* exposes as many getters, does work in the constructor, and has both a superclass and a subclass
*/
public static class SortedMapSubmapTestMapGenerator<K, V>
extends ForwardingTestMapGenerator<K, V> {
final Bound to;
final Bound from;
final K firstInclusive;
final K lastInclusive;
private final Comparator<Entry<K, V>> entryComparator;
public SortedMapSubmapTestMapGenerator(TestMapGenerator<K, V> delegate, Bound to, Bound from) {
super(delegate);
this.to = to;
this.from = from;
SortedMap<K, V> emptyMap = (SortedMap<K, V>) delegate.create();
this.entryComparator = Helpers.entryComparator(emptyMap.comparator());
// derive values for inclusive filtering from the input samples
SampleElements<Entry<K, V>> samples = delegate.samples();
@SuppressWarnings("unchecked") // no elements are inserted into the array
List<Entry<K, V>> samplesList = Arrays.asList(
samples.e0, samples.e1, samples.e2, samples.e3, samples.e4);
Collections.sort(samplesList, entryComparator);
this.firstInclusive = samplesList.get(0).getKey();
this.lastInclusive = samplesList.get(samplesList.size() - 1).getKey();
}
@Override public Map<K, V> create(Object... entries) {
@SuppressWarnings("unchecked") // we dangerously assume K and V are both strings
List<Entry<K, V>> extremeValues = (List) getExtremeValues();
@SuppressWarnings("unchecked") // map generators must past entry objects
List<Entry<K, V>> normalValues = (List) Arrays.asList(entries);
// prepare extreme values to be filtered out of view
Collections.sort(extremeValues, entryComparator);
K firstExclusive = extremeValues.get(1).getKey();
K lastExclusive = extremeValues.get(2).getKey();
if (from == Bound.NO_BOUND) {
extremeValues.remove(0);
extremeValues.remove(0);
}
if (to == Bound.NO_BOUND) {
extremeValues.remove(extremeValues.size() - 1);
extremeValues.remove(extremeValues.size() - 1);
}
// the regular values should be visible after filtering
List<Entry<K, V>> allEntries = new ArrayList<Entry<K, V>>();
allEntries.addAll(extremeValues);
allEntries.addAll(normalValues);
SortedMap<K, V> map = (SortedMap<K, V>)
delegate.create((Object[])
allEntries.toArray(new Entry[allEntries.size()]));
return createSubMap(map, firstExclusive, lastExclusive);
}
/**
* Calls the smallest subMap overload that filters out the extreme values. This method is
* overridden in NavigableMapTestSuiteBuilder.
*/
Map<K, V> createSubMap(SortedMap<K, V> map, K firstExclusive, K lastExclusive) {
if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) {
return map.headMap(lastExclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) {
return map.tailMap(firstInclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) {
return map.subMap(firstInclusive, lastExclusive);
} else {
throw new IllegalArgumentException();
}
}
public final Bound getTo() {
return to;
}
public final Bound getFrom() {
return from;
}
public final TestMapGenerator<K, V> getInnerGenerator() {
return delegate;
}
}
/**
* Returns an array of four bogus elements that will always be too high or
* too low for the display. This includes two values for each extreme.
*
* <p>This method (dangerously) assume that the strings {@code "!! a"} and
* {@code "~~ z"} will work for this purpose, which may cause problems for
* navigable maps with non-string or unicode generators.
*/
private static List<Entry<String, String>> getExtremeValues() {
List<Entry<String, String>> result = new ArrayList<Entry<String, String>>();
result.add(Helpers.mapEntry("!! a", "below view"));
result.add(Helpers.mapEntry("!! b", "below view"));
result.add(Helpers.mapEntry("~~ y", "above view"));
result.add(Helpers.mapEntry("~~ z", "above view"));
return result;
}
private DerivedCollectionGenerators() {}
}
| 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.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Concrete instantiation of {@link AbstractCollectionTestSuiteBuilder} for
* testing collections that do not have a more specific tester like
* {@link ListTestSuiteBuilder} or {@link SetTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Louis Wasserman
*/
public class CollectionTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<
CollectionTestSuiteBuilder<E>, E> {
public static <E> CollectionTestSuiteBuilder<E> using(
TestCollectionGenerator<E> generator) {
return new CollectionTestSuiteBuilder<E>().usingGenerator(generator);
}
@Override
protected
List<TestSuite>
createDerivedSuites(
FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<TestSuite>(
super.createDerivedSuites(parentBuilder));
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(CollectionTestSuiteBuilder
.using(new ReserializedCollectionGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedCollectionGenerator<E> implements TestCollectionGenerator<E> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedCollectionGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Collection<E> create(Object... elements) {
return SerializableTester.reserialize(gen.create(elements));
}
@Override
public E[] createArray(int length) {
return gen.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return gen.order(insertionOrder);
}
}
private static Set<Feature<?>> computeReserializedCollectionFeatures(Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
}
| 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.testing;
import static com.google.common.collect.testing.Helpers.orderEntriesByKey;
import com.google.common.annotations.GwtCompatible;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Implementation helper for {@link TestMapGenerator} for use with enum maps.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public abstract class TestEnumMapGenerator
implements TestMapGenerator<AnEnum, String> {
@Override
public SampleElements<Entry<AnEnum, String>> samples() {
return new SampleElements<Entry<AnEnum, String>>(
Helpers.mapEntry(AnEnum.A, "January"),
Helpers.mapEntry(AnEnum.B, "February"),
Helpers.mapEntry(AnEnum.C, "March"),
Helpers.mapEntry(AnEnum.D, "April"),
Helpers.mapEntry(AnEnum.E, "May")
);
}
@Override
public final Map<AnEnum, String> create(Object... entries) {
@SuppressWarnings("unchecked")
Entry<AnEnum, String>[] array = new Entry[entries.length];
int i = 0;
for (Object o : entries) {
@SuppressWarnings("unchecked")
Entry<AnEnum, String> e = (Entry<AnEnum, String>) o;
array[i++] = e;
}
return create(array);
}
protected abstract Map<AnEnum, String> create(
Entry<AnEnum, String>[] entries);
@Override
@SuppressWarnings("unchecked")
public final Entry<AnEnum, String>[] createArray(int length) {
return new Entry[length];
}
@Override
public final AnEnum[] createKeyArray(int length) {
return new AnEnum[length];
}
@Override
public final String[] createValueArray(int length) {
return new String[length];
}
/** Returns the elements sorted in natural order. */
@Override
public Iterable<Entry<AnEnum, String>> order(
List<Entry<AnEnum, String>> insertionOrder) {
return orderEntriesByKey(insertionOrder);
}
}
| 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.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.CollectionSerializationEqualTester;
import com.google.common.collect.testing.testers.ListAddAllAtIndexTester;
import com.google.common.collect.testing.testers.ListAddAllTester;
import com.google.common.collect.testing.testers.ListAddAtIndexTester;
import com.google.common.collect.testing.testers.ListAddTester;
import com.google.common.collect.testing.testers.ListCreationTester;
import com.google.common.collect.testing.testers.ListEqualsTester;
import com.google.common.collect.testing.testers.ListGetTester;
import com.google.common.collect.testing.testers.ListHashCodeTester;
import com.google.common.collect.testing.testers.ListIndexOfTester;
import com.google.common.collect.testing.testers.ListLastIndexOfTester;
import com.google.common.collect.testing.testers.ListListIteratorTester;
import com.google.common.collect.testing.testers.ListRemoveAllTester;
import com.google.common.collect.testing.testers.ListRemoveAtIndexTester;
import com.google.common.collect.testing.testers.ListRemoveTester;
import com.google.common.collect.testing.testers.ListRetainAllTester;
import com.google.common.collect.testing.testers.ListSetTester;
import com.google.common.collect.testing.testers.ListSubListTester;
import com.google.common.collect.testing.testers.ListToArrayTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a List implementation.
*
* @author George van den Driessche
*/
public final class ListTestSuiteBuilder<E> extends
AbstractCollectionTestSuiteBuilder<ListTestSuiteBuilder<E>, E> {
public static <E> ListTestSuiteBuilder<E> using(
TestListGenerator<E> generator) {
return new ListTestSuiteBuilder<E>().usingGenerator(generator);
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers
= Helpers.copyToList(super.getTesters());
testers.add(CollectionSerializationEqualTester.class);
testers.add(ListAddAllAtIndexTester.class);
testers.add(ListAddAllTester.class);
testers.add(ListAddAtIndexTester.class);
testers.add(ListAddTester.class);
testers.add(ListCreationTester.class);
testers.add(ListEqualsTester.class);
testers.add(ListGetTester.class);
testers.add(ListHashCodeTester.class);
testers.add(ListIndexOfTester.class);
testers.add(ListLastIndexOfTester.class);
testers.add(ListListIteratorTester.class);
testers.add(ListRemoveAllTester.class);
testers.add(ListRemoveAtIndexTester.class);
testers.add(ListRemoveTester.class);
testers.add(ListRetainAllTester.class);
testers.add(ListSetTester.class);
testers.add(ListSubListTester.class);
testers.add(ListToArrayTester.class);
return testers;
}
/**
* Specifies {@link CollectionFeature#KNOWN_ORDER} for all list tests, since
* lists have an iteration ordering corresponding to the insertion order.
*/
@Override public TestSuite createTestSuite() {
if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) {
List<Feature<?>> features = Helpers.copyToList(getFeatures());
features.add(CollectionFeature.KNOWN_ORDER);
withFeatures(features);
}
return super.createTestSuite();
}
@Override
protected
List<TestSuite>
createDerivedSuites(
FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<TestSuite>(
super.createDerivedSuites(parentBuilder));
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(ListTestSuiteBuilder
.using(new ReserializedListGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedListGenerator<E> implements TestListGenerator<E>{
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedListGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public List<E> create(Object... elements) {
return (List<E>) SerializableTester.reserialize(gen.create(elements));
}
@Override
public E[] createArray(int length) {
return gen.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return gen.order(insertionOrder);
}
}
private static Set<Feature<?>> computeReserializedCollectionFeatures(
Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
}
| 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.testing;
import com.google.common.collect.testing.testers.QueueElementTester;
import com.google.common.collect.testing.testers.QueueOfferTester;
import com.google.common.collect.testing.testers.QueuePeekTester;
import com.google.common.collect.testing.testers.QueuePollTester;
import com.google.common.collect.testing.testers.QueueRemoveTester;
import java.util.ArrayList;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a queue implementation.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public final class QueueTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<QueueTestSuiteBuilder<E>, E> {
public static <E> QueueTestSuiteBuilder<E> using(
TestQueueGenerator<E> generator) {
return new QueueTestSuiteBuilder<E>().usingGenerator(generator);
}
private boolean runCollectionTests = true;
/**
* Specify whether to skip the general collection tests. Call this method when
* testing a collection that's both a queue and a list, to avoid running the
* common collection tests twice. By default, collection tests do run.
*/
public QueueTestSuiteBuilder<E> skipCollectionTests() {
runCollectionTests = false;
return this;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
new ArrayList<Class<? extends AbstractTester>>();
if (runCollectionTests) {
testers.addAll(super.getTesters());
}
testers.add(QueueElementTester.class);
testers.add(QueueOfferTester.class);
testers.add(QueuePeekTester.class);
testers.add(QueuePollTester.class);
testers.add(QueueRemoveTester.class);
return testers;
}
}
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in
* {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code long} values, see {@link com.google.common.primitives.Longs}.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class LongMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Long.bitCount(x) == 1}, because
* {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
*/
public static boolean isPowerOfTwo(long x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(long x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Long.SIZE - Long.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Long.numberOfLeadingZeros(x);
long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Long.SIZE - 1) - leadingZeros;
return (x <= cmp) ? logFloor : logFloor + 1;
default:
throw new AssertionError("impossible");
}
}
/** The biggest half power of two that fits into an unsigned long */
@VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;
// MAX_LOG10_FOR_LEADING_ZEROS[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] MAX_LOG10_FOR_LEADING_ZEROS = {
19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12,
12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4,
3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 };
// HALF_POWERS_OF_10[i] = largest long less than 10^(i + 0.5)
static final long[] FACTORIALS = {
1L,
1L,
1L * 2,
1L * 2 * 3,
1L * 2 * 3 * 4,
1L * 2 * 3 * 4 * 5,
1L * 2 * 3 * 4 * 5 * 6,
1L * 2 * 3 * 4 * 5 * 6 * 7,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static long binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k >= BIGGEST_BINOMIALS.length || n > BIGGEST_BINOMIALS[k]) {
return Long.MAX_VALUE;
}
long result = 1;
if (k < BIGGEST_SIMPLE_BINOMIALS.length && n <= BIGGEST_SIMPLE_BINOMIALS[k]) {
// guaranteed not to overflow
for (int i = 0; i < k; i++) {
result *= n - i;
result /= i + 1;
}
} else {
// We want to do this in long math for speed, but want to avoid overflow.
// Dividing by the GCD suffices to avoid overflow in all the remaining cases.
for (int i = 1; i <= k; i++, n--) {
int d = IntMath.gcd(n, i);
result /= i / d; // (i/d) is guaranteed to divide result
result *= n / d;
}
}
return result;
}
/*
* binomial(BIGGEST_BINOMIALS[k], k) fits in a long, but not
* binomial(BIGGEST_BINOMIALS[k] + 1, k).
*/
static final int[] BIGGEST_BINOMIALS =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
67, 67, 66, 66, 66, 66};
/*
* binomial(BIGGEST_SIMPLE_BINOMIALS[k], k) doesn't need to use the slower GCD-based impl,
* but binomial(BIGGEST_SIMPLE_BINOMIALS[k] + 1, k) does.
*/
@VisibleForTesting static final int[] BIGGEST_SIMPLE_BINOMIALS =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313,
684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62,
61, 61, 61};
// These values were generated by using checkedMultiply to see when the simple multiply/divide
// algorithm would lead to an overflow.
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded toward
* negative infinity. This method is resilient to overflow.
*
* @since 14.0
*/
public static long mean(long x, long y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private LongMath() {}
}
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_EVEN;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* A class for arithmetic on values of type {@code BigInteger}.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@code long} can be found in
* {@link IntMath} and {@link LongMath} respectively.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class BigIntegerMath {
/**
* Returns {@code true} if {@code x} represents a power of two.
*/
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(
SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/*
* The maximum number of bits in a square root for which we'll precompute an explicit half power
* of two. This can be any value, but higher values incur more class load time and linearly
* increasing memory consumption.
*/
@VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256;
@VisibleForTesting static final BigInteger SQRT2_PRECOMPUTED_BITS =
new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16);
private static final double LN_10 = Math.log(10);
private static final double LN_2 = Math.log(2);
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, or {@code 1} if {@code n == 0}.
*
* <p><b>Warning</b>: the result takes <i>O(n log n)</i> space, so use cautiously.
*
* <p>This uses an efficient binary recursive algorithm to compute the factorial
* with balanced multiplies. It also removes all the 2s from the intermediate
* products (shifting them back in at the end).
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static BigInteger factorial(int n) {
checkNonNegative("n", n);
// If the factorial is small enough, just use LongMath to do it.
if (n < LongMath.FACTORIALS.length) {
return BigInteger.valueOf(LongMath.FACTORIALS[n]);
}
// Pre-allocate space for our list of intermediate BigIntegers.
int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING);
ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize);
// Start from the pre-computed maximum long factorial.
int startingNumber = LongMath.FACTORIALS.length;
long product = LongMath.FACTORIALS[startingNumber - 1];
// Strip off 2s from this value.
int shift = Long.numberOfTrailingZeros(product);
product >>= shift;
// Use floor(log2(num)) + 1 to prevent overflow of multiplication.
int productBits = LongMath.log2(product, FLOOR) + 1;
int bits = LongMath.log2(startingNumber, FLOOR) + 1;
// Check for the next power of two boundary, to save us a CLZ operation.
int nextPowerOfTwo = 1 << (bits - 1);
// Iteratively multiply the longs as big as they can go.
for (long num = startingNumber; num <= n; num++) {
// Check to see if the floor(log2(num)) + 1 has changed.
if ((num & nextPowerOfTwo) != 0) {
nextPowerOfTwo <<= 1;
bits++;
}
// Get rid of the 2s in num.
int tz = Long.numberOfTrailingZeros(num);
long normalizedNum = num >> tz;
shift += tz;
// Adjust floor(log2(num)) + 1.
int normalizedBits = bits - tz;
// If it won't fit in a long, then we store off the intermediate product.
if (normalizedBits + productBits >= Long.SIZE) {
bignums.add(BigInteger.valueOf(product));
product = 1;
productBits = 0;
}
product *= normalizedNum;
productBits = LongMath.log2(product, FLOOR) + 1;
}
// Check for leftovers.
if (product > 1) {
bignums.add(BigInteger.valueOf(product));
}
// Efficiently multiply all the intermediate products together.
return listProduct(bignums).shiftLeft(shift);
}
static BigInteger listProduct(List<BigInteger> nums) {
return listProduct(nums, 0, nums.size());
}
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
switch (end - start) {
case 0:
return BigInteger.ONE;
case 1:
return nums.get(start);
case 2:
return nums.get(start).multiply(nums.get(start + 1));
case 3:
return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
default:
// Otherwise, split the list in half and recursively do this.
int m = (end + start) >>> 1;
return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
}
}
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, that is, {@code n! / (k! (n - k)!)}.
*
* <p><b>Warning</b>: the result can take as much as <i>O(k log n)</i> space.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static BigInteger binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k < LongMath.BIGGEST_BINOMIALS.length && n <= LongMath.BIGGEST_BINOMIALS[k]) {
return BigInteger.valueOf(LongMath.binomial(n, k));
}
BigInteger accum = BigInteger.ONE;
long numeratorAccum = n;
long denominatorAccum = 1;
int bits = LongMath.log2(n, RoundingMode.CEILING);
int numeratorBits = bits;
for (int i = 1; i < k; i++) {
int p = n - i;
int q = i + 1;
// log2(p) >= bits - 1, because p >= n/2
if (numeratorBits + bits >= Long.SIZE - 1) {
// The numerator is as big as it can get without risking overflow.
// Multiply numeratorAccum / denominatorAccum into accum.
accum = accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
numeratorAccum = p;
denominatorAccum = q;
numeratorBits = bits;
} else {
// We can definitely multiply into the long accumulators without overflowing them.
numeratorAccum *= p;
denominatorAccum *= q;
numeratorBits += bits;
}
}
return accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
private BigIntegerMath() {}
}
| 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.math;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in
* {@link LongMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code int} values, see {@link com.google.common.primitives.Ints}.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class IntMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Integer.bitCount(x) == 1}, because
* {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power
* of two.
*/
public static boolean isPowerOfTwo(int x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(int x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Integer.numberOfLeadingZeros(x);
int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Integer.SIZE - 1) - leadingZeros;
return (x <= cmp) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/** The biggest half power of two that can fit in an unsigned int. */
@VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
private static int log10Floor(int x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
* we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x))
* is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = MAX_LOG10_FOR_LEADING_ZEROS[Integer.numberOfLeadingZeros(x)];
// y is the higher of the two possible values of floor(log10(x))
int sgn = (x - POWERS_OF_10[y]) >>> (Integer.SIZE - 1);
/*
* sgn is the sign bit of x - 10^y; it is 1 if x < 10^y, and 0 otherwise. If x < 10^y, then we
* want the lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - sgn;
}
// MAX_LOG10_FOR_LEADING_ZEROS[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] MAX_LOG10_FOR_LEADING_ZEROS = {9, 9, 9, 8, 8, 8,
7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0};
@VisibleForTesting static final int[] POWERS_OF_10 = {1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000};
// HALF_POWERS_OF_10[i] = largest int less than 10^(i + 0.5)
@VisibleForTesting static final int[] HALF_POWERS_OF_10 =
{3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE};
private static int sqrtFloor(int x) {
// There is no loss of precision in converting an int to a double, according to
// http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
return (int) Math.sqrt(x);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@SuppressWarnings("fallthrough")
public static int divide(int p, int q, RoundingMode mode) {
checkNotNull(mode);
if (q == 0) {
throw new ArithmeticException("/ by zero"); // for GWT
}
int div = p / q;
int rem = p - q * div; // equal to p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
int absRem = abs(rem);
int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative ints can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:<pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
public static int mod(int x, int m) {
if (m <= 0) {
throw new ArithmeticException("Modulus " + m + " must be > 0");
}
int result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static int gcd(int a, int b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31
* isn't an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >40% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Integer.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Integer.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
int delta = a - b; // can't overflow, since a and b are nonnegative
int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
*/
public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
*/
public static int checkedSubtract(int a, int b) {
long result = (long) a - b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
*/
public static int checkedMultiply(int a, int b) {
long result = (long) a * b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* <p>{@link #pow} may be faster, but does not check for overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
* {@code int} arithmetic
*/
public static int checkedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Integer.SIZE - 1);
return 1 << k;
case (-2):
checkNoOverflow(k < Integer.SIZE);
return ((k & 1) == 0) ? 1 << k : -1 << k;
}
int accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT);
b *= b;
}
}
}
}
@VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the
* result does not fit in a {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static int factorial(int n) {
checkNonNegative("n", n);
return (n < FACTORIALS.length) ? FACTORIALS[n] : Integer.MAX_VALUE;
}
static final int[] FACTORIALS = {
1,
1,
1 * 2,
1 * 2 * 3,
1 * 2 * 3 * 4,
1 * 2 * 3 * 4 * 5,
1 * 2 * 3 * 4 * 5 * 6,
1 * 2 * 3 * 4 * 5 * 6 * 7,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12};
// binomial(BIGGEST_BINOMIALS[k], k) fits in an int, but not binomial(BIGGEST_BINOMIALS[k]+1,k).
@VisibleForTesting static int[] BIGGEST_BINOMIALS = {
Integer.MAX_VALUE,
Integer.MAX_VALUE,
65536,
2345,
477,
193,
110,
75,
58,
49,
43,
39,
37,
35,
34,
34,
33
};
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded towards
* negative infinity. This method is overflow resilient.
*
* @since 14.0
*/
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private IntMath() {}
}
| 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.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(emulated = true)
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;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code float} value in the manner of {@link Number#floatValue}.
*
* <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 Number} instances
* @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
* @since 1.0 (parameter was {@code Collection<Float>} before 12.0)
*/
public static float[] toArray(Collection<? extends Number> 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] = ((Number) checkNotNull(boxedArray[i])).floatValue();
}
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];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
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() is not available under GWT
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) 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 java.io.Serializable;
import java.util.AbstractList;
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 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 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;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code int} value in the manner of {@link Number#intValue}.
*
* <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 Number} instances
* @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
* @since 1.0 (parameter was {@code Collection<Integer>} before 12.0)
*/
public static int[] toArray(Collection<? extends Number> 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] = ((Number) checkNotNull(boxedArray[i])).intValue();
}
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];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
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() is not available under GWT
int size = size();
int[] result = new int[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 java.io.Serializable;
import java.util.AbstractList;
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 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];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
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() is not available under GWT
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) 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.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(emulated = true)
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;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code double} value in the manner of {@link Number#doubleValue}.
*
* <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 Number} instances
* @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
* @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
*/
public static double[] toArray(Collection<? extends Number> 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] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
}
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];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
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() is not available under GWT
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) 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 java.io.Serializable;
import java.util.AbstractList;
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 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;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code short} value in the manner of {@link Number#shortValue}.
*
* <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 Number} instances
* @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
* @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
*/
public static short[] toArray(Collection<? extends Number> 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] = ((Number) checkNotNull(boxedArray[i])).shortValue();
}
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];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
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() is not available under GWT
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.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) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.FastMatcher;
/**
* An immutable version of CharMatcher for medium-sized sets of characters that uses a hash table
* with linear probing to check for matches.
*
* @author Christopher Swenson
*/
@GwtCompatible(emulated = true)
final class MediumCharMatcher extends FastMatcher {
static final int MAX_SIZE = 1023;
private final char[] table;
private final boolean containsZero;
private final long filter;
private MediumCharMatcher(char[] table, long filter, boolean containsZero,
String description) {
super(description);
this.table = table;
this.filter = filter;
this.containsZero = containsZero;
}
private boolean checkFilter(int c) {
return 1 == (1 & (filter >> c));
}
// This is all essentially copied from ImmutableSet, but we have to duplicate because
// of dependencies.
// Represents how tightly we can pack things, as a maximum.
private static final double DESIRED_LOAD_FACTOR = 0.5;
/**
* Returns an array size suitable for the backing array of a hash table that
* uses open addressing with linear probing in its implementation. The
* returned size is the smallest power of two that can hold setSize elements
* with the desired load factor.
*/
@VisibleForTesting static int chooseTableSize(int setSize) {
if (setSize == 1) {
return 2;
}
// Correct the size for open addressing to match desired load factor.
// Round up to the next highest power of 2.
int tableSize = Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize <<= 1;
}
return tableSize;
}
@Override
public boolean matches(char c) {
if (c == 0) {
return containsZero;
}
if (!checkFilter(c)) {
return false;
}
int mask = table.length - 1;
int startingIndex = c & mask;
int index = startingIndex;
do {
// Check for empty.
if (table[index] == 0) {
return false;
// Check for match.
} else if (table[index] == c) {
return true;
} else {
// Linear probing.
index = (index + 1) & mask;
}
// Check to see if we wrapped around the whole table.
} while (index != startingIndex);
return false;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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.Arrays;
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(emulated = true)
public abstract class CharMatcher implements Predicate<Character> {
// Constants
/**
* 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("\t\n\013\f\r \u0085\u1680\u2028\u2029\u205f\u3000")
.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', "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("CharMatcher.JAVA_DIGIT") {
@Override public boolean matches(char c) {
return Character.isDigit(c);
}
};
/**
* 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("CharMatcher.JAVA_LETTER") {
@Override public boolean matches(char c) {
return Character.isLetter(c);
}
};
/**
* 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("CharMatcher.JAVA_LETTER_OR_DIGIT") {
@Override public boolean matches(char c) {
return Character.isLetterOrDigit(c);
}
};
/**
* 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("CharMatcher.JAVA_UPPER_CASE") {
@Override public boolean matches(char c) {
return Character.isUpperCase(c);
}
};
/**
* 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("CharMatcher.JAVA_LOWER_CASE") {
@Override public boolean matches(char c) {
return Character.isLowerCase(c);
}
};
/**
* 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', '\u0604'))
.or(anyOf("\u06dd\u070f\u1680\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 FastMatcher("CharMatcher.ANY") {
@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;
}
};
/** Matches no characters. */
public static final CharMatcher NONE =
new FastMatcher("CharMatcher.NONE") {
@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;
}
};
// Static factories
/**
* Returns a {@code char} matcher that matches only one specified character.
*/
public static CharMatcher is(final char match) {
String description = "CharMatcher.is(" + Integer.toHexString(match) + ")";
return new FastMatcher(description) {
@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);
}
};
}
/**
* 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) {
String description = "CharMatcher.isNot(" + Integer.toHexString(match) + ")";
return new FastMatcher(description) {
@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);
}
};
}
/**
* 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:
return isEither(sequence.charAt(0), sequence.charAt(1));
}
// TODO(user): is it potentially worth just going ahead and building a precomputed matcher?
final char[] chars = sequence.toString().toCharArray();
Arrays.sort(chars);
String description = "CharMatcher.anyOf(\"" + String.valueOf(chars) + "\")";
return new CharMatcher(description) {
@Override public boolean matches(char c) {
return Arrays.binarySearch(chars, c) >= 0;
}
};
}
private static CharMatcher isEither(
final char match1,
final char match2) {
String description = "CharMatcher.anyOf(\"" + match1 + match2 + "\")";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c == match1 || c == match2;
}
};
}
/**
* 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);
String description = "CharMatcher.inRange(" +
Integer.toHexString(startInclusive) + ", " +
Integer.toHexString(endInclusive) + ")";
return inRange(startInclusive, endInclusive, description);
}
static CharMatcher inRange(final char startInclusive, final char endInclusive,
String description) {
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return startInclusive <= c && c <= endInclusive;
}
};
}
/**
* 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;
}
String description = "CharMatcher.forPredicate(" + predicate + ")";
return new CharMatcher(description) {
@Override public boolean matches(char c) {
return predicate.apply(c);
}
@Override public boolean apply(Character character) {
return predicate.apply(checkNotNull(character));
}
};
}
// State
final String description;
// Constructors
/**
* Sets the {@code toString()} from the given description.
*/
CharMatcher(String description) {
this.description = description;
}
/**
* Constructor for use by subclasses. When subclassing, you may want to override
* {@code toString()} to provide a useful description.
*/
protected CharMatcher() {
description = "UnknownCharMatcher";
}
// 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() {
return new NegatedMatcher(this);
}
private static class NegatedMatcher extends CharMatcher {
final CharMatcher original;
NegatedMatcher(String toString, CharMatcher original) {
super(toString);
this.original = original;
}
NegatedMatcher(CharMatcher original) {
this(original + ".negate()", original);
}
@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
CharMatcher withToString(String description) {
return new NegatedMatcher(description, original);
}
}
/**
* Returns a matcher that matches any character matched by both this matcher and {@code other}.
*/
public CharMatcher and(CharMatcher other) {
return new And(this, checkNotNull(other));
}
private static class And extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
And(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.and(" + a + ", " + b + ")");
}
And(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
}
@Override
public boolean matches(char c) {
return first.matches(c) && second.matches(c);
}
@Override
CharMatcher withToString(String description) {
return new And(first, second, description);
}
}
/**
* Returns a matcher that matches any character matched by either this matcher or {@code other}.
*/
public CharMatcher or(CharMatcher other) {
return new Or(this, checkNotNull(other));
}
private static class Or extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
Or(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
}
Or(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.or(" + a + ", " + b + ")");
}
@Override
public boolean matches(char c) {
return first.matches(c) || second.matches(c);
}
@Override
CharMatcher withToString(String description) {
return new Or(first, second, description);
}
}
/**
* 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);
}
/**
* Subclasses should provide a new CharMatcher with the same characteristics as {@code this},
* but with their {@code toString} method overridden with the new description.
*
* <p>This is unsupported by default.
*/
CharMatcher withToString(String description) {
throw new UnsupportedOperationException();
}
private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1;
/**
* A matcher for which precomputation will not yield any significant benefit.
*/
abstract static class FastMatcher extends CharMatcher {
FastMatcher() {
super();
}
FastMatcher(String description) {
super(description);
}
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
public CharMatcher negate() {
return new NegatedFastMatcher(this);
}
}
static final class NegatedFastMatcher extends NegatedMatcher {
NegatedFastMatcher(CharMatcher original) {
super(original);
}
NegatedFastMatcher(String toString, CharMatcher original) {
super(toString, original);
}
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
CharMatcher withToString(String description) {
return new NegatedFastMatcher(description, original);
}
}
// 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;
}
/**
* 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 (matches(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 (matches(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 description;
}
/**
* 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 = new FastMatcher("CharMatcher.WHITESPACE") {
/**
* A special-case CharMatcher for Unicode whitespace characters that is extremely
* efficient both in space required and in time to check for matches.
*
* Implementation details.
* It turns out that all current (early 2012) Unicode characters are unique modulo 79:
* so we can construct a lookup table of exactly 79 entries, and just check the character code
* mod 79, and see if that character is in the table.
*
* There is a 1 at the beginning of the table so that the null character is not listed
* as whitespace.
*
* Other things we tried that did not prove to be beneficial, mostly due to speed concerns:
*
* * Binary search into the sorted list of characters, i.e., what
* CharMatcher.anyOf() does</li>
* * Perfect hash function into a table of size 26 (using an offset table and a special
* Jenkins hash function)</li>
* * Perfect-ish hash function that required two lookups into a single table of size 26.</li>
* * Using a power-of-2 sized hash table (size 64) with linear probing.</li>
*
* --Christopher Swenson, February 2012.
*/
// Mod-79 lookup table.
private final char[] table = {1, 0, 160, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 0, 0,
8232, 8233, 0, 0, 0, 0, 0, 8239, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
12288, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 133, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199,
8200, 8201, 8202, 0, 0, 0, 0, 0, 8287, 5760, 0, 0, 6158, 0, 0, 0};
@Override public boolean matches(char c) {
return table[c % 79] == c;
}
};
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
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 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);
}
@Override public String toString() {
return Joiner.on(", ")
.appendTo(new StringBuilder().append('['), this)
.append(']')
.toString();
}
};
}
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() {
/*
* The returned string will be from the end of the last match to the
* beginning of the next one. nextStart is the start position of the
* returned substring, while offset is the place to start looking for a
* separator.
*/
int nextStart = offset;
while (offset != -1) {
int start = nextStart;
int end;
int separatorPosition = separatorStart(offset);
if (separatorPosition == -1) {
end = toSplit.length();
offset = -1;
} else {
end = separatorPosition;
offset = separatorEnd(separatorPosition);
}
if (offset == nextStart) {
/*
* This occurs when some pattern has an empty match, even if it
* doesn't match the empty string -- for example, if it requires
* lookahead or the like. The offset must be increased to look for
* separators beyond this point, without changing the start position
* of the next returned substring -- so nextStart stays the same.
*/
offset++;
if (offset >= toSplit.length()) {
offset = -1;
}
continue;
}
while (start < end && trimmer.matches(toSplit.charAt(start))) {
start++;
}
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
if (omitEmptyStrings && start == end) {
// Don't include the (unused) separator in next split string.
nextStart = offset;
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) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.FastMatcher;
/**
* An immutable small version of CharMatcher that uses an efficient hash table implementation, with
* non-power-of-2 sizing to try to use no reprobing, if possible.
*
* @author Christopher Swenson
*/
@GwtCompatible(emulated = true)
final class SmallCharMatcher extends FastMatcher {
static final int MAX_SIZE = 63;
static final int MAX_TABLE_SIZE = 128;
private final boolean reprobe;
private final char[] table;
private final boolean containsZero;
final long filter;
private SmallCharMatcher(char[] table, long filter, boolean containsZero,
boolean reprobe, String description) {
super(description);
this.table = table;
this.filter = filter;
this.containsZero = containsZero;
this.reprobe = reprobe;
}
private boolean checkFilter(int c) {
return 1 == (1 & (filter >> c));
}
@VisibleForTesting
static char[] buildTable(int modulus, char[] charArray, boolean reprobe) {
char[] table = new char[modulus];
for (char c : charArray) {
int index = c % modulus;
if (index < 0) {
index += modulus;
}
if ((table[index] != 0) && !reprobe) {
return null;
} else if (reprobe) {
while (table[index] != 0) {
index = (index + 1) % modulus;
}
}
table[index] = c;
}
return table;
}
static CharMatcher from(char[] chars, String description) {
int size = chars.length;
boolean containsZero = chars[0] == 0;
boolean reprobe = false;
// Compute the filter.
long filter = 0;
for (char c : chars) {
filter |= 1L << c;
}
char[] table = null;
for (int i = size; table == null && i < MAX_TABLE_SIZE; i++) {
table = buildTable(i, chars, false);
}
// Compute the hash table.
if (table == null) {
table = buildTable(MAX_TABLE_SIZE, chars, true);
reprobe = true;
}
return new SmallCharMatcher(table, filter, containsZero, reprobe, description);
}
@Override
public boolean matches(char c) {
if (c == 0) {
return containsZero;
}
if (!checkFilter(c)) {
return false;
}
int index = c % table.length;
if (index < 0) {
index += table.length;
}
while (true) {
// Check for empty.
if (table[index] == 0) {
return false;
} else if (table[index] == c) {
return true;
} else if (reprobe) {
// Linear probing will terminate eventually.
index = (index + 1) % table.length;
} else {
return false;
}
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.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 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);
}
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) 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.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
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 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);
}
// 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) {
// Avoid using the Iterator to avoid generating garbage (issue 820).
for (int i = 0; i < components.size(); i++) {
if (!components.get(i).apply(t)) {
return false;
}
}
return true;
}
@Override public int hashCode() {
// add a random number to 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) {
// Avoid using the Iterator to avoid generating garbage (issue 820).
for (int i = 0; i < components.size(); i++) {
if (components.get(i).apply(t)) {
return true;
}
}
return false;
}
@Override public int hashCode() {
// add a random number to 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#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;
}
@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) 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(emulated = true)
@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) 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 java.util.concurrent.TimeUnit;
/**
* @author Jesse Wilson
*/
class Platform {
private static final char[] CHAR_BUFFER = new char[1024];
static char[] charBufferFromThreadLocal() {
// ThreadLocal is not available to GWT, so we always reuse the same
// instance. It is always safe to return the same instance because
// javascript is single-threaded, and only used by blocks that doesn't
// involve async callbacks.
return CHAR_BUFFER;
}
static CharMatcher precomputeCharMatcher(CharMatcher matcher) {
// CharMatcher.precomputed() produces CharMatchers that are maybe a little
// faster (and that's debatable), but definitely more memory-hungry. We're
// choosing to turn .precomputed() into a no-op in GWT, because it doesn't
// seem to be a worthwhile tradeoff in a browser.
return matcher;
}
static long systemNanoTime() {
// System.nanoTime() is not available in GWT, so we get milliseconds
// and convert to nanos.
return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis());
}
}
| 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 java.nio.charset.Charset;
/**
* Contains constant definitions for the six standard {@link Charset} instances, which are
* guaranteed to be supported by all Java platform implementations.
*
* <p>Assuming you're free to choose, note that <b>{@link #UTF_8} is widely preferred</b>.
*
* <p>See the Guava User Guide article on <a
* href="http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets">
* {@code Charsets}</a>.
*
* @author Mike Bostock
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Charsets {
private Charsets() {}
/**
* UTF-8: eight-bit UCS Transformation Format.
*/
public static final Charset UTF_8 = Charset.forName("UTF-8");
/*
* 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) 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.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* Common superclass for {@link MultisetSetCountUnconditionallyTester} and
* {@link MultisetSetCountConditionallyTester}. It is used by those testers to
* test calls to the unconditional {@code setCount()} method and calls to the
* conditional {@code setCount()} method when the expected present count is
* correct.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public abstract class AbstractMultisetSetCountTester<E>
extends AbstractMultisetTester<E> {
/*
* TODO: consider adding MultisetFeatures.SUPPORTS_SET_COUNT. Currently we
* assume that using setCount() to increase the count is permitted iff add()
* is permitted and similarly for decrease/remove(). We assume that a
* setCount() no-op is permitted if either add() or remove() is permitted,
* though we also allow it to "succeed" if neither is permitted.
*/
private void assertSetCount(E element, int count) {
setCountCheckReturnValue(element, count);
assertEquals(
"multiset.count() should return the value passed to setCount()",
count, getMultiset().count(element));
int size = 0;
for (Multiset.Entry<E> entry : getMultiset().entrySet()) {
size += entry.getCount();
}
assertEquals(
"multiset.size() should be the sum of the counts of all entries",
size, getMultiset().size());
}
/**
* Call the {@code setCount()} method under test, and check its return value.
*/
abstract void setCountCheckReturnValue(E element, int count);
/**
* Call the {@code setCount()} method under test, but do not check its return
* value. Callers should use this method over
* {@link #setCountCheckReturnValue(Object, int)} when they expect
* {@code setCount()} to throw an exception, as checking the return value
* could produce an incorrect error message like
* "setCount() should return the original count" instead of the message passed
* to a later invocation of {@code fail()}, like "setCount should throw
* UnsupportedOperationException."
*/
abstract void setCountNoCheckReturnValue(E element, int count);
private void assertSetCountIncreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to increase an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
private void assertSetCountDecreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to decrease an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
// Unconditional setCount no-ops.
private void assertZeroToZero() {
assertSetCount(samples.e3, 0);
}
private void assertOneToOne() {
assertSetCount(samples.e0, 1);
}
private void assertThreeToThree() {
initThreeCopies();
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToZero_addSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_zeroToZero_removeSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_zeroToZero_unsupported() {
try {
assertZeroToZero();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToOne_addSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToOne_removeSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_oneToOne_unsupported() {
try {
assertOneToOne();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_threeToThree_addSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToThree_removeSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_threeToThree_unsupported() {
try {
assertThreeToThree();
} catch (UnsupportedOperationException tolerated) {
}
}
// Unconditional setCount size increases:
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToOne_supported() {
assertSetCount(samples.e3, 1);
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToThree_supported() {
assertSetCount(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToThree_supported() {
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToOne_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 1);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_oneToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
// Unconditional setCount size decreases:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToZero_supported() {
assertSetCount(samples.e0, 0);
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountOneToZeroConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToZero_supported() {
initThreeCopies();
assertSetCount(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToOne_supported() {
initThreeCopies();
assertSetCount(samples.e0, 1);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_oneToZero_unsupported() {
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToZero_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToOne_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 1);
}
// setCount with nulls:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testSetCount_removeNull_nullSupported() {
initCollectionWithNullElement();
assertSetCount(null, 0);
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testSetCount_addNull_nullSupported() {
assertSetCount(null, 1);
}
@CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES)
public void testSetCount_addNull_nullUnsupported() {
try {
setCountNoCheckReturnValue(null, 1);
fail("adding null with setCount() should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullSupported() {
try {
assertSetCount(null, 0);
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullUnsupported() {
try {
assertSetCount(null, 0);
} catch (NullPointerException tolerated) {
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_existingNoNopNull_nullSupported() {
initCollectionWithNullElement();
try {
assertSetCount(null, 1);
} catch (UnsupportedOperationException tolerated) {
}
}
// Negative count.
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_negative_removeSupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_negative_removeUnsupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException or UnsupportedOperationException");
} catch (IllegalArgumentException expected) {
} catch (UnsupportedOperationException expected) {
}
}
// TODO: test adding element of wrong type
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
import java.io.Serializable;
/**
* Tests for the {@code inverse} view of a BiMap.
*
* <p>This assumes that {@code bimap.inverse().inverse() == bimap}, which is not technically
* required but is fulfilled by all current implementations.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class BiMapInverseTester<K, V> extends AbstractBiMapTester<K, V> {
public void testInverseSame() {
assertSame(getMap(), getMap().inverse().inverse());
}
@CollectionFeature.Require(SERIALIZABLE)
public void testInverseSerialization() {
BiMapPair<K, V> pair = new BiMapPair<K, V>(getMap());
BiMapPair<K, V> copy = SerializableTester.reserialize(pair);
assertEquals(pair.forward, copy.forward);
assertEquals(pair.backward, copy.backward);
assertSame(copy.backward, copy.forward.inverse());
assertSame(copy.forward, copy.backward.inverse());
}
private static class BiMapPair<K, V> implements Serializable {
final BiMap<K, V> forward;
final BiMap<V, K> backward;
BiMapPair(BiMap<K, V> original) {
this.forward = original;
this.backward = original.inverse();
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collections;
import java.util.Iterator;
/**
* A generic JUnit test which tests multiset-specific write operations.
* Can't be invoked directly; please see {@link MultisetTestSuiteBuilder}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetWritesTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrencesZero() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().add(samples.e0, 0));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrences() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().add(samples.e0, 2));
assertEquals("old count", originalCount + 2, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddOccurrences_unsupported() {
try {
getMultiset().add(samples.e0, 2);
fail("unsupported multiset.add(E, int) didn't throw exception");
} catch (UnsupportedOperationException required) {}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAdd_occurrences_negative() {
try {
getMultiset().add(samples.e0, -1);
fail("multiset.add(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveZeroNoOp() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().remove(samples.e0, 0));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_present() {
assertEquals("multiset.remove(present, 2) didn't return the old count",
1, getMultiset().remove(samples.e0, 2));
assertFalse("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_absent() {
assertEquals("multiset.remove(absent, 0) didn't return 0",
0, getMultiset().remove(samples.e3, 2));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemove_occurrences_unsupported_absent() {
// notice: we don't care whether it succeeds, or fails with UOE
try {
assertEquals(
"multiset.remove(absent, 2) didn't return 0 or throw an exception",
0, getMultiset().remove(samples.e3, 2));
} catch (UnsupportedOperationException ok) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_0() {
int oldCount = getMultiset().count(samples.e0);
assertEquals("multiset.remove(E, 0) didn't return the old count",
oldCount, getMultiset().remove(samples.e0, 0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_negative() {
try {
getMultiset().remove(samples.e0, -1);
fail("multiset.remove(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_wrongType() {
assertEquals("multiset.remove(wrongType, 1) didn't return 0",
0, getMultiset().remove(WrongType.VALUE, 1));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_clear() {
getMultiset().entrySet().clear();
assertTrue("multiset not empty after entrySet().clear()",
getMultiset().isEmpty());
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_iterator() {
Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator();
assertTrue(
"non-empty multiset.entrySet() iterator.hasNext() returned false",
iterator.hasNext());
assertEquals("multiset.entrySet() iterator.next() returned incorrect entry",
Multisets.immutableEntry(samples.e0, 1), iterator.next());
assertFalse(
"size 1 multiset.entrySet() iterator.hasNext() returned true "
+ "after next()",
iterator.hasNext());
iterator.remove();
assertTrue(
"multiset isn't empty after multiset.entrySet() iterator.remove()",
getMultiset().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testEntrySet_iterator_remove_unsupported() {
Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator();
assertTrue(
"non-empty multiset.entrySet() iterator.hasNext() returned false",
iterator.hasNext());
try {
iterator.remove();
fail("multiset.entrySet() iterator.remove() didn't throw an exception");
} catch (UnsupportedOperationException expected) {}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_remove_present() {
assertTrue(
"multiset.entrySet.remove(presentEntry) returned false",
getMultiset().entrySet().remove(
Multisets.immutableEntry(samples.e0, 1)));
assertFalse(
"multiset contains element after removing its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_remove_missing() {
assertFalse(
"multiset.entrySet.remove(missingEntry) returned true",
getMultiset().entrySet().remove(
Multisets.immutableEntry(samples.e0, 2)));
assertTrue(
"multiset didn't contain element after removing a missing entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAll_present() {
assertTrue(
"multiset.entrySet.removeAll(presentEntry) returned false",
getMultiset().entrySet().removeAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 1))));
assertFalse(
"multiset contains element after removing its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAll_missing() {
assertFalse(
"multiset.entrySet.remove(missingEntry) returned true",
getMultiset().entrySet().removeAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 2))));
assertTrue(
"multiset didn't contain element after removing a missing entry",
getMultiset().contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAll_null() {
try {
getMultiset().entrySet().removeAll(null);
fail("multiset.entrySet.removeAll(null) didn't throw an exception");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAll_present() {
assertFalse(
"multiset.entrySet.retainAll(presentEntry) returned false",
getMultiset().entrySet().retainAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 1))));
assertTrue(
"multiset doesn't contains element after retaining its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAll_missing() {
assertTrue(
"multiset.entrySet.retainAll(missingEntry) returned true",
getMultiset().entrySet().retainAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 2))));
assertFalse(
"multiset contains element after retaining a different entry",
getMultiset().contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAll_null() {
try {
getMultiset().entrySet().retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException expected) {}
}
}
| 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.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import java.util.Arrays;
import java.util.Iterator;
/**
* Tester to make sure the {@code iterator().remove()} implementation of {@code Multiset} works when
* there are multiple occurrences of elements.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class MultisetIteratorTester<E> extends AbstractMultisetTester<E> {
@SuppressWarnings("unchecked")
@CollectionFeature.Require({SUPPORTS_REMOVE, KNOWN_ORDER})
public void testRemovingIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = SUPPORTS_REMOVE, absent = KNOWN_ORDER)
public void testRemovingIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_REMOVE)
public void testIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(absent = {SUPPORTS_REMOVE, KNOWN_ORDER})
public void testIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
}
| 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.testing.google;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST_2;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST_2;
import static junit.framework.Assert.assertEquals;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomains;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.TestCollectionGenerator;
import com.google.common.collect.testing.TestCollidingSetGenerator;
import com.google.common.collect.testing.TestIntegerSortedSetGenerator;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
/**
* Generators of different types of sets and derived collections from sets.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
public class SetGenerators {
public static class ImmutableSetCopyOfGenerator extends TestStringSetGenerator {
@Override protected Set<String> create(String[] elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class ImmutableSetWithBadHashesGenerator
extends TestCollidingSetGenerator
// Work around a GWT compiler bug. Not explicitly listing this will
// cause the createArray() method missing in the generated javascript.
// TODO: Remove this once the GWT bug is fixed.
implements TestCollectionGenerator<Object> {
@Override
public Set<Object> create(Object... elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class DegeneratedImmutableSetGenerator
extends TestStringSetGenerator {
// Make sure we get what we think we're getting, or else this test
// is pointless
@SuppressWarnings("cast")
@Override protected Set<String> create(String[] elements) {
return (ImmutableSet<String>)
ImmutableSet.of(elements[0], elements[0]);
}
}
public static class ImmutableSortedSetCopyOfGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSortedSetHeadsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.headSet("zzy");
}
}
public static class ImmutableSortedSetTailsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
return ImmutableSortedSet.copyOf(list)
.tailSet("\0\0");
}
}
public static class ImmutableSortedSetSubsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.subSet("\0\0", "zzy");
}
}
public static class ImmutableSortedSetExplicitComparator
extends TestStringSetGenerator {
private static final Comparator<String> STRING_REVERSED
= Collections.reverseOrder();
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.orderedBy(STRING_REVERSED)
.add(elements)
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetExplicitSuperclassComparatorGenerator
extends TestStringSetGenerator {
private static final Comparator<Comparable<?>> COMPARABLE_REVERSED
= Collections.reverseOrder();
@Override protected SortedSet<String> create(String[] elements) {
return new ImmutableSortedSet.Builder<String>(COMPARABLE_REVERSED)
.add(elements)
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetReversedOrderGenerator
extends TestStringSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.<String>reverseOrder()
.addAll(Arrays.asList(elements).iterator())
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetUnhashableGenerator
extends TestUnhashableSetGenerator {
@Override public Set<UnhashableObject> create(
UnhashableObject[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
return ImmutableSet.copyOf(elements).asList();
}
}
public static class ImmutableSortedSetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSet<String> set = ImmutableSortedSet.copyOf(
comparator, Arrays.asList(elements));
return set.asList();
}
}
public static class ImmutableSortedSetSubsetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST).asList();
}
}
public static class ImmutableSortedSetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().asList().subList(1, elements.length + 1);
}
}
public static class ImmutableSortedsetSubsetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(BEFORE_FIRST_2);
builder.add(elements);
builder.add(AFTER_LAST);
builder.add(AFTER_LAST_2);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST_2)
.asList().subList(1, elements.length + 1);
}
}
public abstract static class TestUnhashableSetGenerator
extends TestUnhashableCollectionGenerator<Set<UnhashableObject>>
implements TestSetGenerator<UnhashableObject> {
}
private static Ordering<String> createExplicitComparator(
String[] elements) {
// Collapse equal elements, which Ordering.explicit() doesn't support, while
// maintaining the ordering by first occurrence.
Set<String> elementsPlus = Sets.newLinkedHashSet();
elementsPlus.add(BEFORE_FIRST);
elementsPlus.add(BEFORE_FIRST_2);
elementsPlus.addAll(Arrays.asList(elements));
elementsPlus.add(AFTER_LAST);
elementsPlus.add(AFTER_LAST_2);
return Ordering.explicit(Lists.newArrayList(elementsPlus));
}
/*
* All the ContiguousSet generators below manually reject nulls here. In principle, we'd like to
* defer that to Range, since it's Range.asSet() that's used to create the sets. However, that
* gets messy here, and we already have null tests for Range.
*/
/*
* These generators also rely on consecutive integer inputs (not necessarily in order, but no
* holes).
*/
// SetCreationTester has some tests that pass in duplicates. Dedup them.
private static <E extends Comparable<? super E>> SortedSet<E> nullCheckedTreeSet(E[] elements) {
SortedSet<E> set = newTreeSet();
for (E element : elements) {
// Explicit null check because TreeSet wrongly accepts add(null) when empty.
set.add(checkNotNull(element));
}
return set;
}
public static class ContiguousSetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
return checkedCreate(nullCheckedTreeSet(elements));
}
}
public static class ContiguousSetHeadsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooHigh = (set.isEmpty()) ? 0 : set.last() + 1;
set.add(tooHigh);
return checkedCreate(set).headSet(tooHigh);
}
}
public static class ContiguousSetTailsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooLow = (set.isEmpty()) ? 0 : set.first() - 1;
set.add(tooLow);
return checkedCreate(set).tailSet(tooLow + 1);
}
}
public static class ContiguousSetSubsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
if (set.isEmpty()) {
/*
* The (tooLow + 1, tooHigh) arguments below would be invalid because tooLow would be
* greater than tooHigh.
*/
return Range.openClosed(0, 1).asSet(DiscreteDomains.integers()).subSet(0, 1);
}
int tooHigh = set.last() + 1;
int tooLow = set.first() - 1;
set.add(tooHigh);
set.add(tooLow);
return checkedCreate(set).subSet(tooLow + 1, tooHigh);
}
}
private abstract static class AbstractContiguousSetGenerator
extends TestIntegerSortedSetGenerator {
protected final ContiguousSet<Integer> checkedCreate(SortedSet<Integer> elementsSet) {
List<Integer> elements = newArrayList(elementsSet);
/*
* A ContiguousSet can't have holes. If a test demands a hole, it should be changed so that it
* doesn't need one, or it should be suppressed for ContiguousSet.
*/
for (int i = 0; i < elements.size() - 1; i++) {
assertEquals(elements.get(i) + 1, (int) elements.get(i + 1));
}
Range<Integer> range =
(elements.isEmpty()) ? Range.closedOpen(0, 0) : Range.encloseAll(elements);
return range.asSet(DiscreteDomains.integers());
}
}
}
| 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.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests multiset-specific read operations.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetReadsTester<E> extends AbstractMultisetTester<E> {
public void testCount_0() {
assertEquals("multiset.count(missing) didn't return 0",
0, getMultiset().count(samples.e3));
}
@CollectionSize.Require(absent = ZERO)
public void testCount_1() {
assertEquals("multiset.count(present) didn't return 1",
1, getMultiset().count(samples.e0));
}
@CollectionSize.Require(SEVERAL)
public void testCount_3() {
initThreeCopies();
assertEquals("multiset.count(thriceContained) didn't return 3",
3, getMultiset().count(samples.e0));
}
public void testCount_null() {
assertEquals("multiset.count(null) didn't return 0",
0, getMultiset().count(null));
}
public void testCount_wrongType() {
assertEquals("multiset.count(wrongType) didn't return 0",
0, getMultiset().count(WrongType.VALUE));
}
@CollectionSize.Require(absent = ZERO)
public void testElementSet_contains() {
assertTrue("multiset.elementSet().contains(present) returned false",
getMultiset().elementSet().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
public void testEntrySet_contains() {
assertTrue("multiset.entrySet() didn't contain [present, 1]",
getMultiset().entrySet().contains(
Multisets.immutableEntry(samples.e0, 1)));
}
public void testEntrySet_contains_count0() {
assertFalse("multiset.entrySet() contains [missing, 0]",
getMultiset().entrySet().contains(
Multisets.immutableEntry(samples.e3, 0)));
}
public void testEntrySet_contains_nonentry() {
assertFalse("multiset.entrySet() contains a non-entry",
getMultiset().entrySet().contains(samples.e0));
}
public void testEntrySet_twice() {
assertEquals("calling multiset.entrySet() twice returned unequal sets",
getMultiset().entrySet(), getMultiset().entrySet());
}
@CollectionSize.Require(ZERO)
public void testEntrySet_hashCode_size0() {
assertEquals("multiset.entrySet() has incorrect hash code",
0, getMultiset().entrySet().hashCode());
}
@CollectionSize.Require(ONE)
public void testEntrySet_hashCode_size1() {
assertEquals("multiset.entrySet() has incorrect hash code",
1 ^ samples.e0.hashCode(), getMultiset().entrySet().hashCode());
}
public void testEquals_yes() {
assertTrue("multiset doesn't equal a multiset with the same elements",
getMultiset().equals(HashMultiset.create(getSampleElements())));
}
public void testEquals_differentSize() {
Multiset<E> other = HashMultiset.create(getSampleElements());
other.add(samples.e0);
assertFalse("multiset equals a multiset with a different size",
getMultiset().equals(other));
}
@CollectionSize.Require(absent = ZERO)
public void testEquals_differentElements() {
Multiset<E> other = HashMultiset.create(getSampleElements());
other.remove(samples.e0);
other.add(samples.e3);
assertFalse("multiset equals a multiset with different elements",
getMultiset().equals(other));
}
@CollectionSize.Require(ZERO)
public void testHashCode_size0() {
assertEquals("multiset has incorrect hash code",
0, getMultiset().hashCode());
}
@CollectionSize.Require(ONE)
public void testHashCode_size1() {
assertEquals("multiset has incorrect hash code",
1 ^ samples.e0.hashCode(), getMultiset().hashCode());
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static java.util.Collections.sort;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@GwtCompatible(emulated = true)
public class Helpers {
// Clone of Objects.equal
static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
// Clone of Lists.newArrayList
public static <E> List<E> copyToList(Iterable<? extends E> elements) {
List<E> list = new ArrayList<E>();
addAll(list, elements);
return list;
}
public static <E> List<E> copyToList(E[] elements) {
return copyToList(Arrays.asList(elements));
}
// Clone of Sets.newLinkedHashSet
public static <E> Set<E> copyToSet(Iterable<? extends E> elements) {
Set<E> set = new LinkedHashSet<E>();
addAll(set, elements);
return set;
}
public static <E> Set<E> copyToSet(E[] elements) {
return copyToSet(Arrays.asList(elements));
}
// Would use Maps.immutableEntry
public static <K, V> Entry<K, V> mapEntry(K key, V value) {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
public static void assertEqualIgnoringOrder(
Iterable<?> expected, Iterable<?> actual) {
List<?> exp = copyToList(expected);
List<?> act = copyToList(actual);
String actString = act.toString();
// Of course we could take pains to give the complete description of the
// problem on any failure.
// Yeah it's n^2.
for (Object object : exp) {
if (!act.remove(object)) {
Assert.fail("did not contain expected element " + object + ", "
+ "expected = " + exp + ", actual = " + actString);
}
}
assertTrue("unexpected elements: " + act, act.isEmpty());
}
public static void assertContentsAnyOrder(
Iterable<?> actual, Object... expected) {
assertEqualIgnoringOrder(Arrays.asList(expected), actual);
}
public static <E> boolean addAll(
Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
boolean modified = false;
for (E e : elementsToAdd) {
modified |= addTo.add(e);
}
return modified;
}
static <T> Iterable<T> reverse(final List<T> list) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
final ListIterator<T> listIter = list.listIterator(list.size());
return new Iterator<T>() {
@Override
public boolean hasNext() {
return listIter.hasPrevious();
}
@Override
public T next() {
return listIter.previous();
}
@Override
public void remove() {
listIter.remove();
}
};
}
};
}
static <T> Iterator<T> cycle(final Iterable<T> iterable) {
return new Iterator<T>() {
Iterator<T> iterator = Collections.<T>emptySet().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
if (!iterator.hasNext()) {
iterator = iterable.iterator();
}
return iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
static <T> T get(Iterator<T> iterator, int position) {
for (int i = 0; i < position; i++) {
iterator.next();
}
return iterator.next();
}
static void fail(Throwable cause, Object message) {
AssertionFailedError assertionFailedError =
new AssertionFailedError(String.valueOf(message));
assertionFailedError.initCause(cause);
throw assertionFailedError;
}
public static <K, V> Comparator<Entry<K, V>> entryComparator(
final Comparator<? super K> keyComparator) {
return new Comparator<Entry<K, V>>() {
@Override
@SuppressWarnings("unchecked") // no less safe than putting it in the map!
public int compare(Entry<K, V> a, Entry<K, V> b) {
return (keyComparator == null)
? ((Comparable) a.getKey()).compareTo(b.getKey())
: keyComparator.compare(a.getKey(), b.getKey());
}
};
}
public static <T> void testComparator(
Comparator<? super T> comparator, T... valuesInExpectedOrder) {
testComparator(comparator, Arrays.asList(valuesInExpectedOrder));
}
public static <T> void testComparator(
Comparator<? super T> comparator, List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
T t = valuesInExpectedOrder.get(i);
for (int j = 0; j < i; j++) {
T lesser = valuesInExpectedOrder.get(j);
assertTrue(comparator + ".compare(" + lesser + ", " + t + ")",
comparator.compare(lesser, t) < 0);
}
assertEquals(comparator + ".compare(" + t + ", " + t + ")",
0, comparator.compare(t, t));
for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) {
T greater = valuesInExpectedOrder.get(j);
assertTrue(comparator + ".compare(" + greater + ", " + t + ")",
comparator.compare(greater, t) > 0);
}
}
}
public static <T extends Comparable<? super T>> void testCompareToAndEquals(
List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
T t = valuesInExpectedOrder.get(i);
for (int j = 0; j < i; j++) {
T lesser = valuesInExpectedOrder.get(j);
assertTrue(lesser + ".compareTo(" + t + ')', lesser.compareTo(t) < 0);
assertFalse(lesser.equals(t));
}
assertEquals(t + ".compareTo(" + t + ')', 0, t.compareTo(t));
assertTrue(t.equals(t));
for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) {
T greater = valuesInExpectedOrder.get(j);
assertTrue(greater + ".compareTo(" + t + ')', greater.compareTo(t) > 0);
assertFalse(greater.equals(t));
}
}
}
/**
* Returns a collection that simulates concurrent modification by
* having its size method return incorrect values. This is useful
* for testing methods that must treat the return value from size()
* as a hint only.
*
* @param delta the difference between the true size of the
* collection and the values returned by the size method
*/
public static <T> Collection<T> misleadingSizeCollection(final int delta) {
// It would be nice to be able to return a real concurrent
// collection like ConcurrentLinkedQueue, so that e.g. concurrent
// iteration would work, but that would not be GWT-compatible.
return new ArrayList<T>() {
@Override public int size() { return Math.max(0, super.size() + delta); }
};
}
/**
* Returns a "nefarious" map entry with the specified key and value,
* meaning an entry that is suitable for testing that map entries cannot be
* modified via a nefarious implementation of equals. This is used for testing
* unmodifiable collections of map entries; for example, it should not be
* possible to access the raw (modifiable) map entry via a nefarious equals
* method.
*/
public static <K, V> Map.Entry<K, V> nefariousMapEntry(final K key,
final V value) {
return new Map.Entry<K, V>() {
@Override public K getKey() {
return key;
}
@Override public V getValue() {
return value;
}
@Override public V setValue(V value) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean equals(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<K, V> e = (Map.Entry<K, V>) o;
e.setValue(value); // muhahaha!
return equal(this.getKey(), e.getKey())
&& equal(this.getValue(), e.getValue());
}
return false;
}
@Override public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ?
0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Override public String toString() {
return getKey() + "=" + getValue();
}
};
}
static <E> List<E> castOrCopyToList(Iterable<E> iterable) {
if (iterable instanceof List) {
return (List<E>) iterable;
}
List<E> list = new ArrayList<E>();
for (E e : iterable) {
list.add(e);
}
return list;
}
private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
@SuppressWarnings("unchecked") // assume any Comparable is Comparable<Self>
@Override public int compare(Comparable left, Comparable right) {
return left.compareTo(right);
}
};
public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey(
List<Entry<K, V>> insertionOrder) {
sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER));
return insertionOrder;
}
/**
* Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} to work around
* build-system quirks.
*/
private @interface GwtTransient {}
/**
* Compares strings in natural order except that null comes immediately before a given value. This
* works better than Ordering.natural().nullsFirst() because, if null comes before all other
* values, it lies outside the submap/submultiset ranges we test, and the variety of tests that
* exercise null handling fail on those subcollections.
*/
public abstract static class NullsBefore implements Comparator<String>, Serializable {
/*
* We don't serialize this class in GWT, so we don't care about whether GWT will serialize this
* field.
*/
@GwtTransient private final String justAfterNull;
protected NullsBefore(String justAfterNull) {
if (justAfterNull == null) {
throw new NullPointerException();
}
this.justAfterNull = justAfterNull;
}
@Override
public int compare(String lhs, String rhs) {
if (lhs == rhs) {
return 0;
}
if (lhs == null) {
// lhs (null) comes just before justAfterNull.
// If rhs is b, lhs comes first.
if (rhs.equals(justAfterNull)) {
return -1;
}
return justAfterNull.compareTo(rhs);
}
if (rhs == null) {
// rhs (null) comes just before justAfterNull.
// If lhs is b, rhs comes first.
if (lhs.equals(justAfterNull)) {
return 1;
}
return lhs.compareTo(justAfterNull);
}
return lhs.compareTo(rhs);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NullsBefore) {
NullsBefore other = (NullsBefore) obj;
return justAfterNull.equals(other.justAfterNull);
}
return false;
}
@Override
public int hashCode() {
return justAfterNull.hashCode();
}
}
public static final class NullsBeforeB extends NullsBefore {
public static final NullsBeforeB INSTANCE = new NullsBeforeB();
private NullsBeforeB() {
super("b");
}
}
public static final class NullsBeforeTwo extends NullsBefore {
public static final NullsBeforeTwo INSTANCE = new NullsBeforeTwo();
private NullsBeforeTwo() {
super("two"); // from TestStringSortedMapGenerator's sample keys
}
}
}
| 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.testing;
import com.google.gwt.core.client.GwtScriptOnly;
import com.google.gwt.lang.Array;
/**
* Version of {@link GwtPlatform} used in web-mode. It includes methods in
* {@link Platform} that requires different implementions in web mode and
* hosted mode. It is factored out from {@link Platform} because <code>
* {@literal @}GwtScriptOnly</code> only supports public classes and methods.
*
* @author Hayward Chan
*/
@GwtScriptOnly
public final class GwtPlatform {
private GwtPlatform() {}
public static <T> T[] clone(T[] array) {
return (T[]) Array.clone(array);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static java.util.Collections.emptyList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import com.google.common.testing.SerializableTester;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A generic JUnit test which tests {@code subList()} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListSubListTester<E> extends AbstractListTester<E> {
public void testSubList_startNegative() {
try {
getList().subList(-1, 0);
fail("subList(-1, 0) should throw");
} catch (IndexOutOfBoundsException expected) {
}
}
public void testSubList_endTooLarge() {
try {
getList().subList(0, getNumElements() + 1);
fail("subList(0, size + 1) should throw");
} catch (IndexOutOfBoundsException expected) {
}
}
public void testSubList_startGreaterThanEnd() {
try {
getList().subList(1, 0);
fail("subList(1, 0) should throw");
} catch (IndexOutOfBoundsException expected) {
} catch (IllegalArgumentException expected) {
/*
* The subList() docs claim that this should be an
* IndexOutOfBoundsException, but many JDK implementations throw
* IllegalArgumentException:
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4506427
*/
}
}
public void testSubList_empty() {
assertEquals("subList(0, 0) should be empty",
emptyList(), getList().subList(0, 0));
}
public void testSubList_entireList() {
assertEquals("subList(0, size) should be equal to the original list",
getList(), getList().subList(0, getNumElements()));
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListRemoveAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.remove(0);
List<E> expected =
Arrays.asList(createSamplesArray()).subList(1, getNumElements());
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testSubList_subListAddAffectsOriginal() {
List<E> subList = getList().subList(0, 0);
subList.add(samples.e3);
expectAdded(0, samples.e3);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListSetAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.set(0, samples.e3);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.set(0, samples.e3);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSubList_originalListSetAffectsSubList() {
List<E> subList = getList().subList(0, 1);
getList().set(0, samples.e3);
assertEquals("A set() call to a list after a sublist has been created "
+ "should be reflected in the sublist",
Collections.singletonList(samples.e3), subList);
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListRemoveAffectsOriginalLargeList() {
List<E> subList = getList().subList(1, 3);
subList.remove(samples.e2);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.remove(2);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListAddAtIndexAffectsOriginalLargeList() {
List<E> subList = getList().subList(2, 3);
subList.add(0, samples.e3);
expectAdded(2, samples.e3);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListSetAffectsOriginalLargeList() {
List<E> subList = getList().subList(1, 2);
subList.set(0, samples.e3);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.set(1, samples.e3);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_originalListSetAffectsSubListLargeList() {
List<E> subList = getList().subList(1, 3);
getList().set(1, samples.e3);
assertEquals("A set() call to a list after a sublist has been created "
+ "should be reflected in the sublist",
Arrays.asList(samples.e3, samples.e2), subList);
}
public void testSubList_ofSubListEmpty() {
List<E> subList = getList().subList(0, 0).subList(0, 0);
assertEquals("subList(0, 0).subList(0, 0) should be an empty list",
emptyList(), subList);
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_ofSubListNonEmpty() {
List<E> subList = getList().subList(0, 2).subList(1, 2);
assertEquals("subList(0, 2).subList(1, 2) "
+ "should be a single-element list of the element at index 1",
Collections.singletonList(samples.e1), subList);
}
@CollectionSize.Require(absent = {ZERO})
public void testSubList_size() {
List<E> list = getList();
int size = getNumElements();
assertEquals(list.subList(0, size).size(),
size);
assertEquals(list.subList(0, size - 1).size(),
size - 1);
assertEquals(list.subList(1, size).size(),
size - 1);
assertEquals(list.subList(size, size).size(),
0);
assertEquals(list.subList(0, 0).size(),
0);
}
@CollectionSize.Require(absent = {ZERO})
public void testSubList_isEmpty() {
List<E> list = getList();
int size = getNumElements();
for (List<E> subList : Arrays.asList(
list.subList(0, size),
list.subList(0, size - 1),
list.subList(1, size),
list.subList(0, 0),
list.subList(size, size))) {
assertEquals(subList.isEmpty(), subList.size() == 0);
}
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_get() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(list.get(0), copy.get(0));
assertEquals(list.get(size - 1), copy.get(size - 1));
assertEquals(list.get(1), tail.get(0));
assertEquals(list.get(size - 1), tail.get(size - 2));
assertEquals(list.get(0), head.get(0));
assertEquals(list.get(size - 2), head.get(size - 2));
for (List<E> subList : Arrays.asList(copy, head, tail)) {
for (int index : Arrays.asList(-1, subList.size())) {
try {
subList.get(index);
fail("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
}
}
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_contains() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertTrue(copy.contains(list.get(0)));
assertTrue(head.contains(list.get(0)));
assertTrue(tail.contains(list.get(1)));
// The following assumes all elements are distinct.
assertTrue(copy.contains(list.get(size - 1)));
assertTrue(head.contains(list.get(size - 2)));
assertTrue(tail.contains(list.get(size - 1)));
assertFalse(head.contains(list.get(size - 1)));
assertFalse(tail.contains(list.get(0)));
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_indexOf() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(copy.indexOf(list.get(0)),
0);
assertEquals(head.indexOf(list.get(0)),
0);
assertEquals(tail.indexOf(list.get(1)),
0);
// The following assumes all elements are distinct.
assertEquals(copy.indexOf(list.get(size - 1)),
size - 1);
assertEquals(head.indexOf(list.get(size - 2)),
size - 2);
assertEquals(tail.indexOf(list.get(size - 1)),
size - 2);
assertEquals(head.indexOf(list.get(size - 1)),
-1);
assertEquals(tail.indexOf(list.get(0)),
-1);
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_lastIndexOf() {
List<E> list = getList();
int size = list.size();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(copy.lastIndexOf(list.get(size - 1)),
size - 1);
assertEquals(head.lastIndexOf(list.get(size - 2)),
size - 2);
assertEquals(tail.lastIndexOf(list.get(size - 1)),
size - 2);
// The following assumes all elements are distinct.
assertEquals(copy.lastIndexOf(list.get(0)),
0);
assertEquals(head.lastIndexOf(list.get(0)),
0);
assertEquals(tail.lastIndexOf(list.get(1)),
0);
assertEquals(head.lastIndexOf(list.get(size - 1)),
-1);
assertEquals(tail.lastIndexOf(list.get(0)),
-1);
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testReserializeWholeSubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements()));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testReserializeEmptySubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, 0));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testReserializeSubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, 2));
}
/*
* TODO: perform all List tests on subList(), but beware infinite recursion
*/
}
| 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.testing.testers;
import com.google.common.annotations.GwtCompatible;
/**
* Tests {@link java.util.List#hashCode}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class ListHashCodeTester<E> extends AbstractListTester<E> {
public void testHashCode() {
int expectedHashCode = 1;
for (E element : getSampleElements()) {
expectedHashCode = 31 * expectedHashCode +
((element == null) ? 0 : element.hashCode());
}
assertEquals(
"A List's hashCode() should be computed from those of its elements.",
expectedHashCode, getList().hashCode());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
/**
* A generic JUnit test which tests {@code set()} operations on a list. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class ListSetTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSet() {
doTestSet(samples.e3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@ListFeature.Require(SUPPORTS_SET)
public void testSet_null() {
doTestSet(null);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@ListFeature.Require(SUPPORTS_SET)
public void testSet_replacingNull() {
E[] elements = createSamplesArray();
int i = aValidIndex();
elements[i] = null;
collection = getSubjectGenerator().create(elements);
doTestSet(samples.e3);
}
private void doTestSet(E newValue) {
int index = aValidIndex();
E initialValue = getList().get(index);
assertEquals("set(i, x) should return the old element at position i.",
initialValue, getList().set(index, newValue));
assertEquals("After set(i, x), get(i) should return x",
newValue, getList().get(index));
assertEquals("set() should not change the size of a list.",
getNumElements(), getList().size());
}
@ListFeature.Require(SUPPORTS_SET)
public void testSet_indexTooLow() {
try {
getList().set(-1, samples.e3);
fail("set(-1) should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_SET)
public void testSet_indexTooHigh() {
int index = getNumElements();
try {
getList().set(index, samples.e3);
fail("set(size) should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@ListFeature.Require(absent = SUPPORTS_SET)
public void testSet_unsupported() {
try {
getList().set(aValidIndex(), samples.e3);
fail("set() should throw UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionSize.Require(ZERO)
@ListFeature.Require(absent = SUPPORTS_SET)
public void testSet_unsupportedByEmptyList() {
try {
getList().set(0, samples.e3);
fail("set() should throw UnsupportedOperationException "
+ "or IndexOutOfBoundsException");
} catch (UnsupportedOperationException tolerated) {
} catch (IndexOutOfBoundsException tolerated) {
}
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@ListFeature.Require(SUPPORTS_SET)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSet_nullUnsupported() {
try {
getList().set(aValidIndex(), null);
fail("set(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
expectUnchanged();
}
private int aValidIndex() {
return getList().size() / 2;
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public class CollectionCreationTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNull_supported() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
expectContents(array);
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNull_unsupported() {
E[] array = createArrayWithNullElement();
try {
getSubjectGenerator().create(array);
fail("Creating a collection containing null should fail");
} catch (NullPointerException expected) {
}
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code add} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class CollectionAddTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAdd_supportedNotPresent() {
assertTrue("add(notPresent) should return true",
collection.add(samples.e3));
expectAdded(samples.e3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAdd_unsupportedNotPresent() {
try {
collection.add(samples.e3);
fail("add(notPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_unsupportedPresent() {
try {
assertFalse("add(present) should return false or throw",
collection.add(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(
value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testAdd_nullSupported() {
assertTrue("add(null) should return true", collection.add(null));
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD,
absent = ALLOWS_NULL_VALUES)
public void testAdd_nullUnsupported() {
try {
collection.add(null);
fail("add(null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported add(null)");
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.add(samples.e3));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A generic JUnit test which tests {@code iterator} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public class CollectionIteratorTester<E> extends AbstractCollectionTester<E> {
public void testIterator() {
List<E> iteratorElements = new ArrayList<E>();
for (E element : collection) { // uses iterator()
iteratorElements.add(element);
}
Helpers.assertEqualIgnoringOrder(
Arrays.asList(createSamplesArray()), iteratorElements);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testIterationOrdering() {
List<E> iteratorElements = new ArrayList<E>();
for (E element : collection) { // uses iterator()
iteratorElements.add(element);
}
List<E> expected = Helpers.copyToList(getOrderedElements());
assertEquals("Different ordered iteration", expected, iteratorElements);
}
// TODO: switch to DerivedIteratorTestSuiteBuilder
@CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE})
public void testIterator_knownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_REMOVE)
public void testIterator_knownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_REMOVE)
public void testIterator_unknownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
@CollectionFeature.Require(absent = {KNOWN_ORDER, SUPPORTS_REMOVE})
public void testIterator_unknownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
private void runIteratorTest(Set<IteratorFeature> features,
IteratorTester.KnownOrder knownOrder, Iterable<E> elements) {
new IteratorTester<E>(Platform.collectionIteratorTesterNumIterations(), features, elements,
knownOrder) {
{
// TODO: don't set this universally
ignoreSunJavaBug6529795();
}
@Override protected Iterator<E> newTargetIterator() {
resetCollection();
return collection.iterator();
}
@Override protected void verify(List<E> elements) {
expectContents(elements);
}
}.test();
}
public void testIteratorNoSuchElementException() {
Iterator<E> iterator = collection.iterator();
while (iterator.hasNext()) {
iterator.next();
}
try {
iterator.next();
fail("iterator.next() should throw NoSuchElementException");
} catch (NoSuchElementException expected) {}
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests add operations on a set. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class SetAddTester<E> extends AbstractSetTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedPresent() {
assertFalse("add(present) should return false", getSet().add(samples.e0));
expectUnchanged();
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedNullPresent() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
assertFalse("add(nullPresent) should return false", getSet().add(null));
expectContents(array);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code add(int, Object)} operations on a
* list. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListAddAtIndexTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAtIndex_supportedPresent() {
getList().add(0, samples.e0);
expectAdded(0, samples.e0);
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
/*
* absent = ZERO isn't required, since unmodList.add() must
* throw regardless, but it keeps the method name accurate.
*/
public void testAddAtIndex_unsupportedPresent() {
try {
getList().add(0, samples.e0);
fail("add(n, present) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_supportedNotPresent() {
getList().add(0, samples.e3);
expectAdded(0, samples.e3);
}
@CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION)
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndexConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
getList().add(0, samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_unsupportedNotPresent() {
try {
getList().add(0, samples.e3);
fail("add(n, notPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testAddAtIndex_middle() {
getList().add(getNumElements() / 2, samples.e3);
expectAdded(getNumElements() / 2, samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAtIndex_end() {
getList().add(getNumElements(), samples.e3);
expectAdded(getNumElements(), samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testAddAtIndex_nullSupported() {
getList().add(0, null);
expectAdded(0, (E) null);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testAddAtIndex_nullUnsupported() {
try {
getList().add(0, null);
fail("add(n, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported add(n, null)");
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_negative() {
try {
getList().add(-1, samples.e3);
fail("add(-1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_tooLarge() {
try {
getList().add(getNumElements() + 1, samples.e3);
fail("add(size + 1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.List;
/**
* A generic JUnit test which tests {@code add(Object)} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListAddTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedPresent() {
assertTrue("add(present) should return true", getList().add(samples.e0));
expectAdded(samples.e0);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
/*
* absent = ZERO isn't required, since unmodList.add() must
* throw regardless, but it keeps the method name accurate.
*/
public void testAdd_unsupportedPresent() {
try {
getList().add(samples.e0);
fail("add(present) should throw");
} catch (UnsupportedOperationException expected) {
}
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedNullPresent() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
assertTrue("add(nullPresent) should return true", getList().add(null));
List<E> expected = Helpers.copyToList(array);
expected.add(null);
expectContents(expected);
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static com.google.common.collect.testing.testers.Platform.listListIteratorTesterNumIterations;
import static java.util.Collections.singleton;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.ListIteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.ListFeature;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
/**
* A generic JUnit test which tests {@code listIterator} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class ListListIteratorTester<E> extends AbstractListTester<E> {
// TODO: switch to DerivedIteratorTestSuiteBuilder
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
@ListFeature.Require(absent = {SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX})
public void testListIterator_unmodifiable() {
runListIteratorTest(UNMODIFIABLE);
}
/*
* For now, we don't cope with testing this when the list supports only some
* modification operations.
*/
@CollectionFeature.Require(SUPPORTS_REMOVE)
@ListFeature.Require({SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX})
public void testListIterator_fullyModifiable() {
runListIteratorTest(MODIFIABLE);
}
private void runListIteratorTest(Set<IteratorFeature> features) {
new ListIteratorTester<E>(
listListIteratorTesterNumIterations(), singleton(samples.e4), features,
Helpers.copyToList(getSampleElements()), 0) {
{
// TODO: don't set this universally
stopTestingWhenAddThrowsException();
}
@Override protected ListIterator<E> newTargetIterator() {
resetCollection();
return getList().listIterator();
}
@Override protected void verify(List<E> elements) {
expectContents(elements);
}
}.test();
}
public void testListIterator_tooLow() {
try {
getList().listIterator(-1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testListIterator_tooHigh() {
try {
getList().listIterator(getNumElements() + 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testListIterator_atSize() {
getList().listIterator(getNumElements());
// TODO: run the iterator through ListIteratorTester
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Arrays;
import java.util.List;
/**
* A generic JUnit test which tests {@code toArray()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public class CollectionToArrayTester<E> extends AbstractCollectionTester<E> {
public void testToArray_noArgs() {
Object[] array = collection.toArray();
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
/**
* {@link Collection#toArray(Object[])} says: "Note that
* <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>."
*
* <p>For maximum effect, the collection under test should be created from an
* element array of a type other than {@code Object[]}.
*/
public void testToArray_isPlainObjectArray() {
Object[] array = collection.toArray();
assertEquals(Object[].class, array.getClass());
}
public void testToArray_emptyArray() {
E[] empty = getSubjectGenerator().createArray(0);
E[] array = collection.toArray(empty);
assertEquals("toArray(emptyT[]) should return an array of type T",
empty.getClass(), array.getClass());
assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_emptyArray_ordered() {
E[] empty = getSubjectGenerator().createArray(0);
E[] array = collection.toArray(empty);
assertEquals("toArray(emptyT[]) should return an array of type T",
empty.getClass(), array.getClass());
assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_emptyArrayOfObject() {
Object[] in = new Object[0];
Object[] array = collection.toArray(in);
assertEquals("toArray(emptyObject[]) should return an array of type Object",
Object[].class, array.getClass());
assertEquals("toArray(emptyObject[]).length",
getNumElements(), array.length);
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
public void testToArray_rightSizedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements());
assertSame("toArray(sameSizeE[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_rightSizedArray_ordered() {
E[] array = getSubjectGenerator().createArray(getNumElements());
assertSame("toArray(sameSizeE[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_rightSizedArrayOfObject() {
Object[] array = new Object[getNumElements()];
assertSame("toArray(sameSizeObject[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_rightSizedArrayOfObject_ordered() {
Object[] array = new Object[getNumElements()];
assertSame("toArray(sameSizeObject[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_oversizedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
array[getNumElements()] = samples.e3;
array[getNumElements() + 1] = samples.e3;
assertSame("toArray(overSizedE[]) should return the given array",
array, collection.toArray(array));
List<E> subArray = Arrays.asList(array).subList(0, getNumElements());
E[] expectedSubArray = createSamplesArray();
for (int i = 0; i < getNumElements(); i++) {
assertTrue(
"toArray(overSizedE[]) should contain element " + expectedSubArray[i],
subArray.contains(expectedSubArray[i]));
}
assertNull("The array element "
+ "immediately following the end of the collection should be nulled",
array[getNumElements()]);
// array[getNumElements() + 1] might or might not have been nulled
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_oversizedArray_ordered() {
E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
array[getNumElements()] = samples.e3;
array[getNumElements() + 1] = samples.e3;
assertSame("toArray(overSizedE[]) should return the given array",
array, collection.toArray(array));
List<E> expected = getOrderedElements();
for (int i = 0; i < getNumElements(); i++) {
assertEquals(expected.get(i), array[i]);
}
assertNull("The array element "
+ "immediately following the end of the collection should be nulled",
array[getNumElements()]);
// array[getNumElements() + 1] might or might not have been nulled
}
@CollectionSize.Require(absent = ZERO)
public void testToArray_emptyArrayOfWrongTypeForNonEmptyCollection() {
try {
WrongType[] array = new WrongType[0];
collection.toArray(array);
fail("toArray(notAssignableTo[]) should throw");
} catch (ArrayStoreException expected) {
}
}
@CollectionSize.Require(ZERO)
public void testToArray_emptyArrayOfWrongTypeForEmptyCollection() {
WrongType[] array = new WrongType[0];
assertSame(
"toArray(sameSizeNotAssignableTo[]) should return the given array",
array, collection.toArray(array));
}
private void expectArrayContentsAnyOrder(Object[] expected, Object[] actual) {
Helpers.assertEqualIgnoringOrder(
Arrays.asList(expected), Arrays.asList(actual));
}
private void expectArrayContentsInOrder(List<E> expected, Object[] actual) {
assertEquals("toArray() ordered contents: ",
expected, Arrays.asList(actual));
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collection;
/**
* Tests {@link java.util.Set#hashCode}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class SetHashCodeTester<E> extends AbstractSetTester<E> {
public void testHashCode() {
int expectedHashCode = 0;
for (E element : getSampleElements()) {
expectedHashCode += ((element == null) ? 0 : element.hashCode());
}
assertEquals(
"A Set's hashCode() should be the sum of those of its elements.",
expectedHashCode, getSet().hashCode());
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testHashCode_containingNull() {
Collection<E> elements = getSampleElements(getNumElements() - 1);
int expectedHashCode = 0;
for (E element : elements) {
expectedHashCode += ((element == null) ? 0 : element.hashCode());
}
elements.add(null);
collection = getSubjectGenerator().create(elements.toArray());
assertEquals(
"A Set's hashCode() should be the sum of those of its elements (with "
+ "a null element counting as having a hash of zero).",
expectedHashCode, getSet().hashCode());
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import com.google.common.annotations.GwtCompatible;
import com.google.gwt.core.client.GWT;
/**
* The emulation source used in GWT.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
class Platform {
// Use fewer steps in the ListIteratorTester in ListListIteratorTester because it's slow in prod
// mode.
static int listListIteratorTesterNumIterations() {
// TODO(hhchan): It's 4 in java. Figure out why even 3 is too slow in prod mode.
return GWT.isProdMode() ? 2 : 4;
}
// Use fewer steps in the IteratorTester in CollectionIteratorTester because it's slow in prod
// mode..
static int collectionIteratorTesterNumIterations() {
return GWT.isProdMode() ? 3 : 5;
}
// TODO: Consolidate different copies in one single place.
static String format(String template, Object... args) {
// 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) 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code put} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class MapPutTester<K, V> extends AbstractMapTester<K, V> {
private Entry<K, V> nullKeyEntry;
private Entry<K, V> nullValueEntry;
private Entry<K, V> nullKeyValueEntry;
private Entry<K, V> presentKeyNullValueEntry;
@Override public void setUp() throws Exception {
super.setUp();
nullKeyEntry = entry(null, samples.e3.getValue());
nullValueEntry = entry(samples.e3.getKey(), null);
nullKeyValueEntry = entry(null, null);
presentKeyNullValueEntry = entry(samples.e0.getKey(), null);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPut_supportedNotPresent() {
assertNull("put(notPresent, value) should return null", put(samples.e3));
expectAdded(samples.e3);
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithKeySetIteration() {
try {
Iterator<K> iterator = getMap().keySet().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithValueIteration() {
try {
Iterator<V> iterator = getMap().values().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPut_unsupportedNotPresent() {
try {
put(samples.e3);
fail("put(notPresent, value) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPut_unsupportedPresentExistingValue() {
try {
assertEquals("put(present, existingValue) should return present or throw",
samples.e0.getValue(), put(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPut_unsupportedPresentDifferentValue() {
try {
getMap().put(samples.e0.getKey(), samples.e3.getValue());
fail("put(present, differentValue) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPut_nullKeySupportedNotPresent() {
assertNull("put(null, value) should return null", put(nullKeyEntry));
expectAdded(nullKeyEntry);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
@CollectionSize.Require(absent = ZERO)
public void testPut_nullKeySupportedPresent() {
Entry<K, V> newEntry = entry(null, samples.e3.getValue());
initMapWithNullKey();
assertEquals("put(present, value) should return the associated value",
getValueForNullKey(), put(newEntry));
Entry<K, V>[] expected = createArrayWithNullKey();
expected[getNullLocation()] = newEntry;
expectContents(expected);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS)
public void testPut_nullKeyUnsupported() {
try {
put(nullKeyEntry);
fail("put(null, value) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullKeyMissingWhenNullKeysUnsupported(
"Should not contain null key after unsupported put(null, value)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPut_nullValueSupported() {
assertNull("put(key, null) should return null", put(nullValueEntry));
expectAdded(nullValueEntry);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPut_nullValueUnsupported() {
try {
put(nullValueEntry);
fail("put(key, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null value after unsupported put(key, null)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceWithNullValueSupported() {
assertEquals("put(present, null) should return the associated value",
samples.e0.getValue(), put(presentKeyNullValueEntry));
expectReplacement(presentKeyNullValueEntry);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceWithNullValueUnsupported() {
try {
put(presentKeyNullValueEntry);
fail("put(present, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null after unsupported put(present, null)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceNullValueWithNullSupported() {
initMapWithNullValue();
assertNull("put(present, null) should return the associated value (null)",
getMap().put(getKeyForNullValue(), null));
expectContents(createArrayWithNullValue());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceNullValueWithNonNullSupported() {
Entry<K, V> newEntry = entry(getKeyForNullValue(), samples.e3.getValue());
initMapWithNullValue();
assertNull("put(present, value) should return the associated value (null)",
put(newEntry));
Entry<K, V>[] expected = createArrayWithNullValue();
expected[getNullLocation()] = newEntry;
expectContents(expected);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
public void testPut_nullKeyAndValueSupported() {
assertNull("put(null, null) should return null", put(nullKeyValueEntry));
expectAdded(nullKeyValueEntry);
}
private V put(Map.Entry<K, V> entry) {
return getMap().put(entry.getKey(), entry.getValue());
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static java.util.Collections.singletonList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
/**
* A generic JUnit test which tests addAll operations on a collection. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class CollectionAddAllTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_supportedNothing() {
assertFalse("addAll(nothing) should return false",
collection.addAll(emptyCollection()));
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddAll_unsupportedNothing() {
try {
assertFalse("addAll(nothing) should return false or throw",
collection.addAll(emptyCollection()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_supportedNonePresent() {
assertTrue("addAll(nonePresent) should return true",
collection.addAll(createDisjointCollection()));
expectAdded(samples.e3, samples.e4);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddAll_unsupportedNonePresent() {
try {
collection.addAll(createDisjointCollection());
fail("addAll(nonePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3, samples.e4);
}
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_supportedSomePresent() {
assertTrue("addAll(somePresent) should return true",
collection.addAll(MinimalCollection.of(samples.e3, samples.e0)));
assertTrue("should contain " + samples.e3, collection.contains(samples.e3));
assertTrue("should contain " + samples.e0, collection.contains(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedSomePresent() {
try {
collection.addAll(MinimalCollection.of(samples.e3, samples.e0));
fail("addAll(somePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddAllConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.addAll(MinimalCollection.of(samples.e3, samples.e0)));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedAllPresent() {
try {
assertFalse("addAll(allPresent) should return false or throw",
collection.addAll(MinimalCollection.of(samples.e0)));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(value = {SUPPORTS_ADD,
ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS)
public void testAddAll_nullSupported() {
List<E> containsNull = singletonList(null);
assertTrue("addAll(containsNull) should return true", collection
.addAll(containsNull));
/*
* We need (E) to force interpretation of null as the single element of a
* varargs array, not the array itself
*/
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD,
absent = ALLOWS_NULL_VALUES)
public void testAddAll_nullUnsupported() {
List<E> containsNull = singletonList(null);
try {
collection.addAll(containsNull);
fail("addAll(containsNull) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported addAll(containsNull)");
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_nullCollectionReference() {
try {
collection.addAll(null);
fail("addAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static java.util.Collections.singletonList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code putAll} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class MapPutAllTester<K, V> extends AbstractMapTester<K, V> {
private List<Entry<K, V>> containsNullKey;
private List<Entry<K, V>> containsNullValue;
@Override public void setUp() throws Exception {
super.setUp();
containsNullKey = singletonList(entry(null, samples.e3.getValue()));
containsNullValue = singletonList(entry(samples.e3.getKey(), null));
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll_supportedNothing() {
getMap().putAll(emptyMap());
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPutAll_unsupportedNothing() {
try {
getMap().putAll(emptyMap());
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll_supportedNonePresent() {
putAll(createDisjointCollection());
expectAdded(samples.e3, samples.e4);
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPutAll_unsupportedNonePresent() {
try {
putAll(createDisjointCollection());
fail("putAll(nonePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3, samples.e4);
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_supportedSomePresent() {
putAll(MinimalCollection.of(samples.e3, samples.e0));
expectAdded(samples.e3);
}
@MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_PUT })
@CollectionSize.Require(absent = ZERO)
public void testPutAllSomePresentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
putAll(MinimalCollection.of(samples.e3, samples.e0));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_unsupportedSomePresent() {
try {
putAll(MinimalCollection.of(samples.e3, samples.e0));
fail("putAll(somePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_unsupportedAllPresent() {
try {
putAll(MinimalCollection.of(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_PUT,
ALLOWS_NULL_KEYS})
public void testPutAll_nullKeySupported() {
putAll(containsNullKey);
expectAdded(containsNullKey.get(0));
}
@MapFeature.Require(value = SUPPORTS_PUT,
absent = ALLOWS_NULL_KEYS)
public void testPutAll_nullKeyUnsupported() {
try {
putAll(containsNullKey);
fail("putAll(containsNullKey) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullKeyMissingWhenNullKeysUnsupported(
"Should not contain null key after unsupported " +
"putAll(containsNullKey)");
}
@MapFeature.Require({SUPPORTS_PUT,
ALLOWS_NULL_VALUES})
public void testPutAll_nullValueSupported() {
putAll(containsNullValue);
expectAdded(containsNullValue.get(0));
}
@MapFeature.Require(value = SUPPORTS_PUT,
absent = ALLOWS_NULL_VALUES)
public void testPutAll_nullValueUnsupported() {
try {
putAll(containsNullValue);
fail("putAll(containsNullValue) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null value after unsupported " +
"putAll(containsNullValue)");
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll_nullCollectionReference() {
try {
getMap().putAll(null);
fail("putAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
private Map<K, V> emptyMap() {
return Collections.emptyMap();
}
private void putAll(Iterable<Entry<K, V>> entries) {
Map<K, V> map = new LinkedHashMap<K, V>();
for (Entry<K, V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
getMap().putAll(map);
}
}
| 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.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a map. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class MapCreationTester<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeySupported() {
initMapWithNullKey();
expectContents(createArrayWithNullKey());
}
@MapFeature.Require(absent = ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyUnsupported() {
try {
initMapWithNullKey();
fail("Creating a map containing a null key should fail");
} catch (NullPointerException expected) {
}
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueSupported() {
initMapWithNullValue();
expectContents(createArrayWithNullValue());
}
@MapFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueUnsupported() {
try {
initMapWithNullValue();
fail("Creating a map containing a null value should fail");
} catch (NullPointerException expected) {
}
}
@MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyAndValueSupported() {
Entry<K, V>[] entries = createSamplesArray();
entries[getNullLocation()] = entry(null, null);
resetMap(entries);
expectContents(entries);
}
@MapFeature.Require(value = ALLOWS_NULL_KEYS,
absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNullKeys());
}
@MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNonNullKeys());
}
@MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION})
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNullKeys();
try {
resetMap(entries);
fail("Should reject duplicate null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
@MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNonNullKeys();
try {
resetMap(entries);
fail("Should reject duplicate non-null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
private Entry<K, V>[] getEntriesMultipleNullKeys() {
Entry<K, V>[] entries = createArrayWithNullKey();
entries[0] = entry(null, entries[0].getValue());
return entries;
}
private Entry<K, V>[] getEntriesMultipleNonNullKeys() {
Entry<K, V>[] entries = createSamplesArray();
entries[0] = entry(samples.e1.getKey(), samples.e0.getValue());
return entries;
}
private void expectFirstRemoved(Entry<K, V>[] entries) {
resetMap(entries);
List<Entry<K, V>> expectedWithDuplicateRemoved =
Arrays.asList(entries).subList(1, getNumElements());
expectContents(expectedWithDuplicateRemoved);
}
}
| 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.testing;
/**
* Minimal GWT emulation of {@code com.google.common.collect.testing.Platform}.
*
* <p><strong>This .java file should never be consumed by javac.</strong>
*
* @author Hayward Chan
*/
class Platform {
static boolean checkIsInstance(Class<?> clazz, Object obj) {
/*
* In GWT, we can't tell whether obj is an instance of clazz because GWT
* doesn't support reflections. For testing purposes, we give up this
* particular assertion (so that we can keep the rest).
*/
return true;
}
// Class.cast is not supported in GWT.
static void checkCast(Class<?> clazz, Object obj) {
}
static <T> T[] clone(T[] array) {
return GwtPlatform.clone(array);
}
// TODO: Consolidate different copies in one single place.
static String format(String template, Object... args) {
// 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();
}
static String classGetSimpleName(Class<?> clazz) {
throw new UnsupportedOperationException("Shouldn't be called in GWT.");
}
}
| 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 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 ForwardingImmutableSet<E> implements SortedSet<E>, SortedIterable<E> {
// TODO(cpovirk): split into ImmutableSortedSet/ForwardingImmutableSortedSet?
// 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;
/**
* Scary constructor for ContiguousSet. This constructor (in this file, the
* GWT emulation of ImmutableSortedSet) creates an empty sortedDelegate,
* which, in a vacuum, sets this object's contents to empty. By contrast,
* the non-GWT constructor with the same signature uses the comparator only
* as a comparator. It does NOT assume empty contents. (It requires an
* implementation of iterator() to define its contents, and methods like
* contains() are implemented in terms of that method (though they will
* likely be overridden by subclasses for performance reasons).) This means
* that a call to this method have can different behavior in GWT and non-GWT
* environments UNLESS subclasses are careful to always override all methods
* implemented in terms of sortedDelegate (except comparator()).
*/
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) 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 ForwardingImmutableSet<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 com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
/**
* List returned by {@code ImmutableSortedSet.asList()} when the set isn't empty.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial")
final class ImmutableSortedAsList<E> extends RegularImmutableAsList<E>
implements SortedIterable<E> {
ImmutableSortedAsList(
ImmutableSortedSet<E> backingSet, ImmutableList<E> backingList) {
super(backingSet, backingList);
}
@Override
ImmutableSortedSet<E> delegateCollection() {
return (ImmutableSortedSet<E>) super.delegateCollection();
}
@Override public Comparator<? super E> comparator() {
return delegateCollection().comparator();
}
// Override indexOf() and lastIndexOf() to be O(log N) instead of O(N).
@Override
public boolean contains(Object target) {
// Necessary for ISS's with comparators inconsistent with equals.
return indexOf(target) >= 0;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* An immutable {@link SetMultimap} with reliable user-specified key and value
* iteration order. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableSetMultimap(SetMultimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableSetMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableSetMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Mike Ward
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableSetMultimap<K, V>
extends ImmutableMultimap<K, V>
implements SetMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableSetMultimap<K, V> of() {
return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
builder.put(k5, v5);
return builder.build();
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new {@link Builder}.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Multimap for {@link ImmutableSetMultimap.Builder} that maintains key
* and value orderings and performs better than {@link LinkedHashMultimap}.
*/
private static class BuilderMultimap<K, V> extends AbstractMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Sets.newLinkedHashSet();
}
private static final long serialVersionUID = 0;
}
/**
* Multimap for {@link ImmutableSetMultimap.Builder} that sorts keys and
* maintains value orderings.
*/
private static class SortedKeyBuilderMultimap<K, V>
extends AbstractMultimap<K, V> {
SortedKeyBuilderMultimap(
Comparator<? super K> keyComparator, Multimap<K, V> multimap) {
super(new TreeMap<K, Collection<V>>(keyComparator));
putAll(multimap);
}
@Override Collection<V> createCollection() {
return Sets.newLinkedHashSet();
}
private static final long serialVersionUID = 0;
}
/**
* A builder for creating immutable {@code SetMultimap} instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableSetMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<K, V>
extends ImmutableMultimap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSetMultimap#builder}.
*/
public Builder() {
builderMultimap = new BuilderMultimap<K, V>();
}
/**
* Adds a key-value mapping to the built multimap if it is not already
* present.
*/
@Override public Builder<K, V> put(K key, V value) {
builderMultimap.put(checkNotNull(key), checkNotNull(value));
return this;
}
/**
* Adds an entry to the built multimap if it is not already present.
*
* @since 11.0
*/
@Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
builderMultimap.put(
checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
return this;
}
@Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
Collection<V> collection = builderMultimap.get(checkNotNull(key));
for (V value : values) {
collection.add(checkNotNull(value));
}
return this;
}
@Override public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
@Override public Builder<K, V> putAll(
Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Beta @Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
this.keyComparator = checkNotNull(keyComparator);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* <p>If this method is called, the sets returned by the {@code get()}
* method of the generated multimap and its {@link Multimap#asMap()} view
* are {@link ImmutableSortedSet} instances. However, serialization does not
* preserve that property, though it does maintain the key and value
* ordering.
*
* @since 8.0
*/
// TODO: Make serialization behavior consistent.
@Beta @Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/**
* Returns a newly-created immutable set multimap.
*/
@Override public ImmutableSetMultimap<K, V> build() {
if (keyComparator != null) {
Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>();
List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList(
builderMultimap.asMap().entrySet());
Collections.sort(
entries,
Ordering.from(keyComparator).onResultOf(new Function<Entry<K, Collection<V>>, K>() {
@Override
public K apply(Entry<K, Collection<V>> entry) {
return entry.getKey();
}
}));
for (Map.Entry<K, Collection<V>> entry : entries) {
sortedCopy.putAll(entry.getKey(), entry.getValue());
}
builderMultimap = sortedCopy;
}
return copyOf(builderMultimap, valueComparator);
}
}
/**
* Returns an immutable set multimap containing the same mappings as
* {@code multimap}. The generated multimap's key and value orderings
* correspond to the iteration ordering of the {@code multimap.asMap()} view.
* Repeated occurrences of an entry in the multimap after the first are
* ignored.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableSetMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
return copyOf(multimap, null);
}
private static <K, V> ImmutableSetMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap,
Comparator<? super V> valueComparator) {
checkNotNull(multimap); // eager for GWT
if (multimap.isEmpty() && valueComparator == null) {
return of();
}
if (multimap instanceof ImmutableSetMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableSetMultimap<K, V> kvMultimap
= (ImmutableSetMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
ImmutableMap.Builder<K, ImmutableSet<V>> builder = ImmutableMap.builder();
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
K key = entry.getKey();
Collection<? extends V> values = entry.getValue();
ImmutableSet<V> set = (valueComparator == null)
? ImmutableSet.copyOf(values)
: ImmutableSortedSet.copyOf(valueComparator, values);
if (!set.isEmpty()) {
builder.put(key, set);
size += set.size();
}
}
return new ImmutableSetMultimap<K, V>(
builder.build(), size, valueComparator);
}
// Returned by get() when values are sorted and a missing key is provided.
private final transient ImmutableSortedSet<V> emptySet;
ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size,
@Nullable Comparator<? super V> valueComparator) {
super(map, size);
this.emptySet = (valueComparator == null)
? null : ImmutableSortedSet.<V>emptySet(valueComparator);
}
// views
/**
* Returns an immutable set of the values for the given key. If no mappings
* in the multimap have the provided key, an empty immutable set is returned.
* The values are in the same order as the parameters used to build this
* multimap.
*/
@Override public ImmutableSet<V> get(@Nullable K key) {
// This cast is safe as its type is known in constructor.
ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
if (set != null) {
return set;
} else if (emptySet != null) {
return emptySet;
} else {
return ImmutableSet.<V>of();
}
}
private transient ImmutableSetMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a set multimap cannot contain multiple pairs with
* the same key and value, this method returns an {@code ImmutableSetMultimap}
* rather than the {@code ImmutableMultimap} specified in the {@code
* ImmutableMultimap} class.
*
* @since 11.0
*/
@Beta
public ImmutableSetMultimap<V, K> inverse() {
ImmutableSetMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableSetMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private transient ImmutableSet<Entry<K, V>> entries;
/**
* Returns an immutable collection of all key-value pairs in the multimap.
* Its iterator traverses the values for the first key, the values for the
* second key, and so on.
*/
// TODO(kevinb): Fix this so that two copies of the entries are not created.
@Override public ImmutableSet<Entry<K, V>> entries() {
ImmutableSet<Entry<K, V>> result = entries;
return (result == null)
? (entries = ImmutableSet.copyOf(super.entries()))
: result;
}
}
| 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) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets">
* {@code Sets}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Chris Povirk
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Sets {
private Sets() {}
/**
* {@link AbstractSet} substitute without the potentially-quadratic
* {@code removeAll} implementation.
*/
abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
@Override
public boolean removeAll(Collection<?> c) {
return removeAllImpl(this, c);
}
@Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(checkNotNull(c)); // GWT compatibility
}
}
/**
* Returns an immutable set instance containing the given enum elements.
* Internally, the returned set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration
* order, not the order in which the elements are provided to the method.
*
* @param anElement one of the elements the set should contain
* @param otherElements the rest of the elements the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
E anElement, E... otherElements) {
return new ImmutableEnumSet<E>(EnumSet.of(anElement, otherElements));
}
/**
* Returns an immutable set instance containing the given enum elements.
* Internally, the returned set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration
* order, not the order in which the elements appear in the given collection.
*
* @param elements the elements, all of the same {@code enum} type, that the
* set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
Iterable<E> elements) {
Iterator<E> iterator = elements.iterator();
if (!iterator.hasNext()) {
return ImmutableSet.of();
}
if (elements instanceof EnumSet) {
EnumSet<E> enumSetClone = EnumSet.copyOf((EnumSet<E>) elements);
return new ImmutableEnumSet<E>(enumSetClone);
}
E first = iterator.next();
EnumSet<E> set = EnumSet.of(first);
while (iterator.hasNext()) {
set.add(iterator.next());
}
return new ImmutableEnumSet<E>(set);
}
/**
* Returns a new {@code EnumSet} instance containing the given elements.
* Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an
* exception on an empty collection, and it may be called on any iterable, not
* just a {@code Collection}.
*/
public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable,
Class<E> elementType) {
/*
* TODO(cpovirk): noneOf() and addAll() will both throw
* NullPointerExceptions when appropriate. However, NullPointerTester will
* fail on this method because it passes in Class.class instead of an enum
* type. This means that, when iterable is null but elementType is not,
* noneOf() will throw a ClassCastException before addAll() has a chance to
* throw a NullPointerException. NullPointerTester considers this a failure.
* Ideally the test would be fixed, but it would require a special case for
* Class<E> where E extends Enum. Until that happens (if ever), leave
* checkNotNull() here. For now, contemplate the irony that checking
* elementType, the problem argument, is harmful, while checking iterable,
* the innocent bystander, is effective.
*/
checkNotNull(iterable);
EnumSet<E> set = EnumSet.noneOf(elementType);
Iterables.addAll(set, iterable);
return set;
}
// HashSet
/**
* Creates a <i>mutable</i>, empty {@code HashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSet#of()} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#noneOf} instead.
*
* @return a new, empty {@code HashSet}
*/
public static <E> HashSet<E> newHashSet() {
return new HashSet<E>();
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or
* {@link ImmutableSet#copyOf(Object[])} (for an array) instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#of(Enum, Enum[])} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(E... elements) {
HashSet<E> set = newHashSetWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a {@code HashSet} instance, with a high enough "initial capacity"
* that it <i>should</i> hold {@code expectedSize} elements without growth.
* This behavior cannot be broadly guaranteed, but it is observed to be true
* for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned set.
*
* @param expectedSize the number of elements you expect to add to the
* returned set
* @return a new, empty {@code HashSet} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
return new HashSet<E>(Maps.capacity(expectedSize));
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use
* {@link #newEnumSet(Iterable, Class)} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? new HashSet<E>(Collections2.cast(elements))
: newHashSet(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an
* {@link EnumSet} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
HashSet<E> set = newHashSet();
while (elements.hasNext()) {
set.add(elements.next());
}
return set;
}
// LinkedHashSet
/**
* Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSet#of()} instead.
*
* @return a new, empty {@code LinkedHashSet}
*/
public static <E> LinkedHashSet<E> newLinkedHashSet() {
return new LinkedHashSet<E>();
}
/**
* Creates a {@code LinkedHashSet} instance, with a high enough "initial
* capacity" that it <i>should</i> hold {@code expectedSize} elements without
* growth. This behavior cannot be broadly guaranteed, but it is observed to
* be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned set.
*
* @param expectedSize the number of elements you expect to add to the
* returned set
* @return a new, empty {@code LinkedHashSet} with enough capacity to hold
* {@code expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 11.0
*/
public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
int expectedSize) {
return new LinkedHashSet<E>(Maps.capacity(expectedSize));
}
/**
* Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the
* given elements in order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code LinkedHashSet} containing those elements (minus
* duplicates)
*/
public static <E> LinkedHashSet<E> newLinkedHashSet(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<E>(Collections2.cast(elements));
}
LinkedHashSet<E> set = newLinkedHashSet();
for (E element : elements) {
set.add(element);
}
return set;
}
// TreeSet
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the
* natural sort ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedSet#of()} instead.
*
* @return a new, empty {@code TreeSet}
*/
public static <E extends Comparable> TreeSet<E> newTreeSet() {
return new TreeSet<E>();
}
/**
* Creates a <i>mutable</i> {@code TreeSet} instance containing the given
* elements sorted by their natural ordering.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit
* comparator, this method has different behavior than
* {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with
* that comparator.
*
* @param elements the elements that the set should contain
* @return a new {@code TreeSet} containing those elements (minus duplicates)
*/
public static <E extends Comparable> TreeSet<E> newTreeSet(
Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
for (E element : elements) {
set.add(element);
}
return set;
}
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedSet.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to use to sort the set
* @return a new, empty {@code TreeSet}
* @throws NullPointerException if {@code comparator} is null
*/
public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
return new TreeSet<E>(checkNotNull(comparator));
}
/**
* Creates an empty {@code Set} that uses identity to determine equality. It
* compares object references, instead of calling {@code equals}, to
* determine whether a provided object matches an element in the set. For
* example, {@code contains} returns {@code false} when passed an object that
* equals a set member, but isn't the same instance. This behavior is similar
* to the way {@code IdentityHashMap} handles key lookups.
*
* @since 8.0
*/
public static <E> Set<E> newIdentityHashSet() {
return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
}
/**
* Creates an {@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.
*
* <p>Further, note that the current implementation is not suitable for nested
* {@code union} views, i.e. the following should be avoided when in a loop:
* {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
* set has a cubic complexity to the depth of the nesting.
*/
public static <E> SetView<E> union(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Set<? extends E> set2minus1 = difference(set2, set1);
return new SetView<E>() {
@Override public int size() {
return set1.size() + set2minus1.size();
}
@Override public boolean isEmpty() {
return set1.isEmpty() && set2.isEmpty();
}
@Override public Iterator<E> iterator() {
return Iterators.unmodifiableIterator(
Iterators.concat(set1.iterator(), set2minus1.iterator()));
}
@Override public boolean contains(Object object) {
return set1.contains(object) || set2.contains(object);
}
@Override public <S extends Set<E>> S copyInto(S set) {
set.addAll(set1);
set.addAll(set2);
return set;
}
@Override public ImmutableSet<E> immutableCopy() {
return new ImmutableSet.Builder<E>()
.addAll(set1).addAll(set2).build();
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the intersection of two sets. The
* returned set contains all elements that are contained by both backing sets.
* The iteration order of the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*
* <p><b>Note:</b> The returned view performs slightly better when {@code
* set1} is the smaller of the two sets. If you have reason to believe one of
* your sets will generally be smaller than the other, pass it first.
* Unfortunately, since this method sets the generic type of the returned set
* based on the type of the first set passed, this could in rare cases force
* you to make a cast, for example: <pre> {@code
*
* Set<Object> aFewBadObjects = ...
* Set<String> manyBadStrings = ...
*
* // impossible for a non-String to be in the intersection
* SuppressWarnings("unchecked")
* Set<String> badStrings = (Set) Sets.intersection(
* aFewBadObjects, manyBadStrings);}</pre>
*
* This is unfortunate, but should come up only very rarely.
*/
public static <E> SetView<E> intersection(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Predicate<Object> inSet2 = Predicates.in(set2);
return new SetView<E>() {
@Override public Iterator<E> iterator() {
return Iterators.filter(set1.iterator(), inSet2);
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean isEmpty() {
return !iterator().hasNext();
}
@Override public boolean contains(Object object) {
return set1.contains(object) && set2.contains(object);
}
@Override public boolean containsAll(Collection<?> collection) {
return set1.containsAll(collection)
&& set2.containsAll(collection);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the difference of two sets. The
* returned set contains all elements that are contained by {@code set1} and
* not contained by {@code set2}. {@code set2} may also contain elements not
* present in {@code set1}; these are simply ignored. The iteration order of
* the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*/
public static <E> SetView<E> difference(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
return new SetView<E>() {
@Override public Iterator<E> iterator() {
return Iterators.filter(set1.iterator(), notInSet2);
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean isEmpty() {
return set2.containsAll(set1);
}
@Override public boolean contains(Object element) {
return set1.contains(element) && !set2.contains(element);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the symmetric difference of two
* sets. The returned set contains all elements that are contained in either
* {@code set1} or {@code set2} but not in both. The iteration order of the
* returned set is undefined.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*
* @since 3.0
*/
public static <E> SetView<E> symmetricDifference(
Set<? extends E> set1, Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
// TODO(kevinb): Replace this with a more efficient implementation
return difference(union(set1, set2), intersection(set1, set2));
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* returned set is a live view of {@code unfiltered}; changes to one affect
* the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set's {@code add()} and {@code addAll()} methods throw
* an {@link IllegalArgumentException}. When methods such as {@code
* removeAll()} and {@code clear()} are called on the filtered set, only
* elements that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate
* across every element in the underlying set and determine which elements
* satisfy the filter. When a live view is <i>not</i> needed, it may be faster
* to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals. (See {@link Iterables#filter(Iterable, Class)} for related
* functionality.)
*/
// TODO(kevinb): how to omit that last sentence when building GWT javadoc?
public static <E> Set<E> filter(
Set<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof SortedSet) {
return filter((SortedSet<E>) unfiltered, predicate);
}
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredSet<E>(
(Set<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSet<E> extends FilteredCollection<E>
implements Set<E> {
FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override public boolean equals(@Nullable Object object) {
return equalsImpl(this, object);
}
@Override public int hashCode() {
return hashCodeImpl(this);
}
}
/**
* Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
* satisfy a predicate. The returned set is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set's {@code add()} and {@code addAll()} methods throw
* an {@link IllegalArgumentException}. When methods such as
* {@code removeAll()} and {@code clear()} are called on the filtered set,
* only elements that satisfy the filter will be removed from the underlying
* set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across
* every element in the underlying set and determine which elements satisfy
* the filter. When a live view is <i>not</i> needed, it may be faster to copy
* {@code Iterables.filter(unfiltered, predicate)} and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such as
* {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
* equals. (See {@link Iterables#filter(Iterable, Class)} for related
* functionality.)
*
* @since 11.0
*/
@SuppressWarnings("unchecked")
public static <E> SortedSet<E> filter(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredSortedSet<E>(
(SortedSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSortedSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSortedSet<E> extends FilteredCollection<E>
implements SortedSet<E> {
FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override public boolean equals(@Nullable Object object) {
return equalsImpl(this, object);
}
@Override public int hashCode() {
return hashCodeImpl(this);
}
@Override
public Comparator<? super E> comparator() {
return ((SortedSet<E>) unfiltered).comparator();
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement),
predicate);
}
@Override
public SortedSet<E> headSet(E toElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
}
@Override
public E first() {
return iterator().next();
}
@Override
public E last() {
SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
while (true) {
E element = sortedUnfiltered.last();
if (predicate.apply(element)) {
return element;
}
sortedUnfiltered = sortedUnfiltered.headSet(element);
}
}
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given sets in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example: <pre> {@code
*
* Sets.cartesianProduct(ImmutableList.of(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C")))}</pre>
*
* returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* The order in which these lists are returned is not guaranteed, however the
* position of an element inside a tuple always corresponds to the position of
* the set from which it came in the input list. Note that if any input set is
* empty, the Cartesian product will also be empty. If no sets at all are
* provided (an empty list), the resulting Cartesian product has one element,
* an empty list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size
* {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian set is constructed, the
* input sets are merely copied. Only as the resulting set is iterated are the
* individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that
* the elements chosen from those sets should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable set containing immutable
* lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets},
* or any element of a provided set is null
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(
List<? extends Set<? extends B>> sets) {
for (Set<? extends B> set : sets) {
if (set.isEmpty()) {
return ImmutableSet.of();
}
}
CartesianSet<B> cartesianSet = new CartesianSet<B>(sets);
return cartesianSet;
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given sets in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example: <pre> {@code
*
* Sets.cartesianProduct(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C"))}</pre>
*
* returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* The order in which these lists are returned is not guaranteed, however the
* position of an element inside a tuple always corresponds to the position of
* the set from which it came in the input list. Note that if any input set is
* empty, the Cartesian product will also be empty. If no sets at all are
* provided, the resulting Cartesian product has one element, an empty list
* (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size
* {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian set is constructed, the
* input sets are merely copied. Only as the resulting set is iterated are the
* individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that
* the elements chosen from those sets should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable set containing immutable
* lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets},
* or any element of a provided set is null
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(
Set<? extends B>... sets) {
return cartesianProduct(Arrays.asList(sets));
}
private static class CartesianSet<B> extends AbstractSet<List<B>> {
final ImmutableList<Axis> axes;
final int size;
CartesianSet(List<? extends Set<? extends B>> sets) {
int dividend = 1;
ImmutableList.Builder<Axis> builder = ImmutableList.builder();
try {
for (Set<? extends B> set : sets) {
Axis axis = new Axis(set, dividend);
builder.add(axis);
dividend = IntMath.checkedMultiply(dividend, axis.size());
}
} catch (ArithmeticException overflow) {
throw new IllegalArgumentException("cartesian product too big");
}
this.axes = builder.build();
size = dividend;
}
@Override public int size() {
return size;
}
@Override public UnmodifiableIterator<List<B>> iterator() {
return new AbstractIndexedListIterator<List<B>>(size) {
@Override
protected List<B> get(int index) {
Object[] tuple = new Object[axes.size()];
for (int i = 0 ; i < tuple.length; i++) {
tuple[i] = axes.get(i).getForIndex(index);
}
@SuppressWarnings("unchecked") // only B's are put in here
List<B> result = (ImmutableList<B>) ImmutableList.copyOf(tuple);
return result;
}
};
}
@Override public boolean contains(Object element) {
if (!(element instanceof List)) {
return false;
}
List<?> tuple = (List<?>) element;
int dimensions = axes.size();
if (tuple.size() != dimensions) {
return false;
}
for (int i = 0; i < dimensions; i++) {
if (!axes.get(i).contains(tuple.get(i))) {
return false;
}
}
return true;
}
@Override public boolean equals(@Nullable Object object) {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
if (object instanceof CartesianSet) {
CartesianSet<?> that = (CartesianSet<?>) object;
return this.axes.equals(that.axes);
}
return super.equals(object);
}
@Override public int hashCode() {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
// It's a weird formula, but tests prove it works.
int adjust = size - 1;
for (int i = 0; i < axes.size(); i++) {
adjust *= 31;
}
return axes.hashCode() + adjust;
}
private class Axis {
final ImmutableSet<? extends B> choices;
final ImmutableList<? extends B> choicesList;
final int dividend;
Axis(Set<? extends B> set, int dividend) {
choices = ImmutableSet.copyOf(set);
choicesList = choices.asList();
this.dividend = dividend;
}
int size() {
return choices.size();
}
B getForIndex(int index) {
return choicesList.get(index / dividend % size());
}
boolean contains(Object target) {
return choices.contains(target);
}
@Override public boolean equals(Object obj) {
if (obj instanceof CartesianSet.Axis) {
CartesianSet.Axis that = (CartesianSet.Axis) obj;
return this.choices.equals(that.choices);
// dividends must be equal or we wouldn't have gotten this far
}
return false;
}
@Override public int hashCode() {
// Because Axis instances are not exposed, we can
// opportunistically choose whatever bizarre formula happens
// to make CartesianSet.hashCode() as simple as possible.
return size / choices.size() * choices.hashCode();
}
}
}
/**
* Returns the set of all possible subsets of {@code set}. For example,
* {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
* {1}, {2}, {1, 2}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they
* appeared in the input set. The order in which these subsets appear in the
* outer set is undefined. Note that the power set of the empty set is not the
* empty set, but a one-element set containing the empty set.
*
* <p>The returned set and its constituent sets use {@code equals} to decide
* whether two elements are identical, even if the input set uses a different
* concept of equivalence.
*
* <p><i>Performance notes:</i> while the power set of a set with size {@code
* n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
* power set is constructed, the input set is merely copied. Only as the
* power set is iterated are the individual subsets created, and these subsets
* themselves occupy only a few bytes of memory regardless of their size.
*
* @param set the set of elements to construct a power set from
* @return the power set, as an immutable set of immutable sets
* @throws IllegalArgumentException if {@code set} has more than 30 unique
* elements (causing the power set size to exceed the {@code int} range)
* @throws NullPointerException if {@code set} is or contains {@code null}
* @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
* Wikipedia</a>
* @since 4.0
*/
@GwtCompatible(serializable = false)
public static <E> Set<Set<E>> powerSet(Set<E> set) {
ImmutableSet<E> input = ImmutableSet.copyOf(set);
checkArgument(input.size() <= 30,
"Too many elements to create power set: %s > 30", input.size());
return new PowerSet<E>(input);
}
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableSet<E> inputSet;
final ImmutableList<E> inputList;
final int powerSetSize;
PowerSet(ImmutableSet<E> input) {
this.inputSet = input;
this.inputList = input.asList();
this.powerSetSize = 1 << input.size();
}
@Override public int size() {
return powerSetSize;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Iterator<Set<E>> iterator() {
return new AbstractIndexedListIterator<Set<E>>(powerSetSize) {
@Override protected Set<E> get(final int setBits) {
return new AbstractSet<E>() {
@Override public int size() {
return Integer.bitCount(setBits);
}
@Override public Iterator<E> iterator() {
return new BitFilteredSetIterator<E>(inputList, setBits);
}
};
}
};
}
private static final class BitFilteredSetIterator<E>
extends UnmodifiableIterator<E> {
final ImmutableList<E> input;
int remainingSetBits;
BitFilteredSetIterator(ImmutableList<E> input, int allSetBits) {
this.input = input;
this.remainingSetBits = allSetBits;
}
@Override public boolean hasNext() {
return remainingSetBits != 0;
}
@Override public E next() {
int index = Integer.numberOfTrailingZeros(remainingSetBits);
if (index == 32) {
throw new NoSuchElementException();
}
int currentElementMask = 1 << index;
remainingSetBits &= ~currentElementMask;
return input.get(index);
}
}
@Override public boolean contains(@Nullable Object obj) {
if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
return inputSet.containsAll(set);
}
return false;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof PowerSet) {
PowerSet<?> that = (PowerSet<?>) obj;
return inputSet.equals(that.inputSet);
}
return super.equals(obj);
}
@Override public int hashCode() {
/*
* The sum of the sums of the hash codes in each subset is just the sum of
* each input element's hash code times the number of sets that element
* appears in. Each element appears in exactly half of the 2^n sets, so:
*/
return inputSet.hashCode() << (inputSet.size() - 1);
}
@Override public String toString() {
return "powerSet(" + inputSet + ")";
}
}
/**
* An implementation for {@link Set#hashCode()}.
*/
static int hashCodeImpl(Set<?> s) {
int hashCode = 0;
for (Object o : s) {
hashCode += o != null ? o.hashCode() : 0;
}
return hashCode;
}
/**
* An implementation for {@link Set#equals(Object)}.
*/
static boolean equalsImpl(Set<?> s, @Nullable Object object){
if (s == object) {
return true;
}
if (object instanceof Set) {
Set<?> o = (Set<?>) object;
try {
return s.size() == o.size() && s.containsAll(o);
} catch (NullPointerException ignored) {
return false;
} catch (ClassCastException ignored) {
return false;
}
}
return false;
}
/**
* Remove each element in an iterable from a set.
*/
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
boolean changed = false;
while (iterator.hasNext()) {
changed |= set.remove(iterator.next());
}
return changed;
}
static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
checkNotNull(collection); // for GWT
if (collection instanceof Multiset) {
collection = ((Multiset<?>) collection).elementSet();
}
/*
* AbstractSet.removeAll(List) has quadratic behavior if the list size
* is just less than the set's size. We augment the test by
* assuming that sets have fast contains() performance, and other
* collections don't. See
* http://code.google.com/p/guava-libraries/issues/detail?id=1013
*/
if (collection instanceof Set && collection.size() > set.size()) {
Iterator<?> setIterator = set.iterator();
boolean changed = false;
while (setIterator.hasNext()) {
if (collection.contains(setIterator.next())) {
changed = true;
setIterator.remove();
}
}
return changed;
} else {
return removeAllImpl(set, collection.iterator());
}
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> SortedSet<T> cast(Iterable<T> iterable) {
return (SortedSet<T>) iterable;
}
}
| Java |
/*
* Copyright (C) 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.RandomAccess;
import javax.annotation.Nullable;
/**
* GWT emulated version of {@link ImmutableList}.
* TODO(cpovirk): more doc
*
* @author Hayward Chan
*/
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableList<E> extends ImmutableCollection<E>
implements List<E>, RandomAccess {
ImmutableList() {}
// 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 non-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);
}
}
/**
* Views the array as an immutable list. The array must have only {@code E} elements.
*
* <p>The array must be internally created.
*/
@SuppressWarnings("unchecked") // caller is reponsible for getting this right
static <E> ImmutableList<E> asImmutableList(Object[] elements) {
return unsafeDelegateList((List) 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);
}
@Override
public int indexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.indexOfImpl(this, object);
}
@Override
public int lastIndexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
}
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();
}
@Override public UnmodifiableIterator<E> iterator() {
return listIterator();
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
return unsafeDelegateList(Lists.subListImpl(this, fromIndex, toIndex));
}
@Override public UnmodifiableListIterator<E> listIterator() {
return listIterator(0);
}
@Override public UnmodifiableListIterator<E> listIterator(int index) {
return new AbstractIndexedListIterator<E>(size(), index) {
@Override
protected E get(int index) {
return ImmutableList.this.get(index);
}
};
}
@Override public ImmutableList<E> asList() {
return this;
}
public ImmutableList<E> reverse() {
List<E> list = Lists.newArrayList(this);
Collections.reverse(list);
return unsafeDelegateList(list);
}
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) 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;
/**
* GWT emulation of {@link RegularImmutableBiMap}.
*
* @author Jared Levy
* @author Hayward Chan
*/
@SuppressWarnings("serial")
class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
// This reference is used both by the GWT compiler to infer the elements
// of the lists that needs to be serialized.
private ImmutableBiMap<V, K> inverse;
RegularImmutableBiMap(ImmutableMap<K, V> delegate) {
super(delegate);
ImmutableMap.Builder<V, K> builder = ImmutableMap.builder();
for (Entry<K, V> entry : delegate.entrySet()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableMap<V, K> backwardMap = builder.build();
this.inverse = new RegularImmutableBiMap<V, K>(backwardMap, this);
}
RegularImmutableBiMap(ImmutableMap<K, V> delegate,
ImmutableBiMap<V, K> inverse) {
super(delegate);
this.inverse = inverse;
}
@Override public ImmutableBiMap<V, K> inverse() {
return inverse;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code entrySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
ImmutableMapEntrySet() {}
abstract ImmutableMap<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public boolean contains(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
V value = map().get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
return false;
}
@Override
boolean isPartialView() {
return map().isPartialView();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link List} instances. Also see this
* class's counterparts {@link Sets}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists">
* {@code Lists}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Lists {
private Lists() {}
// ArrayList
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableList#of()} instead.
*
* @return a new, empty {@code ArrayList}
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableList#of()} (for varargs) or
* {@link ImmutableList#copyOf(Object[])} (for an array) instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements); // for GWT
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@VisibleForTesting static int computeArrayListCapacity(int arraySize) {
checkArgument(arraySize >= 0);
// TODO(kevinb): Figure out the right behavior, and document it
return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
checkNotNull(elements); // for GWT
ArrayList<E> list = newArrayList();
while (elements.hasNext()) {
list.add(elements.next());
}
return list;
}
/**
* Creates an {@code ArrayList} instance backed by an array of the
* <i>exact</i> size specified; equivalent to
* {@link ArrayList#ArrayList(int)}.
*
* <p><b>Note:</b> if you know the exact size your list will be, consider
* using a fixed-size list ({@link Arrays#asList(Object[])}) or an {@link
* ImmutableList} instead of a growable {@link ArrayList}.
*
* <p><b>Note:</b> If you have only an <i>estimate</i> of the eventual size of
* the list, consider padding this estimate by a suitable amount, or simply
* use {@link #newArrayListWithExpectedSize(int)} instead.
*
* @param initialArraySize the exact size of the initial backing array for
* the returned array list ({@code ArrayList} documentation calls this
* value the "capacity")
* @return a new, empty {@code ArrayList} which is guaranteed not to resize
* itself unless its size reaches {@code initialArraySize + 1}
* @throws IllegalArgumentException if {@code initialArraySize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithCapacity(
int initialArraySize) {
checkArgument(initialArraySize >= 0); // for GWT.
return new ArrayList<E>(initialArraySize);
}
/**
* Creates an {@code ArrayList} instance sized appropriately to hold an
* <i>estimated</i> number of elements without resizing. A small amount of
* padding is added in case the estimate is low.
*
* <p><b>Note:</b> If you know the <i>exact</i> number of elements the list
* will hold, or prefer to calculate your own amount of padding, refer to
* {@link #newArrayListWithCapacity(int)}.
*
* @param estimatedSize an estimate of the eventual {@link List#size()} of
* the new list
* @return a new, empty {@code ArrayList}, sized appropriately to hold the
* estimated number of elements
* @throws IllegalArgumentException if {@code estimatedSize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithExpectedSize(
int estimatedSize) {
return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
}
// LinkedList
/**
* Creates an empty {@code LinkedList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use
* {@link ImmutableList#of()} instead.
*
* @return a new, empty {@code LinkedList}
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList() {
return new LinkedList<E>();
}
/**
* Creates a {@code LinkedList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code LinkedList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList(
Iterable<? extends E> elements) {
LinkedList<E> list = newLinkedList();
for (E element : elements) {
list.add(element);
}
return list;
}
/**
* Returns an unmodifiable list containing the specified first element and
* backed by the specified array of additional elements. Changes to the {@code
* rest} array will be reflected in the returned list. Unlike {@link
* Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload
* ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(@Nullable E first, E[] rest) {
return new OnePlusArrayList<E>(first, rest);
}
/** @see Lists#asList(Object, Object[]) */
private static class OnePlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E[] rest;
OnePlusArrayList(@Nullable E first, E[] rest) {
this.first = first;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 1;
}
@Override public E get(int index) {
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return (index == 0) ? first : rest[index - 1];
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable list containing the specified first and second
* element, and backed by the specified array of additional elements. Changes
* to the {@code rest} array will be reflected in the returned list. Unlike
* {@link Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid
* overload ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param second the second element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(
@Nullable E first, @Nullable E second, E[] rest) {
return new TwoPlusArrayList<E>(first, second, rest);
}
/** @see Lists#asList(Object, Object, Object[]) */
private static class TwoPlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E second;
final E[] rest;
TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
this.first = first;
this.second = second;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 2;
}
@Override public E get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return rest[index - 2];
}
}
private static final long serialVersionUID = 0;
}
/**
* Returns a list that applies {@code function} to each element of {@code
* fromList}. The returned list is a transformed view of {@code fromList};
* changes to {@code fromList} will be reflected in the returned list and vice
* versa.
*
* <p>Since functions are not reversible, the transform is one-way and new
* items cannot be stored in the returned list. The {@code add},
* {@code addAll} and {@code set} methods are unsupported in the returned
* list.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned list to be a view, but it means that the function will be
* applied many times for bulk operations like {@link List#contains} and
* {@link List#hashCode}. For this to perform well, {@code function} should be
* fast. To avoid lazy evaluation when the returned list doesn't need to be a
* view, copy the returned list into a new list of your choosing.
*
* <p>If {@code fromList} implements {@link RandomAccess}, so will the
* returned list. The returned list is threadsafe if the supplied list and
* function are.
*
* <p>If only a {@code Collection} or {@code Iterable} input is available, use
* {@link Collections2#transform} or {@link Iterables#transform}.
*
* <p><b>Note:</b> serializing the returned list is implemented by serializing
* {@code fromList}, its contents, and {@code function} -- <i>not</i> by
* serializing the transformed values. This can lead to surprising behavior,
* so serializing the returned list is <b>not recommended</b>. Instead,
* copy the list using {@link ImmutableList#copyOf(Collection)} (for example),
* then serialize the copy. Other methods similar to this do not implement
* serialization at all for this reason.
*/
public static <F, T> List<T> transform(
List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<F, T>(fromList, function)
: new TransformingSequentialList<F, T>(fromList, function);
}
/**
* Implementation of a sequential transforming list.
*
* @see Lists#transform
*/
private static class TransformingSequentialList<F, T>
extends AbstractSequentialList<T> implements Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingSequentialList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
/**
* The default implementation inherited is based on iteration and removal of
* each element which can be overkill. That's why we forward this call
* directly to the backing list.
*/
@Override public void clear() {
fromList.clear();
}
@Override public int size() {
return fromList.size();
}
@Override public ListIterator<T> listIterator(final int index) {
final ListIterator<F> delegate = fromList.listIterator(index);
return new ListIterator<T>() {
@Override
public void add(T e) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public boolean hasPrevious() {
return delegate.hasPrevious();
}
@Override
public T next() {
return function.apply(delegate.next());
}
@Override
public int nextIndex() {
return delegate.nextIndex();
}
@Override
public T previous() {
return function.apply(delegate.previous());
}
@Override
public int previousIndex() {
return delegate.previousIndex();
}
@Override
public void remove() {
delegate.remove();
}
@Override
public void set(T e) {
throw new UnsupportedOperationException("not supported");
}
};
}
private static final long serialVersionUID = 0;
}
/**
* Implementation of a transforming random access list. We try to make as many
* of these methods pass-through to the source list as possible so that the
* performance characteristics of the source list and transformed list are
* similar.
*
* @see Lists#transform
*/
private static class TransformingRandomAccessList<F, T>
extends AbstractList<T> implements RandomAccess, Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingRandomAccessList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
@Override public void clear() {
fromList.clear();
}
@Override public T get(int index) {
return function.apply(fromList.get(index));
}
@Override public boolean isEmpty() {
return fromList.isEmpty();
}
@Override public T remove(int index) {
return function.apply(fromList.remove(index));
}
@Override public int size() {
return fromList.size();
}
private static final long serialVersionUID = 0;
}
/**
* Returns consecutive {@linkplain List#subList(int, int) sublists} of a list,
* each of the same size (the final list may be smaller). For example,
* partitioning a list containing {@code [a, b, c, d, e]} with a partition
* size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
* two inner lists of three and two elements, all in the original order.
*
* <p>The outer list is unmodifiable, but reflects the latest state of the
* source list. The inner lists are sublist views of the original list,
* produced on demand using {@link List#subList(int, int)}, and are subject
* to all the usual caveats about modification as explained in that API.
*
* @param list the list to return consecutive sublists of
* @param size the desired size of each sublist (the last may be
* smaller)
* @return a list of consecutive sublists
* @throws IllegalArgumentException if {@code partitionSize} is nonpositive
*/
public static <T> List<List<T>> partition(List<T> list, int size) {
checkNotNull(list);
checkArgument(size > 0);
return (list instanceof RandomAccess)
? new RandomAccessPartition<T>(list, size)
: new Partition<T>(list, size);
}
private static class Partition<T> extends AbstractList<List<T>> {
final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
@Override public List<T> get(int index) {
int listSize = size();
checkElementIndex(index, listSize);
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override public int size() {
// TODO(user): refactor to common.math.IntMath.divide
int result = list.size() / size;
if (result * size != list.size()) {
result++;
}
return result;
}
@Override public boolean isEmpty() {
return list.isEmpty();
}
}
private static class RandomAccessPartition<T> extends Partition<T>
implements RandomAccess {
RandomAccessPartition(List<T> list, int size) {
super(list, size);
}
}
/**
* Returns a view of the specified string as an immutable list of {@code
* Character} values.
*
* @since 7.0
*/
@Beta public static ImmutableList<Character> charactersOf(String string) {
return new StringAsImmutableList(checkNotNull(string));
}
@SuppressWarnings("serial") // serialized using ImmutableList serialization
private static final class StringAsImmutableList
extends ImmutableList<Character> {
private final String string;
StringAsImmutableList(String string) {
this.string = string;
}
@Override public int indexOf(@Nullable Object object) {
return (object instanceof Character)
? string.indexOf((Character) object) : -1;
}
@Override public int lastIndexOf(@Nullable Object object) {
return (object instanceof Character)
? string.lastIndexOf((Character) object) : -1;
}
@Override public ImmutableList<Character> subList(
int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(string.substring(fromIndex, toIndex));
}
@Override boolean isPartialView() {
return false;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return string.charAt(index);
}
@Override public int size() {
return string.length();
}
@Override public boolean equals(@Nullable Object obj) {
if (!(obj instanceof List)) {
return false;
}
List<?> list = (List<?>) obj;
int n = string.length();
if (n != list.size()) {
return false;
}
Iterator<?> iterator = list.iterator();
for (int i = 0; i < n; i++) {
Object elem = iterator.next();
if (!(elem instanceof Character)
|| ((Character) elem).charValue() != string.charAt(i)) {
return false;
}
}
return true;
}
int hash = 0;
@Override public int hashCode() {
int h = hash;
if (h == 0) {
h = 1;
for (int i = 0; i < string.length(); i++) {
h = h * 31 + string.charAt(i);
}
hash = h;
}
return h;
}
}
/**
* Returns a view of the specified {@code CharSequence} as a {@code
* List<Character>}, viewing {@code sequence} as a sequence of Unicode code
* units. The view does not support any modification operations, but reflects
* any changes to the underlying character sequence.
*
* @param sequence the character sequence to view as a {@code List} of
* characters
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
@Beta public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
private static final class CharSequenceAsList
extends AbstractList<Character> {
private final CharSequence sequence;
CharSequenceAsList(CharSequence sequence) {
this.sequence = sequence;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return sequence.charAt(index);
}
@Override public boolean contains(@Nullable Object o) {
return indexOf(o) >= 0;
}
@Override public int indexOf(@Nullable Object o) {
if (o instanceof Character) {
char c = (Character) o;
for (int i = 0; i < sequence.length(); i++) {
if (sequence.charAt(i) == c) {
return i;
}
}
}
return -1;
}
@Override public int lastIndexOf(@Nullable Object o) {
if (o instanceof Character) {
char c = ((Character) o).charValue();
for (int i = sequence.length() - 1; i >= 0; i--) {
if (sequence.charAt(i) == c) {
return i;
}
}
}
return -1;
}
@Override public int size() {
return sequence.length();
}
@Override public List<Character> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(sequence.subSequence(fromIndex, toIndex));
}
@Override public int hashCode() {
int hash = 1;
for (int i = 0; i < sequence.length(); i++) {
hash = hash * 31 + sequence.charAt(i);
}
return hash;
}
@Override public boolean equals(@Nullable Object o) {
if (!(o instanceof List)) {
return false;
}
List<?> list = (List<?>) o;
int n = sequence.length();
if (n != list.size()) {
return false;
}
Iterator<?> iterator = list.iterator();
for (int i = 0; i < n; i++) {
Object elem = iterator.next();
if (!(elem instanceof Character)
|| ((Character) elem).charValue() != sequence.charAt(i)) {
return false;
}
}
return true;
}
}
/**
* Returns a reversed view of the specified list. For example, {@code
* Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
* 2, 1}. The returned list is backed by this list, so changes in the returned
* list are reflected in this list, and vice-versa. The returned list supports
* all of the optional list operations supported by this list.
*
* <p>The returned list is random-access if the specified list is random
* access.
*
* @since 7.0
*/
public static <T> List<T> reverse(List<T> list) {
if (list instanceof ReverseList) {
return ((ReverseList<T>) list).getForwardList();
} else if (list instanceof RandomAccess) {
return new RandomAccessReverseList<T>(list);
} else {
return new ReverseList<T>(list);
}
}
private static class ReverseList<T> extends AbstractList<T> {
private final List<T> forwardList;
ReverseList(List<T> forwardList) {
this.forwardList = checkNotNull(forwardList);
}
List<T> getForwardList() {
return forwardList;
}
private int reverseIndex(int index) {
int size = size();
checkElementIndex(index, size);
return (size - 1) - index;
}
private int reversePosition(int index) {
int size = size();
checkPositionIndex(index, size);
return size - index;
}
@Override public void add(int index, @Nullable T element) {
forwardList.add(reversePosition(index), element);
}
@Override public void clear() {
forwardList.clear();
}
@Override public T remove(int index) {
return forwardList.remove(reverseIndex(index));
}
@Override protected void removeRange(int fromIndex, int toIndex) {
subList(fromIndex, toIndex).clear();
}
@Override public T set(int index, @Nullable T element) {
return forwardList.set(reverseIndex(index), element);
}
@Override public T get(int index) {
return forwardList.get(reverseIndex(index));
}
@Override public boolean isEmpty() {
return forwardList.isEmpty();
}
@Override public int size() {
return forwardList.size();
}
@Override public boolean contains(@Nullable Object o) {
return forwardList.contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return forwardList.containsAll(c);
}
@Override public List<T> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
return reverse(forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)));
}
@Override public int indexOf(@Nullable Object o) {
int index = forwardList.lastIndexOf(o);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public int lastIndexOf(@Nullable Object o) {
int index = forwardList.indexOf(o);
return (index >= 0) ? reverseIndex(index) : -1;
}
@Override public Iterator<T> iterator() {
return listIterator();
}
@Override public ListIterator<T> listIterator(int index) {
int start = reversePosition(index);
final ListIterator<T> forwardIterator = forwardList.listIterator(start);
return new ListIterator<T>() {
boolean canRemove;
boolean canSet;
@Override public void add(T e) {
forwardIterator.add(e);
forwardIterator.previous();
canSet = canRemove = false;
}
@Override public boolean hasNext() {
return forwardIterator.hasPrevious();
}
@Override public boolean hasPrevious() {
return forwardIterator.hasNext();
}
@Override public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
canSet = canRemove = true;
return forwardIterator.previous();
}
@Override public int nextIndex() {
return reversePosition(forwardIterator.nextIndex());
}
@Override public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
canSet = canRemove = true;
return forwardIterator.next();
}
@Override public int previousIndex() {
return nextIndex() - 1;
}
@Override public void remove() {
checkState(canRemove);
forwardIterator.remove();
canRemove = canSet = false;
}
@Override public void set(T e) {
checkState(canSet);
forwardIterator.set(e);
}
};
}
}
private static class RandomAccessReverseList<T> extends ReverseList<T>
implements RandomAccess {
RandomAccessReverseList(List<T> forwardList) {
super(forwardList);
}
}
/**
* An implementation of {@link List#hashCode()}.
*/
static int hashCodeImpl(List<?> list){
int hashCode = 1;
for (Object o : list) {
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
}
return hashCode;
}
/**
* An implementation of {@link List#equals(Object)}.
*/
static boolean equalsImpl(List<?> list, @Nullable Object object) {
if (object == checkNotNull(list)) {
return true;
}
if (!(object instanceof List)) {
return false;
}
List<?> o = (List<?>) object;
return list.size() == o.size()
&& Iterators.elementsEqual(list.iterator(), o.iterator());
}
/**
* An implementation of {@link List#addAll(int, Collection)}.
*/
static <E> boolean addAllImpl(
List<E> list, int index, Iterable<? extends E> elements) {
boolean changed = false;
ListIterator<E> listIterator = list.listIterator(index);
for (E e : elements) {
listIterator.add(e);
changed = true;
}
return changed;
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element){
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element){
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
/**
* Returns an implementation of {@link List#listIterator(int)}.
*/
static <E> ListIterator<E> listIteratorImpl(List<E> list, int index) {
return new AbstractListWrapper<E>(list).listIterator(index);
}
/**
* An implementation of {@link List#subList(int, int)}.
*/
static <E> List<E> subListImpl(
final List<E> list, int fromIndex, int toIndex) {
List<E> wrapper;
if (list instanceof RandomAccess) {
wrapper = new RandomAccessListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
} else {
wrapper = new AbstractListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
}
private static class AbstractListWrapper<E> extends AbstractList<E> {
final List<E> backingList;
AbstractListWrapper(List<E> backingList) {
this.backingList = checkNotNull(backingList);
}
@Override public void add(int index, E element) {
backingList.add(index, element);
}
@Override public boolean addAll(int index, Collection<? extends E> c) {
return backingList.addAll(index, c);
}
@Override public E get(int index) {
return backingList.get(index);
}
@Override public E remove(int index) {
return backingList.remove(index);
}
@Override public E set(int index, E element) {
return backingList.set(index, element);
}
@Override public boolean contains(Object o) {
return backingList.contains(o);
}
@Override public int size() {
return backingList.size();
}
}
private static class RandomAccessListWrapper<E>
extends AbstractListWrapper<E> implements RandomAccess {
RandomAccessListWrapper(List<E> backingList) {
super(backingList);
}
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> List<T> cast(Iterable<T> iterable) {
return (List<T>) iterable;
}
}
| Java |
/*
* Copyright (C) 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
@Override
public ImmutableListMultimap<V, K> inverse() {
ImmutableListMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableListMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableListMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableList<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableList<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
}
| 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 3 methods to show that values may be null (but not keys)
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override public V put(K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(K key, @Nullable V value) {
return super.forcePut(key, value);
}
/** Returns the associated key type. */
public Class<K> keyType() {
return keyType;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.gwt.core.client.GwtScriptOnly;
import com.google.gwt.lang.Array;
/**
* Version of {@link GwtPlatform} used in web-mode. It includes methods in
* {@link Platform} that requires different implementions in web mode and
* hosted mode. It is factored out from {@link Platform} because <code>
* {@literal @}GwtScriptOnly</code> only supports public classes and methods.
*
* @author Hayward Chan
*/
@GwtCompatible
@GwtScriptOnly
public final class GwtPlatform {
private GwtPlatform() {}
public static <T> T[] clone(T[] array) {
return (T[]) Array.clone(array);
}
public static <T> T[] newArray(T[] reference, int length) {
return Array.createFrom(reference, length);
}
}
| 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.Collection;
import javax.annotation.Nullable;
/**
* A GWT-only class only used by GWT emulations. It is used to consolidate the
* definitions of method delegation to save code size.
*
* @author Hayward Chan
*/
// TODO: Make this class GWT serializable.
class ForwardingImmutableCollection<E> extends ImmutableCollection<E> {
transient final Collection<E> delegate;
ForwardingImmutableCollection(Collection<E> delegate) {
this.delegate = delegate;
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override public boolean contains(@Nullable Object object) {
return object != null && delegate.contains(object);
}
@Override public boolean containsAll(Collection<?> targets) {
return delegate.containsAll(targets);
}
public int size() {
return delegate.size();
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public Object[] toArray() {
return delegate.toArray();
}
@Override public <T> T[] toArray(T[] other) {
return delegate.toArray(other);
}
@Override public String toString() {
return delegate.toString();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.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.SortedSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link Map} instances (including instances of
* {@link SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts
* {@link Lists}, {@link Sets} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Maps">
* {@code Maps}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Isaac Shum
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Maps {
private Maps() {}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
* #newEnumMap} instead.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity"
* that it <i>should</i> hold {@code expectedSize} elements without growth.
* This behavior cannot be broadly guaranteed, but it is observed to be true
* for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of elements you expect to add to the
* returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
int expectedSize) {
return new HashMap<K, V>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as
* long as it grows no larger than expectedSize and the load factor is >= its
* default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkArgument(expectedSize >= 0);
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
return expectedSize + expectedSize / 3;
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as
* the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link
* #newEnumMap} instead.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code
* map}
*/
public static <K, V> HashMap<K, V> newHashMap(
Map<? extends K, ? extends V> map) {
return new HashMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap}
* instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
/**
* Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance
* with the same mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from
* {@code map}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(
Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
}
/**
* Returns a general-purpose instance of {@code ConcurrentMap}, which supports
* all optional operations of the ConcurrentMap interface. It does not permit
* null keys or values. It is serializable.
*
* <p>This is currently accomplished by calling {@link MapMaker#makeMap()}.
*
* <p>It is preferable to use {@code MapMaker} directly (rather than through
* this method), as it presents numerous useful configuration options,
* such as the concurrency level, load factor, key/value reference types,
* and value computation.
*
* @return a new, empty {@code ConcurrentMap}
* @since 3.0
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new MapMaker().<K, V>makeMap();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural
* ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#of()} instead.
*
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
/**
* Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as
* the specified map and using the same ordering as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
* @param map the sorted map whose mappings are to be placed in the new map
* and whose comparator is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code
* map} and using the comparator of {@code map}
*/
public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
return new TreeMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(
@Nullable Comparator<C> comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator<Class<?>> comparator = null;
// Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
return new TreeMap<K, V>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
return new EnumMap<K, V>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code
* map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(
Map<K, ? extends V> map) {
return new EnumMap<K, V>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<K, V>();
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* <p><b>Note:</b>If you only need to know whether two maps have the same
* mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
@SuppressWarnings("unchecked")
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
SortedMapDifference<K, V> result = difference(sortedLeft, right);
return result;
}
return difference(left, right, Equivalence.equals());
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Values are compared using a provided equivalence, in the case of
* equality, the value on the 'left' is returned in the difference.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @param valueEquivalence the equivalence relationship to use to compare
* values
* @return the difference between the two maps
* @since 10.0
*/
@Beta
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newHashMap();
Map<K, V> onlyOnRight = new HashMap<K, V>(right); // will whittle it down
Map<K, V> onBoth = newHashMap();
Map<K, MapDifference.ValueDifference<V>> differences = newHashMap();
boolean eq = true;
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
eq = false;
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
eq = false;
onlyOnLeft.put(leftKey, leftValue);
}
}
boolean areEqual = eq && onlyOnRight.isEmpty();
return mapDifference(
areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> MapDifference<K, V> mapDifference(boolean areEqual,
Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
return new MapDifferenceImpl<K, V>(areEqual,
Collections.unmodifiableMap(onlyOnLeft),
Collections.unmodifiableMap(onlyOnRight),
Collections.unmodifiableMap(onBoth),
Collections.unmodifiableMap(differences));
}
static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
final boolean areEqual;
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(boolean areEqual, Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.areEqual = areEqual;
this.onlyOnLeft = onlyOnLeft;
this.onlyOnRight = onlyOnRight;
this.onBoth = onBoth;
this.differences = differences;
}
@Override
public boolean areEqual() {
return areEqual;
}
@Override
public Map<K, V> entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map<K, V> entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map<K, V> entriesInCommon() {
return onBoth;
}
@Override
public Map<K, ValueDifference<V>> entriesDiffering() {
return differences;
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference<?, ?> other = (MapDifference<?, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(),
entriesInCommon(), entriesDiffering());
}
@Override public String toString() {
if (areEqual) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl<V>
implements MapDifference.ValueDifference<V> {
private final V left;
private final V right;
static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) {
return new ValueDifferenceImpl<V>(left, right);
}
private ValueDifferenceImpl(@Nullable V left, @Nullable V right) {
this.left = left;
this.right = right;
}
@Override
public V leftValue() {
return left;
}
@Override
public V rightValue() {
return right;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof MapDifference.ValueDifference) {
MapDifference.ValueDifference<?> that =
(MapDifference.ValueDifference<?>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(left, right);
}
@Override public String toString() {
return "(" + left + ", " + right + ")";
}
}
/**
* Computes the difference between two sorted maps, using the comparator of
* the left map, or {@code Ordering.natural()} if the left map uses the
* natural ordering of its elements. This difference is an immutable snapshot
* of the state of the maps at the time this method is called. It will never
* change, even if the maps change at a later time.
*
* <p>Since this method uses {@code TreeMap} instances internally, the keys of
* the right map must all compare as distinct according to the comparator
* of the left map.
*
* <p><b>Note:</b>If you only need to know whether two sorted maps have the
* same mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
public static <K, V> SortedMapDifference<K, V> difference(
SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator<? super K> comparator = orNaturalOrder(left.comparator());
SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences =
Maps.newTreeMap(comparator);
boolean eq = true;
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (Objects.equal(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
eq = false;
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
eq = false;
onlyOnLeft.put(leftKey, leftValue);
}
}
boolean areEqual = eq && onlyOnRight.isEmpty();
return sortedMapDifference(
areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> SortedMapDifference<K, V> sortedMapDifference(
boolean areEqual, SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight,
SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) {
return new SortedMapDifferenceImpl<K, V>(areEqual,
Collections.unmodifiableSortedMap(onlyOnLeft),
Collections.unmodifiableSortedMap(onlyOnRight),
Collections.unmodifiableSortedMap(onBoth),
Collections.unmodifiableSortedMap(differences));
}
static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(boolean areEqual, SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(areEqual, onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override public SortedMap<K, ValueDifference<V>> entriesDiffering() {
return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
}
@Override public SortedMap<K, V> entriesInCommon() {
return (SortedMap<K, V>) super.entriesInCommon();
}
@Override public SortedMap<K, V> entriesOnlyOnLeft() {
return (SortedMap<K, V>) super.entriesOnlyOnLeft();
}
@Override public SortedMap<K, V> entriesOnlyOnRight() {
return (SortedMap<K, V>) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code
* Ordering.natural()}. This method is an abomination of generics; the only
* purpose of this method is to contain the ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static <E> Comparator<? super E> orNaturalOrder(
@Nullable Comparator<? super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator<E>) Ordering.natural();
}
/**
* Returns a view of the set as a map, mapping keys from the set according to
* the specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map
* does not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also
* of type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
public static <K, V> Map<K, V> asMap(
Set<K> set, Function<? super K, V> function) {
if (set instanceof SortedSet) {
return asMap((SortedSet<K>) set, function);
} else {
return new AsMapView<K, V>(set, function);
}
}
/**
* Returns a view of the sorted set as a map, mapping keys from the set
* according to the specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map does
* not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
public static <K, V> SortedMap<K, V> asMap(
SortedSet<K> set, Function<? super K, V> function) {
return Platform.mapsAsMapSortedSet(set, function);
}
static <K, V> SortedMap<K, V> asMapSortedIgnoreNavigable(SortedSet<K> set,
Function<? super K, V> function) {
return new SortedAsMapView<K, V>(set, function);
}
private static class AsMapView<K, V> extends ImprovedAbstractMap<K, V> {
private final Set<K> set;
final Function<? super K, V> function;
Set<K> backingSet() {
return set;
}
AsMapView(Set<K> set, Function<? super K, V> function) {
this.set = checkNotNull(set);
this.function = checkNotNull(function);
}
@Override
public Set<K> keySet() {
// probably not worth caching
return removeOnlySet(backingSet());
}
@Override
public Collection<V> values() {
// probably not worth caching
return Collections2.transform(set, function);
}
@Override
public int size() {
return backingSet().size();
}
@Override
public boolean containsKey(@Nullable Object key) {
return backingSet().contains(key);
}
@Override
public V get(@Nullable Object key) {
if (backingSet().contains(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public V remove(@Nullable Object key) {
if (backingSet().remove(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
backingSet().clear();
}
protected Entry<K, V> entry(K key) {
return immutableEntry(key, function.apply(key));
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet<K, V>() {
@Override
Map<K, V> map() {
return AsMapView.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
final Iterator<K> backingIterator = backingSet().iterator();
return new Iterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public Entry<K, V> next() {
return entry(backingIterator.next());
}
@Override
public void remove() {
backingIterator.remove();
}
};
}
};
}
}
private static class SortedAsMapView<K, V> extends AsMapView<K, V>
implements SortedMap<K, V> {
SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) {
super(set, function);
}
@Override
SortedSet<K> backingSet() {
return (SortedSet<K>) super.backingSet();
}
@Override
public Comparator<? super K> comparator() {
return backingSet().comparator();
}
@Override
public Set<K> keySet() {
return removeOnlySortedSet(backingSet());
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return asMap(backingSet().subSet(fromKey, toKey), function);
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return asMap(backingSet().headSet(toKey), function);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return asMap(backingSet().tailSet(fromKey), function);
}
@Override
public K firstKey() {
return backingSet().first();
}
@Override
public K lastKey() {
return backingSet().last();
}
}
private static <E> Set<E> removeOnlySet(final Set<E> set) {
return new ForwardingSet<E>() {
@Override
protected Set<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
};
}
private static <E> SortedSet<E> removeOnlySortedSet(final SortedSet<E> set) {
return new ForwardingSortedSet<E>() {
@Override
protected SortedSet<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
};
}
/**
* Returns an immutable map for which the given {@code keys} are mapped to
* values by the given function in the order they appear in the original
* iterable. If {@code keys} contains duplicate elements, the returned map
* will contain each distinct key once in the order it first appears in
* {@code keys}.
*
* @throws NullPointerException if any element of {@code keys} is
* {@code null}, or if {@code valueFunction} produces {@code null}
* for any key
* @since 14.0
*/
@Beta
public static <K, V> ImmutableMap<K, V> toMap(Iterable<K> keys,
Function<? super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map for which the given {@code keys} are mapped to
* values by the given function in the order they appear in the original
* iterator. If {@code keys} contains duplicate elements, the returned map
* will contain each distinct key once in the order it first appears in
* {@code keys}.
*
* @throws NullPointerException if any element of {@code keys} is
* {@code null}, or if {@code valueFunction} produces {@code null}
* for any key
* @since 14.0
*/
@Beta
public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys,
Function<? super K, V> valueFunction) {
checkNotNull(valueFunction);
// Using LHM instead of a builder so as not to fail on duplicate keys
Map<K, V> builder = newLinkedHashMap();
while (keys.hasNext()) {
K key = keys.next();
builder.put(key, valueFunction.apply(key));
}
return ImmutableMap.copyOf(builder);
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
* @since 10.0
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
/**
* Returns an immutable map entry with the specified key and value. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException}.
*
* <p>The returned entry is serializable.
*
* @param key the key to be associated with the returned entry
* @param value the value to be associated with the returned entry
*/
@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(
@Nullable K key, @Nullable V value) {
return new ImmutableEntry<K, V>(key, value);
}
/**
* Returns an unmodifiable view of the specified set of entries. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException},
* as do any operations that would modify the returned set.
*
* @param entrySet the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
static <K, V> Set<Entry<K, V>> unmodifiableEntrySet(
Set<Entry<K, V>> entrySet) {
return new UnmodifiableEntrySet<K, V>(
Collections.unmodifiableSet(entrySet));
}
/**
* Returns an unmodifiable view of the specified map entry. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException}.
* This also has the side-effect of redefining {@code equals} to comply with
* the Entry contract, to avoid a possible nefarious implementation of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
static <K, V> Entry<K, V> unmodifiableEntry(final Entry<K, V> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V getValue() {
return entry.getValue();
}
};
}
/** @see Multimaps#unmodifiableEntries */
static class UnmodifiableEntries<K, V>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
UnmodifiableEntries(Collection<Entry<K, V>> entries) {
this.entries = entries;
}
@Override protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> delegate = super.iterator();
return new ForwardingIterator<Entry<K, V>>() {
@Override public Entry<K, V> next() {
return unmodifiableEntry(super.next());
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
@Override protected Iterator<Entry<K, V>> delegate() {
return delegate;
}
};
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean add(Entry<K, V> element) {
throw new UnsupportedOperationException();
}
@Override public boolean addAll(
Collection<? extends Entry<K, V>> collection) {
throw new UnsupportedOperationException();
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object object) {
throw new UnsupportedOperationException();
}
@Override public boolean removeAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override public boolean retainAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
}
/** @see Maps#unmodifiableEntrySet(Set) */
static class UnmodifiableEntrySet<K, V>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
super(entries);
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/**
* Returns a synchronized (thread-safe) bimap backed by the specified bimap.
* In order to guarantee serial access, it is critical that <b>all</b> access
* to the backing bimap is accomplished through the returned bimap.
*
* <p>It is imperative that the user manually synchronize on the returned map
* when accessing any of its collection views: <pre> {@code
*
* BiMap<Long, String> map = Maps.synchronizedBiMap(
* HashBiMap.<Long, String>create());
* ...
* Set<Long> set = map.keySet(); // Needn't be in synchronized block
* ...
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<Long> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap to be wrapped in a synchronized view
* @return a sychronized view of the specified bimap
*/
public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
return Synchronized.biMap(bimap, null);
}
/**
* Returns an unmodifiable view of the specified bimap. This method allows
* modules to provide users with "read-only" access to internal bimaps. Query
* operations on the returned bimap "read through" to the specified bimap, and
* attempts to modify the returned map, whether direct or via its collection
* views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified bimap
*/
public static <K, V> BiMap<K, V> unmodifiableBiMap(
BiMap<? extends K, ? extends V> bimap) {
return new UnmodifiableBiMap<K, V>(bimap, null);
}
/** @see Maps#unmodifiableBiMap(BiMap) */
private static class UnmodifiableBiMap<K, V>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
BiMap<V, K> inverse;
transient Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate,
@Nullable BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
this.delegate = delegate;
this.inverse = inverse;
}
@Override protected Map<K, V> delegate() {
return unmodifiableMap;
}
@Override
public V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null)
? inverse = new UnmodifiableBiMap<V, K>(delegate.inverse(), this)
: result;
}
@Override public Set<V> values() {
Set<V> result = values;
return (result == null)
? values = Collections.unmodifiableSet(delegate.values())
: result;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a view of a map where each value is transformed by a function. All
* other properties of the map, such as iteration order, are left intact. For
* example, the code: <pre> {@code
*
* Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* Map<String, Double> transformed = Maps.transformValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*/
public static <K, V1, V2> Map<K, V2> transformValues(
Map<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a sorted map where each value is transformed by a
* function. All other properties of the map, such as iteration order, are
* left intact. For example, the code: <pre> {@code
*
* SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* SortedMap<String, Double> transformed =
* Maps.transformSortedValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*
* @since 11.0
*/
@Beta
public static <K, V1, V2> SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
private static <K, V1, V2> EntryTransformer<K, V1, V2>
asEntryTransformer(final Function<? super V1, V2> function) {
checkNotNull(function);
return new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
}
/**
* Returns a view of a map whose values are derived from the original map's
* entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "no" + key;
* }
* };
* Map<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {verbose=verbose, sort=nosort}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 7.0
*/
public static <K, V1, V2> Map<K, V2> transformEntries(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
if (fromMap instanceof SortedMap) {
return transformEntries((SortedMap<K, V1>) fromMap, transformer);
}
return new TransformedEntriesMap<K, V1, V2>(fromMap, transformer);
}
/**
* Returns a view of a sorted map whose values are derived from the original
* sorted map's entries. In contrast to {@link #transformValues}, this
* method's entry-transformation logic may depend on the key as well as the
* value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableSortedMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "yes" + key;
* }
* };
* SortedMap<String, String> transformed =
* LabsMaps.transformSortedEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 11.0
*/
@Beta
public static <K, V1, V2> SortedMap<K, V2> transformEntries(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return Platform.mapsTransformEntriesSortedMap(fromMap, transformer);
}
static <K, V1, V2> SortedMap<K, V2> transformEntriesIgnoreNavigable(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesSortedMap<K, V1, V2>(fromMap, transformer);
}
/**
* A transformation of the value of a key-value pair, using both key and value
* as inputs. To apply the transformation to a map, use
* {@link Maps#transformEntries(Map, EntryTransformer)}.
*
* @param <K> the key type of the input and output entries
* @param <V1> the value type of the input entry
* @param <V2> the value type of the output entry
* @since 7.0
*/
public interface EntryTransformer<K, V1, V2> {
/**
* Determines an output value based on a key-value pair. This method is
* <i>generally expected</i>, but not absolutely required, to have the
* following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is,
* {@link Objects#equal Objects.equal}{@code (k1, k2) &&}
* {@link Objects#equal}{@code (v1, v2)} implies that {@code
* Objects.equal(transformer.transform(k1, v1),
* transformer.transform(k2, v2))}.
* </ul>
*
* @throws NullPointerException if the key or value is null and this
* transformer does not accept null arguments
*/
V2 transformEntry(@Nullable K key, @Nullable V1 value);
}
static class TransformedEntriesMap<K, V1, V2>
extends AbstractMap<K, V2> {
final Map<K, V1> fromMap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMap(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMap = checkNotNull(fromMap);
this.transformer = checkNotNull(transformer);
}
@Override public int size() {
return fromMap.size();
}
@Override public boolean containsKey(Object key) {
return fromMap.containsKey(key);
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 get(Object key) {
V1 value = fromMap.get(key);
return (value != null || fromMap.containsKey(key))
? transformer.transformEntry((K) key, value)
: null;
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 remove(Object key) {
return fromMap.containsKey(key)
? transformer.transformEntry((K) key, fromMap.remove(key))
: null;
}
@Override public void clear() {
fromMap.clear();
}
@Override public Set<K> keySet() {
return fromMap.keySet();
}
Set<Entry<K, V2>> entrySet;
@Override public Set<Entry<K, V2>> entrySet() {
Set<Entry<K, V2>> result = entrySet;
if (result == null) {
entrySet = result = new EntrySet<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
@Override public Iterator<Entry<K, V2>> iterator() {
return new TransformedIterator<Entry<K, V1>, Entry<K, V2>>(
fromMap.entrySet().iterator()) {
@Override
Entry<K, V2> transform(final Entry<K, V1> entry) {
return new AbstractMapEntry<K, V2>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V2 getValue() {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
};
}
};
}
return result;
}
Collection<V2> values;
@Override public Collection<V2> values() {
Collection<V2> result = values;
if (result == null) {
return values = new Values<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
};
}
return result;
}
}
static class TransformedEntriesSortedMap<K, V1, V2>
extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
protected SortedMap<K, V1> fromMap() {
return (SortedMap<K, V1>) fromMap;
}
TransformedEntriesSortedMap(SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override public Comparator<? super K> comparator() {
return fromMap().comparator();
}
@Override public K firstKey() {
return fromMap().firstKey();
}
@Override public SortedMap<K, V2> headMap(K toKey) {
return transformEntries(fromMap().headMap(toKey), transformer);
}
@Override public K lastKey() {
return fromMap().lastKey();
}
@Override public SortedMap<K, V2> subMap(K fromKey, K toKey) {
return transformEntries(
fromMap().subMap(fromKey, toKey), transformer);
}
@Override public SortedMap<K, V2> tailMap(K fromKey) {
return transformEntries(fromMap().tailMap(fromKey), transformer);
}
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*/
public static <K, V> Map<K, V> filterKeys(
Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof SortedMap) {
return filterKeys((SortedMap<K, V>) unfiltered, keyPredicate);
}
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredKeyMap<K, V>(
checkNotNull(unfiltered), keyPredicate, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* keys satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO: Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
checkNotNull(keyPredicate);
Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return keyPredicate.apply(input.getKey());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*/
public static <K, V> Map<K, V> filterValues(
Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
if (unfiltered instanceof SortedMap) {
return filterValues((SortedMap<K, V>) unfiltered, valuePredicate);
}
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* values satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
checkNotNull(valuePredicate);
Predicate<Entry<K, V>> entryPredicate =
new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return valuePredicate.apply(input.getValue());
}
};
return filterEntries(unfiltered, entryPredicate);
}
/**
* Returns a map containing the mappings in {@code unfiltered} that satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes
* to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*/
public static <K, V> Map<K, V> filterEntries(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
if (unfiltered instanceof SortedMap) {
return filterEntries((SortedMap<K, V>) unfiltered, entryPredicate);
}
checkNotNull(entryPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntrySortedMap)
? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered map.
*/
private static <K, V> Map<K, V> filterFiltered(AbstractFilteredMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate =
Predicates.and(map.predicate, entryPredicate);
return new FilteredEntryMap<K, V>(map.unfiltered, predicate);
}
private abstract static class AbstractFilteredMap<K, V>
extends AbstractMap<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
AbstractFilteredMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
boolean apply(Object key, V value) {
// This method is called only when the key is in the map, implying that
// key is a K.
@SuppressWarnings("unchecked")
K k = (K) key;
return predicate.apply(Maps.immutableEntry(k, value));
}
@Override public V put(K key, V value) {
checkArgument(apply(key, value));
return unfiltered.put(key, value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
checkArgument(apply(entry.getKey(), entry.getValue()));
}
unfiltered.putAll(map);
}
@Override public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
}
@Override public V get(Object key) {
V value = unfiltered.get(key);
return ((value != null) && apply(key, value)) ? value : null;
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public V remove(Object key) {
return containsKey(key) ? unfiltered.remove(key) : null;
}
Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = new Values() : result;
}
class Values extends AbstractCollection<V> {
@Override public Iterator<V> iterator() {
final Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
@Override public int size() {
return entrySet().size();
}
@Override public void clear() {
entrySet().clear();
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public boolean remove(Object o) {
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> collection) {
checkNotNull(collection);
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (collection.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> collection) {
checkNotNull(collection);
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!collection.contains(entry.getValue())
&& predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered sorted map.
*/
private static <K, V> SortedMap<K, V> filterFiltered(
FilteredEntrySortedMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredEntrySortedMap<K, V>(map.sortedMap(), predicate);
}
private static class FilteredEntrySortedMap<K, V>
extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
FilteredEntrySortedMap(SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
}
SortedMap<K, V> sortedMap() {
return (SortedMap<K, V>) unfiltered;
}
@Override public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override public K firstKey() {
// correctly throws NoSuchElementException when filtered map is empty.
return keySet().iterator().next();
}
@Override public K lastKey() {
SortedMap<K, V> headMap = sortedMap();
while (true) {
// correctly throws NoSuchElementException when filtered map is empty.
K key = headMap.lastKey();
if (apply(key, unfiltered.get(key))) {
return key;
}
headMap = sortedMap().headMap(key);
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
return new FilteredEntrySortedMap<K, V>(sortedMap().headMap(toKey), predicate);
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().subMap(fromKey, toKey), predicate);
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().tailMap(fromKey), predicate);
}
}
private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> {
Predicate<? super K> keyPredicate;
FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate,
Predicate<Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null)
? entrySet = Sets.filter(unfiltered.entrySet(), predicate)
: result;
}
Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null)
? keySet = Sets.filter(unfiltered.keySet(), keyPredicate)
: result;
}
// The cast is called only when the key is in the unfiltered map, implying
// that key is a K.
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
}
}
static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> {
/**
* Entries in this set satisfy the predicate, but they don't validate the
* input to {@code Entry.setValue()}.
*/
final Set<Entry<K, V>> filteredEntrySet;
FilteredEntryMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
}
Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = new EntrySet() : result;
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
@Override protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator();
return new UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry<K, V> next() {
final Entry<K, V> entry = iterator.next();
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return entry;
}
@Override public V setValue(V value) {
checkArgument(apply(entry.getKey(), value));
return super.setValue(value);
}
};
}
};
}
}
Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = new KeySet() : result;
}
private class KeySet extends Sets.ImprovedAbstractSet<K> {
@Override public Iterator<K> iterator() {
final Iterator<Entry<K, V>> iterator = filteredEntrySet.iterator();
return new UnmodifiableIterator<K>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public K next() {
return iterator.next().getKey();
}
};
}
@Override public int size() {
return filteredEntrySet.size();
}
@Override public void clear() {
filteredEntrySet.clear();
}
@Override public boolean contains(Object o) {
return containsKey(o);
}
@Override public boolean remove(Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
@Override public boolean retainAll(Collection<?> collection) {
checkNotNull(collection); // for GWT
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entrySet().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (predicate.apply(entry) && !collection.contains(entry.getKey())) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
@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
abstract static class ImprovedAbstractMap<K, V> extends AbstractMap<K, V> {
/**
* Creates the entry set to be returned by {@link #entrySet()}. This method
* is invoked at most once on a given map, at the time when {@code entrySet}
* is first called.
*/
protected abstract Set<Entry<K, V>> createEntrySet();
private Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
if (result == null) {
entrySet = result = createEntrySet();
}
return result;
}
private Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
return keySet = new KeySet<K, V>() {
@Override Map<K, V> map() {
return ImprovedAbstractMap.this;
}
};
}
return result;
}
private Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
return values = new Values<K, V>() {
@Override Map<K, V> map() {
return ImprovedAbstractMap.this;
}
};
}
return result;
}
}
static final MapJoiner STANDARD_JOINER =
Collections2.STANDARD_JOINER.withKeyValueSeparator("=");
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code
* ClassCastException}.
*/
static <V> V safeGet(Map<?, V> map, Object key) {
try {
return map.get(key);
} catch (ClassCastException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code
* ClassCastException}
*/
static boolean safeContainsKey(Map<?, ?> map, Object key) {
try {
return map.containsKey(key);
} catch (ClassCastException e) {
return false;
}
}
/**
* Implements {@code Collection.contains} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is the backing (delegate) collection, rather than
* the forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object that might be contained in {@code c}
* @return {@code true} if {@code c} contains {@code o}
*/
static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.contains(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* Implements {@code Collection.remove} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is backing (delegate) collection, rather than the
* forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object to remove from {@code c}
* @return {@code true} if {@code c} was changed
*/
static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.remove(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* An implementation of {@link Map#equals}.
*/
static boolean equalsImpl(Map<?, ?> map, Object object) {
if (map == object) {
return true;
}
if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
/**
* An implementation of {@link Map#toString}.
*/
static String toStringImpl(Map<?, ?> map) {
StringBuilder sb
= Collections2.newStringBuilderForCollection(map.size()).append('{');
STANDARD_JOINER.appendTo(sb, map);
return sb.append('}').toString();
}
/**
* An implementation of {@link Map#putAll}.
*/
static <K, V> void putAllImpl(
Map<K, V> self, Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
self.put(entry.getKey(), entry.getValue());
}
}
/**
* An admittedly inefficient implementation of {@link Map#containsKey}.
*/
static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) {
for (Entry<?, ?> entry : map.entrySet()) {
if (Objects.equal(entry.getKey(), key)) {
return true;
}
}
return false;
}
/**
* An implementation of {@link Map#containsValue}.
*/
static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) {
for (Entry<?, ?> entry : map.entrySet()) {
if (Objects.equal(entry.getValue(), value)) {
return true;
}
}
return false;
}
static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, K>(entryIterator) {
@Override
K transform(Entry<K, V> entry) {
return entry.getKey();
}
};
}
abstract static class KeySet<K, V> extends Sets.ImprovedAbstractSet<K> {
abstract Map<K, V> map();
@Override public Iterator<K> iterator() {
return keyIterator(map().entrySet().iterator());
}
@Override public int size() {
return map().size();
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean contains(Object o) {
return map().containsKey(o);
}
@Override public boolean remove(Object o) {
if (contains(o)) {
map().remove(o);
return true;
}
return false;
}
@Override public void clear() {
map().clear();
}
}
@Nullable
static <K> K keyOrNull(@Nullable Entry<K, ?> entry) {
return (entry == null) ? null : entry.getKey();
}
static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, V>(entryIterator) {
@Override
V transform(Entry<K, V> entry) {
return entry.getValue();
}
};
}
static <K, V> UnmodifiableIterator<V> valueIterator(
final UnmodifiableIterator<Entry<K, V>> entryIterator) {
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
abstract static class Values<K, V> extends AbstractCollection<V> {
abstract Map<K, V> map();
@Override public Iterator<V> iterator() {
return valueIterator(map().entrySet().iterator());
}
@Override public boolean remove(Object o) {
try {
return super.remove(o);
} catch (UnsupportedOperationException e) {
for (Entry<K, V> entry : map().entrySet()) {
if (Objects.equal(o, entry.getValue())) {
map().remove(entry.getKey());
return true;
}
}
return false;
}
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRemove = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRemove.add(entry.getKey());
}
}
return map().keySet().removeAll(toRemove);
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRetain = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRetain.add(entry.getKey());
}
}
return map().keySet().retainAll(toRetain);
}
}
@Override public int size() {
return map().size();
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean contains(@Nullable Object o) {
return map().containsValue(o);
}
@Override public void clear() {
map().clear();
}
}
abstract static class EntrySet<K, V>
extends Sets.ImprovedAbstractSet<Entry<K, V>> {
abstract Map<K, V> map();
@Override public int size() {
return map().size();
}
@Override public void clear() {
map().clear();
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
V value = map().get(key);
return Objects.equal(value, entry.getValue())
&& (value != null || map().containsKey(key));
}
return false;
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return map().keySet().remove(entry.getKey());
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
boolean changed = true;
for (Object o : c) {
changed |= remove(o);
}
return changed;
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size());
for (Object o : c) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
keys.add(entry.getKey());
}
}
return map().keySet().retainAll(keys);
}
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newTreeMap;
import static java.util.Collections.unmodifiableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
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 abstract class ImmutableSortedMap<K, V>
extends ForwardingImmutableMap<K, V> implements SortedMap<K, V> {
@SuppressWarnings("unchecked")
static final Comparator NATURAL_ORDER = Ordering.natural();
// This reference is only used by GWT compiler to infer the keys and values
// of the map that needs to be serialized.
private Comparator<? super K> unusedComparatorForSerialization;
private K unusedKeyForSerialization;
private V unusedValueForSerialization;
private final transient 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().
// (cpovirk: Is sortedDelegate's comparator really ever null?)
// The comparator will likely also differ because of our nullAccepting hack.
// See the bottom of the file for more information about it.
private final transient Comparator<? super K> comparator;
ImmutableSortedMap(SortedMap<K, V> delegate, Comparator<? super K> comparator) {
super(delegate);
this.comparator = comparator;
this.sortedDelegate = 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 = newModifiableDelegate(comparator);
for (Entry<? extends K, ? extends V> entry : entries) {
delegate.put(entry.getKey(), entry.getValue());
}
return newView(unmodifiableSortedMap(delegate), comparator);
}
// 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 EmptyImmutableSortedMap.forComparator(NATURAL_ORDER);
}
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 = newModifiableDelegate(comparator);
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
putEntryWithChecks(delegate, entry);
}
return newView(unmodifiableSortedMap(delegate), comparator);
}
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 = newModifiableDelegate(comparator);
for (Entry<? extends K, ? extends V> entry : entries) {
putEntryWithChecks(delegate, entry);
}
return newView(unmodifiableSortedMap(delegate), comparator);
}
}
private transient ImmutableSortedSet<K> keySet;
@Override public ImmutableSortedSet<K> keySet() {
ImmutableSortedSet<K> ks = keySet;
return (ks == null) ? (keySet = createKeySet()) : ks;
}
@Override 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 newView(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 newView(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 newView(sortedDelegate.tailMap(fromKey));
}
public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
checkNotNull(fromKey);
if (!inclusive) {
fromKey = higher(fromKey);
if (fromKey == null) {
return EmptyImmutableSortedMap.forComparator(comparator());
}
}
return tailMap(fromKey);
}
private ImmutableSortedMap<K, V> newView(SortedMap<K, V> delegate) {
return newView(delegate, comparator);
}
private static <K, V> ImmutableSortedMap<K, V> newView(
SortedMap<K, V> delegate, Comparator<? super K> comparator) {
if (delegate.isEmpty()) {
return EmptyImmutableSortedMap.forComparator(comparator);
}
return new RegularImmutableSortedMap<K, V>(delegate, comparator);
}
/*
* We don't permit nulls, but we wrap every comparator with nullsFirst().
* Why? We want for queries like containsKey(null) to return false, but the
* GWT SortedMap implementation that we delegate to throws
* NullPointerException if the comparator does. Since our construction
* methods ensure that null is never present in the map, it's OK for the
* comparator to look for it wherever it wants.
*
* Note that we do NOT touch the comparator returned by comparator(), which
* should be identical to the one the user passed in. We touch only the
* "secret" comparator used by the delegate implementation.
*/
private static <K, V> SortedMap<K, V> newModifiableDelegate(Comparator<? super K> comparator) {
return newTreeMap(nullAccepting(comparator));
}
private static <E> Comparator<E> nullAccepting(Comparator<E> comparator) {
return Ordering.from(comparator).nullsFirst();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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.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> multimap = Multimaps.synchronizedMultimap(
* HashMultimap.<K, V>create());
* ...
* Collection<V> values = multimap.get(key); // Needn't be in synchronized block
* ...
* synchronized (multimap) { // Synchronizing on multimap, not values!
* Iterator<V> i = values.iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }}</pre>
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that aren't
* synchronized.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped in a synchronized view
* @return a synchronized view of the specified multimap
*/
public static <K, V> Multimap<K, V> synchronizedMultimap(
Multimap<K, V> multimap) {
return Synchronized.multimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified multimap. Query operations on
* the returned multimap "read through" to the specified multimap, and
* attempts to modify the returned multimap, either directly or through the
* multimap's views, result in an {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> Multimap<K, V> unmodifiableMultimap(
Multimap<K, V> delegate) {
if (delegate instanceof UnmodifiableMultimap ||
delegate instanceof ImmutableMultimap) {
return delegate;
}
return new UnmodifiableMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap(
ImmutableMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
private static class UnmodifiableMultimap<K, V>
extends ForwardingMultimap<K, V> implements Serializable {
final Multimap<K, V> delegate;
transient Collection<Entry<K, V>> entries;
transient Multiset<K> keys;
transient Set<K> keySet;
transient Collection<V> values;
transient Map<K, Collection<V>> map;
UnmodifiableMultimap(final Multimap<K, V> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override protected Multimap<K, V> delegate() {
return delegate;
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = map;
if (result == null) {
final Map<K, Collection<V>> unmodifiableMap
= Collections.unmodifiableMap(delegate.asMap());
map = result = new ForwardingMap<K, Collection<V>>() {
@Override protected Map<K, Collection<V>> delegate() {
return unmodifiableMap;
}
Set<Entry<K, Collection<V>>> entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
Set<Entry<K, Collection<V>>> result = entrySet;
return (result == null)
? entrySet
= unmodifiableAsMapEntries(unmodifiableMap.entrySet())
: result;
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = unmodifiableMap.get(key);
return (collection == null)
? null : unmodifiableValueCollection(collection);
}
Collection<Collection<V>> asMapValues;
@Override public Collection<Collection<V>> values() {
Collection<Collection<V>> result = asMapValues;
return (result == null)
? asMapValues
= new UnmodifiableAsMapValues<V>(unmodifiableMap.values())
: result;
}
@Override public boolean containsValue(Object o) {
return values().contains(o);
}
};
}
return result;
}
@Override public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
if (result == null) {
entries = result = unmodifiableEntries(delegate.entries());
}
return result;
}
@Override public Collection<V> get(K key) {
return unmodifiableValueCollection(delegate.get(key));
}
@Override public Multiset<K> keys() {
Multiset<K> result = keys;
if (result == null) {
keys = result = Multisets.unmodifiableMultiset(delegate.keys());
}
return result;
}
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
keySet = result = Collections.unmodifiableSet(delegate.keySet());
}
return result;
}
@Override public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
values = result = Collections.unmodifiableCollection(delegate.values());
}
return result;
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableAsMapValues<V>
extends ForwardingCollection<Collection<V>> {
final Collection<Collection<V>> delegate;
UnmodifiableAsMapValues(Collection<Collection<V>> delegate) {
this.delegate = Collections.unmodifiableCollection(delegate);
}
@Override protected Collection<Collection<V>> delegate() {
return delegate;
}
@Override public Iterator<Collection<V>> iterator() {
final Iterator<Collection<V>> iterator = delegate.iterator();
return new UnmodifiableIterator<Collection<V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Collection<V> next() {
return unmodifiableValueCollection(iterator.next());
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return standardContains(o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
}
private static class UnmodifiableListMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> {
UnmodifiableListMultimap(ListMultimap<K, V> delegate) {
super(delegate);
}
@Override public ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
return Collections.unmodifiableList(delegate().get(key));
}
@Override public List<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSetMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> {
UnmodifiableSetMultimap(SetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
/*
* Note that this doesn't return a SortedSet when delegate is a
* SortedSetMultiset, unlike (SortedSet<V>) super.get().
*/
return Collections.unmodifiableSet(delegate().get(key));
}
@Override public Set<Map.Entry<K, V>> entries() {
return Maps.unmodifiableEntrySet(delegate().entries());
}
@Override public Set<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSortedSetMultimap<K, V>
extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> {
UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
return Collections.unmodifiableSortedSet(delegate().get(key));
}
@Override public SortedSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super V> valueComparator() {
return delegate().valueComparator();
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) {@code SetMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> synchronizedSetMultimap(
SetMultimap<K, V> multimap) {
return Synchronized.setMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SetMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
SetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSetMultimap ||
delegate instanceof ImmutableSetMultimap) {
return delegate;
}
return new UnmodifiableSetMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
ImmutableSetMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by
* the specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V>
synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) {
return Synchronized.sortedSetMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SortedSetMultimap}.
* Query operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(
SortedSetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSortedSetMultimap) {
return delegate;
}
return new UnmodifiableSortedSetMultimap<K, V>(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code ListMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> synchronizedListMultimap(
ListMultimap<K, V> multimap) {
return Synchronized.listMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code ListMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ListMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableListMultimap ||
delegate instanceof ImmutableListMultimap) {
return delegate;
}
return new UnmodifiableListMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ImmutableListMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns an unmodifiable view of the specified collection, preserving the
* interface for instances of {@code SortedSet}, {@code Set}, {@code List} and
* {@code Collection}, in that order of preference.
*
* @param collection the collection for which to return an unmodifiable view
* @return an unmodifiable view of the collection
*/
private static <V> Collection<V> unmodifiableValueCollection(
Collection<V> collection) {
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
}
return Collections.unmodifiableCollection(collection);
}
/**
* Returns an unmodifiable view of the specified multimap {@code asMap} entry.
* The {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}, and the collection returned by {@code
* getValue} is also an unmodifiable (type-preserving) view. This also has the
* side-effect of redefining equals to comply with the Map.Entry contract, and
* to avoid a possible nefarious implementation of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
private static <K, V> Map.Entry<K, Collection<V>> unmodifiableAsMapEntry(
final Map.Entry<K, Collection<V>> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, Collection<V>>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public Collection<V> getValue() {
return unmodifiableValueCollection(entry.getValue());
}
};
}
/**
* Returns an unmodifiable view of the specified collection of entries. The
* {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}. If the specified collection is a {@code
* Set}, the returned collection is also a {@code Set}.
*
* @param entries the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
private static <K, V> Collection<Entry<K, V>> unmodifiableEntries(
Collection<Entry<K, V>> entries) {
if (entries instanceof Set) {
return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries);
}
return new Maps.UnmodifiableEntries<K, V>(
Collections.unmodifiableCollection(entries));
}
/**
* Returns an unmodifiable view of the specified set of {@code asMap} entries.
* The {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}, as do any operations that attempt to modify
* the returned collection.
*
* @param asMapEntries the {@code asMap} entries for which to return an
* unmodifiable view
* @return an unmodifiable view of the collection entries
*/
private static <K, V> Set<Entry<K, Collection<V>>> unmodifiableAsMapEntries(
Set<Entry<K, Collection<V>>> asMapEntries) {
return new UnmodifiableAsMapEntries<K, V>(
Collections.unmodifiableSet(asMapEntries));
}
/** @see Multimaps#unmodifiableAsMapEntries */
static class UnmodifiableAsMapEntries<K, V>
extends ForwardingSet<Entry<K, Collection<V>>> {
private final Set<Entry<K, Collection<V>>> delegate;
UnmodifiableAsMapEntries(Set<Entry<K, Collection<V>>> delegate) {
this.delegate = delegate;
}
@Override protected Set<Entry<K, Collection<V>>> delegate() {
return delegate;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
final Iterator<Entry<K, Collection<V>>> iterator = delegate.iterator();
return new ForwardingIterator<Entry<K, Collection<V>>>() {
@Override protected Iterator<Entry<K, Collection<V>>> delegate() {
return iterator;
}
@Override public Entry<K, Collection<V>> next() {
return unmodifiableAsMapEntry(iterator.next());
}
};
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
}
/**
* Returns a multimap view of the specified map. The multimap is backed by the
* map, so changes to the map are reflected in the multimap, and vice versa.
* If the map is modified while an iteration over one of the multimap's
* collection views is in progress (except through the iterator's own {@code
* remove} operation, or through the {@code setValue} operation on a map entry
* returned by the iterator), the results of the iteration are undefined.
*
* <p>The multimap supports mapping removal, which removes the corresponding
* mapping from the map. It does not support any operations which might add
* mappings, such as {@code put}, {@code putAll} or {@code replaceValues}.
*
* <p>The returned multimap will be serializable if the specified map is
* serializable.
*
* @param map the backing map for the returned multimap view
*/
public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) {
return new MapMultimap<K, V>(map);
}
/** @see Multimaps#forMap */
private static class MapMultimap<K, V>
implements SetMultimap<K, V>, Serializable {
final Map<K, V> map;
transient Map<K, Collection<V>> asMap;
MapMultimap(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public boolean containsEntry(Object key, Object value) {
return map.entrySet().contains(Maps.immutableEntry(key, value));
}
@Override
public Set<V> get(final K key) {
return new Sets.ImprovedAbstractSet<V>() {
@Override public Iterator<V> iterator() {
return new Iterator<V>() {
int i;
@Override
public boolean hasNext() {
return (i == 0) && map.containsKey(key);
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
i++;
return map.get(key);
}
@Override
public void remove() {
checkState(i == 1);
i = -1;
map.remove(key);
}
};
}
@Override public int size() {
return map.containsKey(key) ? 1 : 0;
}
};
}
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object key, Object value) {
return map.entrySet().remove(Maps.immutableEntry(key, value));
}
@Override
public Set<V> removeAll(Object key) {
Set<V> values = new HashSet<V>(2);
if (!map.containsKey(key)) {
return values;
}
values.add(map.remove(key));
return values;
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<K> keySet() {
return map.keySet();
}
@Override
public Multiset<K> keys() {
return Multisets.forSet(map.keySet());
}
@Override
public Collection<V> values() {
return map.values();
}
@Override
public Set<Entry<K, V>> entries() {
return map.entrySet();
}
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
if (result == null) {
asMap = result = new AsMap();
}
return result;
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return this.size() == that.size() && asMap().equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
private static final MapJoiner JOINER
= Joiner.on("], ").withKeyValueSeparator("=[").useForNull("null");
@Override public String toString() {
if (map.isEmpty()) {
return "{}";
}
StringBuilder builder
= Collections2.newStringBuilderForCollection(map.size()).append('{');
JOINER.appendTo(builder, map);
return builder.append("]}").toString();
}
/** @see MapMultimap#asMap */
class AsMapEntries extends Sets.ImprovedAbstractSet<Entry<K, Collection<V>>> {
@Override public int size() {
return map.size();
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return new TransformedIterator<K, Entry<K, Collection<V>>>(map.keySet().iterator()) {
@Override
Entry<K, Collection<V>> transform(final K key) {
return new AbstractMapEntry<K, Collection<V>>() {
@Override
public K getKey() {
return key;
}
@Override
public Collection<V> getValue() {
return get(key);
}
};
}
};
}
@Override public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
if (!(entry.getValue() instanceof Set)) {
return false;
}
Set<?> set = (Set<?>) entry.getValue();
return (set.size() == 1)
&& containsEntry(entry.getKey(), set.iterator().next());
}
@Override public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
if (!(entry.getValue() instanceof Set)) {
return false;
}
Set<?> set = (Set<?>) entry.getValue();
return (set.size() == 1)
&& map.entrySet().remove(
Maps.immutableEntry(entry.getKey(), set.iterator().next()));
}
}
/** @see MapMultimap#asMap */
class AsMap extends Maps.ImprovedAbstractMap<K, Collection<V>> {
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new AsMapEntries();
}
// The following methods are included for performance.
@Override public boolean containsKey(Object key) {
return map.containsKey(key);
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
Collection<V> collection = MapMultimap.this.get((K) key);
return collection.isEmpty() ? null : collection;
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = removeAll(key);
return collection.isEmpty() ? null : collection;
}
}
private static final long serialVersionUID = 7845222491160860175L;
}
/**
* Returns a view of a multimap where each value is transformed by a function.
* All other properties of the multimap, such as iteration order, are left
* intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
* Function<Integer, String> square = new Function<Integer, String>() {
* public String apply(Integer in) {
* return Integer.toString(in * in);
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformValues(multimap, square);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[4, 16], b=[9, 9], c=[6]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
public static <K, V1, V2> Multimap<K, V2> transformValues(
Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a multimap whose values are derived from the original
* multimap's entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* SetMultimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return (value >= 0) ? key : "no" + key;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[a, a], b=[nob]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
public static <K, V1, V2> Multimap<K, V2> transformEntries(
Multimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesMultimap<K, V1, V2>(fromMap, transformer);
}
private static class TransformedEntriesMultimap<K, V1, V2>
implements Multimap<K, V2> {
final Multimap<K, V1> fromMultimap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMultimap(Multimap<K, V1> fromMultimap,
final EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMultimap = checkNotNull(fromMultimap);
this.transformer = checkNotNull(transformer);
}
Collection<V2> transform(final K key, Collection<V1> values) {
return Collections2.transform(values, new Function<V1, V2>() {
@Override public V2 apply(V1 value) {
return transformer.transformEntry(key, value);
}
});
}
private transient Map<K, Collection<V2>> asMap;
@Override public Map<K, Collection<V2>> asMap() {
if (asMap == null) {
Map<K, Collection<V2>> aM = Maps.transformEntries(fromMultimap.asMap(),
new EntryTransformer<K, Collection<V1>, Collection<V2>>() {
@Override public Collection<V2> transformEntry(
K key, Collection<V1> value) {
return transform(key, value);
}
});
asMap = aM;
return aM;
}
return asMap;
}
@Override public void clear() {
fromMultimap.clear();
}
@SuppressWarnings("unchecked")
@Override public boolean containsEntry(Object key, Object value) {
Collection<V2> values = get((K) key);
return values.contains(value);
}
@Override public boolean containsKey(Object key) {
return fromMultimap.containsKey(key);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
private transient Collection<Entry<K, V2>> entries;
@Override public Collection<Entry<K, V2>> entries() {
if (entries == null) {
Collection<Entry<K, V2>> es = new TransformedEntries(transformer);
entries = es;
return es;
}
return entries;
}
private class TransformedEntries
extends TransformedCollection<Entry<K, V1>, Entry<K, V2>> {
TransformedEntries(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap.entries(),
new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override public Entry<K, V2> apply(final Entry<K, V1> entry) {
return new AbstractMapEntry<K, V2>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V2 getValue() {
return transformer.transformEntry(
entry.getKey(), entry.getValue());
}
};
}
});
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Collection<V2> values = get((K) entry.getKey());
return values.remove(entry.getValue());
}
return false;
}
}
@Override public Collection<V2> get(final K key) {
return transform(key, fromMultimap.get(key));
}
@Override public boolean isEmpty() {
return fromMultimap.isEmpty();
}
@Override public Set<K> keySet() {
return fromMultimap.keySet();
}
@Override public Multiset<K> keys() {
return fromMultimap.keys();
}
@Override public boolean put(K key, V2 value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(
Multimap<? extends K, ? extends V2> multimap) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object key, Object value) {
return get((K) key).remove(value);
}
@SuppressWarnings("unchecked")
@Override public Collection<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public Collection<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public int size() {
return fromMultimap.size();
}
private transient Collection<V2> values;
@Override public Collection<V2> values() {
if (values == null) {
Collection<V2> vs = Collections2.transform(
fromMultimap.entries(), new Function<Entry<K, V1>, V2>() {
@Override public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(
entry.getKey(), entry.getValue());
}
});
values = vs;
return vs;
}
return values;
}
@Override public boolean equals(Object obj) {
if (obj instanceof Multimap) {
Multimap<?, ?> other = (Multimap<?, ?>) obj;
return asMap().equals(other.asMap());
}
return false;
}
@Override public int hashCode() {
return asMap().hashCode();
}
@Override public String toString() {
return asMap().toString();
}
}
/**
* Returns a view of a {@code ListMultimap} where each value is transformed by
* a function. All other properties of the multimap, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* ListMultimap<String, Integer> multimap
* = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* ListMultimap<String, Double> transformed = Multimaps.transformValues(map,
* sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[2.0, 4.0], b=[3.0]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
public static <K, V1, V2> ListMultimap<K, V2> transformValues(
ListMultimap<K, V1> fromMultimap,
final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer =
new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a {@code ListMultimap} whose values are derived from the
* original multimap's entries. In contrast to
* {@link #transformValues(ListMultimap, Function)}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return key + value;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
public static <K, V1, V2> ListMultimap<K, V2> transformEntries(
ListMultimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesListMultimap<K, V1, V2>(fromMap, transformer);
}
private static final class TransformedEntriesListMultimap<K, V1, V2>
extends TransformedEntriesMultimap<K, V1, V2>
implements ListMultimap<K, V2> {
TransformedEntriesListMultimap(ListMultimap<K, V1> fromMultimap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap, transformer);
}
@Override List<V2> transform(final K key, Collection<V1> values) {
return Lists.transform((List<V1>) values, new Function<V1, V2>() {
@Override public V2 apply(V1 value) {
return transformer.transformEntry(key, value);
}
});
}
@Override public List<V2> get(K key) {
return transform(key, fromMultimap.get(key));
}
@SuppressWarnings("unchecked")
@Override public List<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public List<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterable} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterable. The key used
* to store that value in the multimap will be the result of calling the
* function on that value. The resulting multimap is created as an immutable
* snapshot. In the returned multimap, keys appear in the order they are first
* encountered, and the values corresponding to each key appear in the same
* order as they are encountered.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys, stringLengthFunction);
* System.out.println(index);}</pre>
*
* prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterable<V> values, Function<? super V, K> keyFunction) {
return index(values.iterator(), keyFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterator} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterator. The key used
* to store that value in the multimap will be the result of calling the
* function on that value. The resulting multimap is created as an immutable
* snapshot. In the returned multimap, keys appear in the order they are first
* encountered, and the values corresponding to each key appear in the same
* order as they are encountered.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys.iterator(), stringLengthFunction);
* System.out.println(index);}</pre>
*
* prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
* @since 10.0
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
while (values.hasNext()) {
V value = values.next();
checkNotNull(value, values);
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
static abstract class Keys<K, V> extends AbstractMultiset<K> {
abstract Multimap<K, V> multimap();
@Override Iterator<Multiset.Entry<K>> entryIterator() {
return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>(
multimap().asMap().entrySet().iterator()) {
@Override
Multiset.Entry<K> transform(
final Map.Entry<K, Collection<V>> backingEntry) {
return new Multisets.AbstractEntry<K>() {
@Override
public K getElement() {
return backingEntry.getKey();
}
@Override
public int getCount() {
return backingEntry.getValue().size();
}
};
}
};
}
@Override int distinctElements() {
return multimap().asMap().size();
}
@Override Set<Multiset.Entry<K>> createEntrySet() {
return new KeysEntrySet();
}
class KeysEntrySet extends Multisets.EntrySet<K> {
@Override Multiset<K> multiset() {
return Keys.this;
}
@Override public Iterator<Multiset.Entry<K>> iterator() {
return entryIterator();
}
@Override public int size() {
return distinctElements();
}
@Override public boolean isEmpty() {
return multimap().isEmpty();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
Collection<V> collection = multimap().asMap().get(entry.getElement());
return collection != null && collection.size() == entry.getCount();
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
Collection<V> collection = multimap().asMap().get(entry.getElement());
if (collection != null && collection.size() == entry.getCount()) {
collection.clear();
return true;
}
}
return false;
}
}
@Override public boolean contains(@Nullable Object element) {
return multimap().containsKey(element);
}
@Override public Iterator<K> iterator() {
return Maps.keyIterator(multimap().entries().iterator());
}
@Override public int count(@Nullable Object element) {
try {
if (multimap().containsKey(element)) {
Collection<V> values = multimap().asMap().get(element);
return (values == null) ? 0 : values.size();
}
return 0;
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
@Override public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0);
if (occurrences == 0) {
return count(element);
}
Collection<V> values;
try {
values = multimap().asMap().get(element);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
if (values == null) {
return 0;
}
int oldCount = values.size();
if (occurrences >= oldCount) {
values.clear();
} else {
Iterator<V> iterator = values.iterator();
for (int i = 0; i < occurrences; i++) {
iterator.next();
iterator.remove();
}
}
return oldCount;
}
@Override public void clear() {
multimap().clear();
}
@Override public Set<K> elementSet() {
return multimap().keySet();
}
}
static abstract class Values<K, V> extends AbstractCollection<V> {
abstract Multimap<K, V> multimap();
@Override public Iterator<V> iterator() {
return Maps.valueIterator(multimap().entries().iterator());
}
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
return multimap().containsValue(o);
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link Multimap#entries()}.
*/
static abstract class Entries<K, V> extends
AbstractCollection<Map.Entry<K, V>> {
abstract Multimap<K, V> multimap();
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link SetMultimap#entries()}.
*/
static abstract class EntrySet<K, V> extends Entries<K, V> implements
Set<Map.Entry<K, V>> {
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override public boolean equals(@Nullable Object obj) {
return Sets.equalsImpl(this, obj);
}
}
/**
* A skeleton implementation of {@link Multimap#asMap()}.
*/
static abstract class AsMap<K, V> extends
Maps.ImprovedAbstractMap<K, Collection<V>> {
abstract Multimap<K, V> multimap();
@Override public abstract int size();
abstract Iterator<Entry<K, Collection<V>>> entryIterator();
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new EntrySet();
}
void removeValuesForKey(Object key){
multimap().removeAll(key);
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return entryIterator();
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
return containsKey(key) ? multimap().get((K) key) : null;
}
@Override public Collection<V> remove(Object key) {
return containsKey(key) ? multimap().removeAll(key) : null;
}
@Override public Set<K> keySet() {
return multimap().keySet();
}
@Override public boolean isEmpty() {
return multimap().isEmpty();
}
@Override public boolean containsKey(Object key) {
return multimap().containsKey(key);
}
@Override public void clear() {
multimap().clear();
}
}
/**
* Support removal operations when filtering a filtered multimap. Since a
* filtered multimap has iterators that don't support remove, passing one to
* the FilteredMultimap constructor would lead to a multimap whose removal
* operations would fail. This method combines the predicates to avoid that
* problem.
*/
private static <K, V> Multimap<K, V> filterFiltered(FilteredMultimap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredMultimap<K, V>(map.unfiltered, predicate);
}
private static class FilteredMultimap<K, V> implements Multimap<K, V> {
final Multimap<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
FilteredMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override public int size() {
return entries().size();
}
@Override public boolean isEmpty() {
return entries().isEmpty();
}
@Override public boolean containsKey(Object key) {
return asMap().containsKey(key);
}
@Override public boolean containsValue(Object value) {
return values().contains(value);
}
// This method should be called only when key is a K and value is a V.
@SuppressWarnings("unchecked")
boolean satisfiesPredicate(Object key, Object value) {
return predicate.apply(Maps.immutableEntry((K) key, (V) value));
}
@Override public boolean containsEntry(Object key, Object value) {
return unfiltered.containsEntry(key, value) && satisfiesPredicate(key, value);
}
@Override public boolean put(K key, V value) {
checkArgument(satisfiesPredicate(key, value));
return unfiltered.put(key, value);
}
@Override public boolean remove(Object key, Object value) {
return containsEntry(key, value) ? unfiltered.remove(key, value) : false;
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
for (V value : values) {
checkArgument(satisfiesPredicate(key, value));
}
return unfiltered.putAll(key, values);
}
@Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
checkArgument(satisfiesPredicate(entry.getKey(), entry.getValue()));
}
return unfiltered.putAll(multimap);
}
@Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
for (V value : values) {
checkArgument(satisfiesPredicate(key, value));
}
// Not calling unfiltered.replaceValues() since values that don't satisify
// the filter should remain in the multimap.
Collection<V> oldValues = removeAll(key);
unfiltered.putAll(key, values);
return oldValues;
}
@Override public Collection<V> removeAll(Object key) {
List<V> removed = Lists.newArrayList();
Collection<V> values = unfiltered.asMap().get(key);
if (values != null) {
Iterator<V> iterator = values.iterator();
while (iterator.hasNext()) {
V value = iterator.next();
if (satisfiesPredicate(key, value)) {
removed.add(value);
iterator.remove();
}
}
}
if (unfiltered instanceof SetMultimap) {
return Collections.unmodifiableSet(Sets.newLinkedHashSet(removed));
} else {
return Collections.unmodifiableList(removed);
}
}
@Override public void clear() {
entries().clear();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return asMap().equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return asMap().hashCode();
}
@Override public String toString() {
return asMap().toString();
}
class ValuePredicate implements Predicate<V> {
final K key;
ValuePredicate(K key) {
this.key = key;
}
@Override public boolean apply(V value) {
return satisfiesPredicate(key, value);
}
}
Collection<V> filterCollection(Collection<V> collection, Predicate<V> predicate) {
if (collection instanceof Set) {
return Sets.filter((Set<V>) collection, predicate);
} else {
return Collections2.filter(collection, predicate);
}
}
@Override public Collection<V> get(K key) {
return filterCollection(unfiltered.get(key), new ValuePredicate(key));
}
@Override public Set<K> keySet() {
return asMap().keySet();
}
Collection<V> values;
@Override public Collection<V> values() {
return (values == null) ? values = new Values() : values;
}
class Values extends Multimaps.Values<K, V> {
@Override Multimap<K, V> multimap() {
return FilteredMultimap.this;
}
@Override public boolean contains(@Nullable Object o) {
return Iterators.contains(iterator(), o);
}
// Override remove methods since iterator doesn't support remove.
@Override public boolean remove(Object o) {
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (c.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
boolean changed = false;
Iterator<Entry<K, V>> iterator = unfiltered.entries().iterator();
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
if (!c.contains(entry.getValue()) && predicate.apply(entry)) {
iterator.remove();
changed = true;
}
}
return changed;
}
}
Collection<Entry<K, V>> entries;
@Override public Collection<Entry<K, V>> entries() {
return (entries == null)
? entries = Collections2.filter(unfiltered.entries(), predicate)
: entries;
}
/**
* Remove all filtered asMap() entries that satisfy the predicate.
*/
boolean removeEntriesIf(Predicate<Map.Entry<K, Collection<V>>> removalPredicate) {
Iterator<Map.Entry<K, Collection<V>>> iterator = unfiltered.asMap().entrySet().iterator();
boolean changed = false;
while (iterator.hasNext()) {
// Determine whether to remove the filtered values with this key.
Map.Entry<K, Collection<V>> entry = iterator.next();
K key = entry.getKey();
Collection<V> collection = entry.getValue();
Predicate<V> valuePredicate = new ValuePredicate(key);
Collection<V> filteredCollection = filterCollection(collection, valuePredicate);
Map.Entry<K, Collection<V>> filteredEntry = Maps.immutableEntry(key, filteredCollection);
if (removalPredicate.apply(filteredEntry) && !filteredCollection.isEmpty()) {
changed = true;
if (Iterables.all(collection, valuePredicate)) {
iterator.remove(); // Remove all values for the key.
} else {
filteredCollection.clear(); // Remove the filtered values only.
}
}
}
return changed;
}
Map<K, Collection<V>> asMap;
@Override public Map<K, Collection<V>> asMap() {
return (asMap == null) ? asMap = createAsMap() : asMap;
}
static final Predicate<Collection<?>> NOT_EMPTY = new Predicate<Collection<?>>() {
@Override public boolean apply(Collection<?> input) {
return !input.isEmpty();
}
};
Map<K, Collection<V>> createAsMap() {
// Select the values that satisify the predicate.
EntryTransformer<K, Collection<V>, Collection<V>> transformer
= new EntryTransformer<K, Collection<V>, Collection<V>>() {
@Override public Collection<V> transformEntry(K key, Collection<V> collection) {
return filterCollection(collection, new ValuePredicate(key));
}
};
Map<K, Collection<V>> transformed
= Maps.transformEntries(unfiltered.asMap(), transformer);
// Select the keys that have at least one value remaining.
Map<K, Collection<V>> filtered = Maps.filterValues(transformed, NOT_EMPTY);
// Override the removal methods, since removing a map entry should not
// affect values that don't satisfy the filter.
return new AsMap(filtered);
}
class AsMap extends ForwardingMap<K, Collection<V>> {
final Map<K, Collection<V>> delegate;
AsMap(Map<K, Collection<V>> delegate) {
this.delegate = delegate;
}
@Override protected Map<K, Collection<V>> delegate() {
return delegate;
}
@Override public Collection<V> remove(Object o) {
Collection<V> output = FilteredMultimap.this.removeAll(o);
return output.isEmpty() ? null : output;
}
@Override public void clear() {
FilteredMultimap.this.clear();
}
Set<K> keySet;
@Override public Set<K> keySet() {
return (keySet == null) ? keySet = new KeySet() : keySet;
}
class KeySet extends Maps.KeySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public boolean remove(Object o) {
Collection<V> collection = delegate.get(o);
if (collection == null) {
return false;
}
collection.clear();
return true;
}
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c.iterator());
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry.getKey());
}
};
return removeEntriesIf(removalPredicate);
}
}
Values asMapValues;
@Override public Collection<Collection<V>> values() {
return (asMapValues == null) ? asMapValues = new Values() : asMapValues;
}
class Values extends Maps.Values<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public boolean remove(Object o) {
for (Collection<V> collection : this) {
if (collection.equals(o)) {
collection.clear();
return true;
}
}
return false;
}
@Override public boolean removeAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return c.contains(entry.getValue());
}
};
return removeEntriesIf(removalPredicate);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry.getValue());
}
};
return removeEntriesIf(removalPredicate);
}
}
EntrySet entrySet;
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
return (entrySet == null) ? entrySet = new EntrySet(super.entrySet()) : entrySet;
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
Set<Map.Entry<K, Collection<V>>> delegateEntries;
public EntrySet(Set<Map.Entry<K, Collection<V>>> delegateEntries) {
this.delegateEntries = delegateEntries;
}
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return delegateEntries.iterator();
}
@Override public boolean remove(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Collection<V> collection = delegate.get(entry.getKey());
if (collection != null && collection.equals(entry.getValue())) {
collection.clear();
return true;
}
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
return Sets.removeAllImpl(this, c);
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
return !c.contains(entry);
}
};
return removeEntriesIf(removalPredicate);
}
}
}
AbstractMultiset<K> keys;
@Override public Multiset<K> keys() {
return (keys == null) ? keys = new Keys() : keys;
}
class Keys extends Multimaps.Keys<K, V> {
@Override Multimap<K, V> multimap() {
return FilteredMultimap.this;
}
@Override public int remove(Object o, int occurrences) {
checkArgument(occurrences >= 0);
Collection<V> values = unfiltered.asMap().get(o);
if (values == null) {
return 0;
}
int priorCount = 0;
int removed = 0;
Iterator<V> iterator = values.iterator();
while (iterator.hasNext()) {
if (satisfiesPredicate(o, iterator.next())) {
priorCount++;
if (removed < occurrences) {
iterator.remove();
removed++;
}
}
}
return priorCount;
}
@Override Set<Multiset.Entry<K>> createEntrySet() {
return new EntrySet();
}
class EntrySet extends Multimaps.Keys<K, V>.KeysEntrySet {
@Override
public boolean removeAll(final Collection<?> c) {
return Sets.removeAllImpl(this, c.iterator());
}
@Override public boolean retainAll(final Collection<?> c) {
Predicate<Map.Entry<K, Collection<V>>> removalPredicate
= new Predicate<Map.Entry<K, Collection<V>>>() {
@Override public boolean apply(Map.Entry<K, Collection<V>> entry) {
Multiset.Entry<K> multisetEntry
= Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
return !c.contains(multisetEntry);
}
};
return removeEntriesIf(removalPredicate);
}
}
}
}
// TODO(jlevy): Create methods that filter a SetMultimap or SortedSetMultimap.
}
| Java |
/*
* Copyright (C) 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;
/**
* 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 ForwardingImmutableMap<Object, Object> {
EmptyImmutableMap() {
super(Collections.emptyMap());
}
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 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 {
static final Object[] EMPTY_ARRAY = new Object[0];
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;
System.arraycopy(array, 0, result, 1, array.length);
return result;
}
/**
* Returns a new array that appends {@code element} to {@code array}.
*
* @param array the array of elements to prepend
* @param element the element to append to the end
* @return an array whose size is one larger than {@code array}, with
* the same contents as {@code array}, plus {@code element} occupying the
* last position.
*/
public static <T> T[] concat(T[] array, @Nullable T element) {
T[] result = arraysCopyOf(array, array.length + 1);
result[array.length] = element;
return result;
}
/** GWT safe version of Arrays.copyOf. */
static <T> T[] arraysCopyOf(T[] original, int newLength) {
T[] copy = newArray(original, newLength);
System.arraycopy(
original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
/**
* Returns an array containing all of the elements in the specified
* collection; the runtime type of the returned array is that of the specified
* array. If the collection fits in the specified array, it is returned
* therein. Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of the specified collection.
*
* <p>If the collection fits in the specified array with room to spare (i.e.,
* the array has more elements than the collection), the element in the array
* immediately following the end of the collection is set to {@code null}.
* This is useful in determining the length of the collection <i>only</i> if
* the caller knows that the collection does not contain any null elements.
*
* <p>This method returns the elements in the order they are returned by the
* collection's iterator.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
* @param array the array in which to place the collection elements
* @throws ArrayStoreException if the runtime type of the specified array is
* not a supertype of the runtime type of every element in the specified
* collection
*/
static <T> T[] toArrayImpl(Collection<?> c, T[] array) {
int size = c.size();
if (array.length < size) {
array = newArray(array, size);
}
fillArray(c, array);
if (array.length > size) {
array[size] = null;
}
return array;
}
/**
* Returns an array containing all of the elements in the specified
* collection. This method returns the elements in the order they are returned
* by the collection's iterator. The returned array is "safe" in that no
* references to it are maintained by the collection. The caller is thus free
* to modify the returned array.
*
* <p>This method assumes that the collection size doesn't change while the
* method is running.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
*/
static Object[] toArrayImpl(Collection<?> c) {
return fillArray(c, new Object[c.size()]);
}
private static Object[] fillArray(Iterable<?> elements, Object[] array) {
int i = 0;
for (Object element : elements) {
array[i++] = element;
}
return array;
}
/**
* Swaps {@code array[i]} with {@code array[j]}.
*/
static void swap(Object[] array, int i, int j) {
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// We do this instead of Preconditions.checkNotNull to save boxing and array
// creation cost.
static Object checkElementNotNull(Object element, int index) {
if (element == null) {
throw new NullPointerException("at index " + index);
}
return element;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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#concurrencyLevel}.
*/
public abstract GenericMapMaker<K0, V0> concurrencyLevel(int concurrencyLevel);
/**
* 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) 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 ForwardingImmutableSet<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) 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.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Basic implementation of {@code Multiset<E>} backed by an instance of {@code
* Map<E, Count>}.
*
* <p>For serialization to work, the subclass must specify explicit {@code
* readObject} and {@code writeObject} methods.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E>
implements Serializable {
private transient Map<E, Count> backingMap;
/*
* Cache the size for efficiency. Using a long lets us avoid the need for
* overflow checking and ensures that size() will function correctly even if
* the multiset had once been larger than Integer.MAX_VALUE.
*/
private transient long size;
/** Standard constructor. */
protected AbstractMapBasedMultiset(Map<E, Count> backingMap) {
this.backingMap = checkNotNull(backingMap);
this.size = super.size();
}
/** Used during deserialization only. The backing map must be empty. */
void setBackingMap(Map<E, Count> backingMap) {
this.backingMap = backingMap;
}
// Required Implementations
/**
* {@inheritDoc}
*
* <p>Invoking {@link Multiset.Entry#getCount} on an entry in the returned
* set always returns the current count of that element in the multiset, as
* opposed to the count at the time the entry was retrieved.
*/
@Override
public Set<Multiset.Entry<E>> entrySet() {
return super.entrySet();
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Count>> backingEntries =
backingMap.entrySet().iterator();
return new Iterator<Multiset.Entry<E>>() {
Map.Entry<E, Count> toRemove;
@Override
public boolean hasNext() {
return backingEntries.hasNext();
}
@Override
public Multiset.Entry<E> next() {
final Map.Entry<E, Count> mapEntry = backingEntries.next();
toRemove = mapEntry;
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return mapEntry.getKey();
}
@Override
public int getCount() {
int count = mapEntry.getValue().get();
if (count == 0) {
Count frequency = backingMap.get(getElement());
if (frequency != null) {
count = frequency.get();
}
}
return count;
}
};
}
@Override
public void remove() {
Iterators.checkRemove(toRemove != null);
size -= toRemove.getValue().getAndSet(0);
backingEntries.remove();
toRemove = null;
}
};
}
@Override
public void clear() {
for (Count frequency : backingMap.values()) {
frequency.set(0);
}
backingMap.clear();
size = 0L;
}
@Override
int distinctElements() {
return backingMap.size();
}
// Optimizations - Query Operations
@Override public int size() {
return Ints.saturatedCast(size);
}
@Override public Iterator<E> iterator() {
return new MapBasedMultisetIterator();
}
/*
* Not subclassing AbstractMultiset$MultisetIterator because next() needs to
* retrieve the Map.Entry<E, AtomicInteger> entry, which can then be used for
* a more efficient remove() call.
*/
private class MapBasedMultisetIterator implements Iterator<E> {
final Iterator<Map.Entry<E, Count>> entryIterator;
Map.Entry<E, Count> currentEntry;
int occurrencesLeft;
boolean canRemove;
MapBasedMultisetIterator() {
this.entryIterator = backingMap.entrySet().iterator();
}
@Override
public boolean hasNext() {
return occurrencesLeft > 0 || entryIterator.hasNext();
}
@Override
public E next() {
if (occurrencesLeft == 0) {
currentEntry = entryIterator.next();
occurrencesLeft = currentEntry.getValue().get();
}
occurrencesLeft--;
canRemove = true;
return currentEntry.getKey();
}
@Override
public void remove() {
checkState(canRemove,
"no calls to next() since the last call to remove()");
int frequency = currentEntry.getValue().get();
if (frequency <= 0) {
throw new ConcurrentModificationException();
}
if (currentEntry.getValue().addAndGet(-1) == 0) {
entryIterator.remove();
}
size--;
canRemove = false;
}
}
@Override public int count(@Nullable Object element) {
try {
Count frequency = backingMap.get(element);
return (frequency == null) ? 0 : frequency.get();
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
// Optional Operations - Modification Operations
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the call would result in more than
* {@link Integer#MAX_VALUE} occurrences of {@code element} in this
* multiset.
*/
@Override public int add(@Nullable E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
int oldCount;
if (frequency == null) {
oldCount = 0;
backingMap.put(element, new Count(occurrences));
} else {
oldCount = frequency.get();
long newCount = (long) oldCount + (long) occurrences;
checkArgument(newCount <= Integer.MAX_VALUE,
"too many occurrences: %s", newCount);
frequency.getAndAdd(occurrences);
}
size += occurrences;
return oldCount;
}
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
if (frequency == null) {
return 0;
}
int oldCount = frequency.get();
int numberRemoved;
if (oldCount > occurrences) {
numberRemoved = occurrences;
} else {
numberRemoved = oldCount;
backingMap.remove(element);
}
frequency.addAndGet(-numberRemoved);
size -= numberRemoved;
return oldCount;
}
// Roughly a 33% performance improvement over AbstractMultiset.setCount().
@Override public int setCount(@Nullable E element, int count) {
checkNonnegative(count, "count");
Count existingCounter;
int oldCount;
if (count == 0) {
existingCounter = backingMap.remove(element);
oldCount = getAndSet(existingCounter, count);
} else {
existingCounter = backingMap.get(element);
oldCount = getAndSet(existingCounter, count);
if (existingCounter == null) {
backingMap.put(element, new Count(count));
}
}
size += (count - oldCount);
return oldCount;
}
private static int getAndSet(Count i, int count) {
if (i == null) {
return 0;
}
return i.getAndSet(count);
}
// Views
@Override Set<E> createElementSet() {
return new MapBasedElementSet();
}
class MapBasedElementSet extends Multisets.ElementSet<E> {
@Override
Multiset<E> multiset() {
return AbstractMapBasedMultiset.this;
}
}
// Don't allow default serialization.
}
| 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) 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 java.util.Collections.singletonList;
import java.util.List;
/**
* GWT emulated version of {@link SingletonImmutableList}.
*
* @author Hayward Chan
*/
final class SingletonImmutableList<E> extends ForwardingImmutableList<E> {
final transient List<E> delegate;
// 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) {
this.delegate = singletonList(checkNotNull(element));
this.element = element;
}
@Override List<E> delegateList() {
return delegate;
}
}
| 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.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> extends FluentIterable<T> {
private final Iterable<T> iterable;
private UnmodifiableIterable(Iterable<T> iterable) {
this.iterable = iterable;
}
@Override
public Iterator<T> iterator() {
return Iterators.unmodifiableIterator(iterable.iterator());
}
@Override
public String toString() {
return iterable.toString();
}
// no equals and hashCode; it would break the contract!
}
/**
* Returns the number of elements in {@code iterable}.
*/
public static int size(Iterable<?> iterable) {
return (iterable instanceof Collection)
? ((Collection<?>) iterable).size()
: Iterators.size(iterable.iterator());
}
/**
* Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)}
* is true.
*/
public static boolean contains(Iterable<?> iterable, @Nullable Object element)
{
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
try {
return collection.contains(element);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
return Iterators.contains(iterable.iterator(), element);
}
/**
* Removes, from an iterable, every element that belongs to the provided
* collection.
*
* <p>This method calls {@link Collection#removeAll} if {@code iterable} is a
* collection, and {@link Iterators#removeAll} otherwise.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param elementsToRemove the elements to remove
* @return {@code true} if any element was removed from {@code iterable}
*/
public static boolean removeAll(
Iterable<?> removeFrom, Collection<?> elementsToRemove) {
return (removeFrom instanceof Collection)
? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove))
: Iterators.removeAll(removeFrom.iterator(), elementsToRemove);
}
/**
* Removes, from an iterable, every element that does not belong to the
* provided collection.
*
* <p>This method calls {@link Collection#retainAll} if {@code iterable} is a
* collection, and {@link Iterators#retainAll} otherwise.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param elementsToRetain the elements to retain
* @return {@code true} if any element was removed from {@code iterable}
*/
public static boolean retainAll(
Iterable<?> removeFrom, Collection<?> elementsToRetain) {
return (removeFrom instanceof Collection)
? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain))
: Iterators.retainAll(removeFrom.iterator(), elementsToRetain);
}
/**
* Removes, from an iterable, every element that satisfies the provided
* predicate.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param predicate a predicate that determines whether an element should
* be removed
* @return {@code true} if any elements were removed from the iterable
*
* @throws UnsupportedOperationException if the iterable does not support
* {@code remove()}.
* @since 2.0
*/
public static <T> boolean removeIf(
Iterable<T> removeFrom, Predicate<? super T> predicate) {
if (removeFrom instanceof RandomAccess && removeFrom instanceof List) {
return removeIfFromRandomAccessList(
(List<T>) removeFrom, checkNotNull(predicate));
}
return Iterators.removeIf(removeFrom.iterator(), predicate);
}
private static <T> boolean removeIfFromRandomAccessList(
List<T> list, Predicate<? super T> predicate) {
// Note: Not all random access lists support set() so we need to deal with
// those that don't and attempt the slower remove() based solution.
int from = 0;
int to = 0;
for (; from < list.size(); from++) {
T element = list.get(from);
if (!predicate.apply(element)) {
if (from > to) {
try {
list.set(to, element);
} catch (UnsupportedOperationException e) {
slowRemoveIfForRemainingElements(list, predicate, to, from);
return true;
}
}
to++;
}
}
// Clear the tail of any remaining items
list.subList(to, list.size()).clear();
return from != to;
}
private static <T> void slowRemoveIfForRemainingElements(List<T> list,
Predicate<? super T> predicate, int to, int from) {
// Here we know that:
// * (to < from) and that both are valid indices.
// * Everything with (index < to) should be kept.
// * Everything with (to <= index < from) should be removed.
// * The element with (index == from) should be kept.
// * Everything with (index > from) has not been checked yet.
// Check from the end of the list backwards (minimize expected cost of
// moving elements when remove() is called). Stop before 'from' because
// we already know that should be kept.
for (int n = list.size() - 1; n > from; n--) {
if (predicate.apply(list.get(n))) {
list.remove(n);
}
}
// And now remove everything in the range [to, from) (going backwards).
for (int n = from - 1; n >= to; n--) {
list.remove(n);
}
}
/**
* Determines whether two iterables contain equal elements in the same order.
* More specifically, this method returns {@code true} if {@code iterable1}
* and {@code iterable2} contain the same number of elements and every element
* of {@code iterable1} is equal to the corresponding element of
* {@code iterable2}.
*/
public static boolean elementsEqual(
Iterable<?> iterable1, Iterable<?> iterable2) {
return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
}
/**
* Returns a string representation of {@code iterable}, with the format
* {@code [e1, e2, ..., en]}.
*/
public static String toString(Iterable<?> iterable) {
return Iterators.toString(iterable.iterator());
}
/**
* Returns the single element contained in {@code iterable}.
*
* @throws NoSuchElementException if the iterable is empty
* @throws IllegalArgumentException if the iterable contains multiple
* elements
*/
public static <T> T getOnlyElement(Iterable<T> iterable) {
return Iterators.getOnlyElement(iterable.iterator());
}
/**
* Returns the single element contained in {@code iterable}, or {@code
* defaultValue} if the iterable is empty.
*
* @throws IllegalArgumentException if the iterator contains multiple
* elements
*/
@Nullable
public static <T> T getOnlyElement(
Iterable<? extends T> iterable, @Nullable T defaultValue) {
return Iterators.getOnlyElement(iterable.iterator(), defaultValue);
}
/**
* Copies an iterable's elements into an array.
*
* @param iterable the iterable to copy
* @return a newly-allocated array into which all the elements of the iterable
* have been copied
*/
static Object[] toArray(Iterable<?> iterable) {
return toCollection(iterable).toArray();
}
/**
* Converts an iterable into a collection. If the iterable is already a
* collection, it is returned. Otherwise, an {@link java.util.ArrayList} is
* created with the contents of the iterable in the same iteration order.
*/
private static <E> Collection<E> toCollection(Iterable<E> iterable) {
return (iterable instanceof Collection)
? (Collection<E>) iterable
: Lists.newArrayList(iterable.iterator());
}
/**
* Adds all elements in {@code iterable} to {@code collection}.
*
* @return {@code true} if {@code collection} was modified as a result of this
* operation.
*/
public static <T> boolean addAll(
Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
if (elementsToAdd instanceof Collection) {
Collection<? extends T> c = Collections2.cast(elementsToAdd);
return addTo.addAll(c);
}
return Iterators.addAll(addTo, elementsToAdd.iterator());
}
/**
* Returns the number of elements in the specified iterable that equal the
* specified object. This implementation avoids a full iteration when the
* iterable is a {@link Multiset} or {@link Set}.
*
* @see Collections#frequency
*/
public static int frequency(Iterable<?> iterable, @Nullable Object element) {
if ((iterable instanceof Multiset)) {
return ((Multiset<?>) iterable).count(element);
}
if ((iterable instanceof Set)) {
return ((Set<?>) iterable).contains(element) ? 1 : 0;
}
return Iterators.frequency(iterable.iterator(), element);
}
/**
* Returns an iterable whose iterators cycle indefinitely over the elements of
* {@code iterable}.
*
* <p>That iterator supports {@code remove()} if {@code iterable.iterator()}
* does. After {@code remove()} is called, subsequent cycles omit the removed
* element, which is no longer in {@code iterable}. The iterator's
* {@code hasNext()} method returns {@code true} until {@code iterable} is
* empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*
* <p>To cycle over the iterable {@code n} times, use the following:
* {@code Iterables.concat(Collections.nCopies(n, iterable))}
*/
public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.cycle(iterable);
}
@Override public String toString() {
return iterable.toString() + " (cycled)";
}
};
}
/**
* Returns an iterable whose iterators cycle indefinitely over the provided
* elements.
*
* <p>After {@code remove} is invoked on a generated iterator, the removed
* element will no longer appear in either that iterator or any other iterator
* created from the same source iterable. That is, this method behaves exactly
* as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's
* {@code hasNext} method returns {@code true} until all of the original
* elements have been removed.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*
* <p>To cycle over the elements {@code n} times, use the following:
* {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))}
*/
public static <T> Iterable<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
}
/**
* Combines two iterables into a single iterable. The returned iterable has an
* iterator that traverses the elements in {@code a}, followed by the elements
* in {@code b}. The source iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b) {
checkNotNull(a);
checkNotNull(b);
return concat(Arrays.asList(a, b));
}
/**
* Combines three iterables into a single iterable. The returned iterable has
* an iterator that traverses the elements in {@code a}, followed by the
* elements in {@code b}, followed by the elements in {@code c}. The source
* iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
return concat(Arrays.asList(a, b, c));
}
/**
* Combines four iterables into a single iterable. The returned iterable has
* an iterator that traverses the elements in {@code a}, followed by the
* elements in {@code b}, followed by the elements in {@code c}, followed by
* the elements in {@code d}. The source iterators are not polled until
* necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c,
Iterable<? extends T> d) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
checkNotNull(d);
return concat(Arrays.asList(a, b, c, d));
}
/**
* Combines multiple iterables into a single iterable. The returned iterable
* has an iterator that traverses the elements of each iterable in
* {@code inputs}. The input iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*
* @throws NullPointerException if any of the provided iterables is null
*/
public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
return concat(ImmutableList.copyOf(inputs));
}
/**
* Combines multiple iterables into a single iterable. The returned iterable
* has an iterator that traverses the elements of each iterable in
* {@code inputs}. The input iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it. The methods of the returned
* iterable may throw {@code NullPointerException} if any of the input
* iterators is null.
*/
public static <T> Iterable<T> concat(
final Iterable<? extends Iterable<? extends T>> inputs) {
checkNotNull(inputs);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.concat(iterators(inputs));
}
};
}
/**
* Returns an iterator over the iterators of the given iterables.
*/
private static <T> UnmodifiableIterator<Iterator<? extends T>> iterators(
Iterable<? extends Iterable<? extends T>> iterables) {
final Iterator<? extends Iterable<? extends T>> iterableIterator =
iterables.iterator();
return new UnmodifiableIterator<Iterator<? extends T>>() {
@Override
public boolean hasNext() {
return iterableIterator.hasNext();
}
@Override
public Iterator<? extends T> next() {
return iterableIterator.next().iterator();
}
};
}
/**
* Divides an iterable into unmodifiable sublists of the given size (the final
* iterable may be smaller). For example, partitioning an iterable containing
* {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
* [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of
* three and two elements, all in the original order.
*
* <p>Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method. The returned lists implement {@link
* RandomAccess}, whether or not the input list does.
*
* <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link
* Lists#partition(List, int)} instead.
*
* @param iterable the iterable to return a partitioned view of
* @param size the desired size of each partition (the last may be smaller)
* @return an iterable of unmodifiable lists containing the elements of {@code
* iterable} divided into partitions
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> Iterable<List<T>> partition(
final Iterable<T> iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new FluentIterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return Iterators.partition(iterable.iterator(), size);
}
};
}
/**
* Divides an iterable into unmodifiable sublists of the given size, padding
* the final iterable with null values if necessary. For example, partitioning
* an iterable containing {@code [a, b, c, d, e]} with a partition size of 3
* yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing
* two inner lists of three elements each, all in the original order.
*
* <p>Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method.
*
* @param iterable the iterable to return a partitioned view of
* @param size the desired size of each partition
* @return an iterable of unmodifiable lists containing the elements of {@code
* iterable} divided into partitions (the final iterable may have
* trailing null elements)
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> Iterable<List<T>> paddedPartition(
final Iterable<T> iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new FluentIterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return Iterators.paddedPartition(iterable.iterator(), size);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* resulting iterable's iterator does not support {@code remove()}.
*/
public static <T> Iterable<T> filter(
final Iterable<T> unfiltered, final Predicate<? super T> predicate) {
checkNotNull(unfiltered);
checkNotNull(predicate);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
};
}
/**
* Returns {@code true} if any element in {@code iterable} satisfies the predicate.
*/
public static <T> boolean any(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.any(iterable.iterator(), predicate);
}
/**
* Returns {@code true} if every element in {@code iterable} satisfies the
* predicate. If {@code iterable} is empty, {@code true} is returned.
*/
public static <T> boolean all(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.all(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate; use this method only when such an element is known to exist. If
* it is possible that <i>no</i> element will match, use {@link #tryFind} or
* {@link #find(Iterable, Predicate, Object)} instead.
*
* @throws NoSuchElementException if no element in {@code iterable} matches
* the given predicate
*/
public static <T> T find(Iterable<T> iterable,
Predicate<? super T> predicate) {
return Iterators.find(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate, or {@code defaultValue} if none found. Note that this can
* usually be handled more naturally using {@code
* tryFind(iterable, predicate).or(defaultValue)}.
*
* @since 7.0
*/
@Nullable
public static <T> T find(Iterable<? extends T> iterable,
Predicate<? super T> predicate, @Nullable T defaultValue) {
return Iterators.find(iterable.iterator(), predicate, defaultValue);
}
/**
* Returns an {@link Optional} containing the first element in {@code
* iterable} that satisfies the given predicate, if such an element exists.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
* null}. If {@code null} is matched in {@code iterable}, a
* NullPointerException will be thrown.
*
* @since 11.0
*/
public static <T> Optional<T> tryFind(Iterable<T> iterable,
Predicate<? super T> predicate) {
return Iterators.tryFind(iterable.iterator(), predicate);
}
/**
* Returns the index in {@code iterable} of the first element that satisfies
* the provided {@code predicate}, or {@code -1} if the Iterable has no such
* elements.
*
* <p>More formally, returns the lowest index {@code i} such that
* {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true},
* or {@code -1} if there is no such index.
*
* @since 2.0
*/
public static <T> int indexOf(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.indexOf(iterable.iterator(), predicate);
}
/**
* Returns an iterable that applies {@code function} to each element of {@code
* fromIterable}.
*
* <p>The returned iterable's iterator supports {@code remove()} if the
* provided iterator does. After a successful {@code remove()} call,
* {@code fromIterable} no longer contains the corresponding element.
*
* <p>If the input {@code Iterable} is known to be a {@code List} or other
* {@code Collection}, consider {@link Lists#transform} and {@link
* Collections2#transform}.
*/
public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable,
final Function<? super F, ? extends T> function) {
checkNotNull(fromIterable);
checkNotNull(function);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.transform(fromIterable.iterator(), function);
}
};
}
/**
* Returns the element at the specified position in an iterable.
*
* @param position position of the element to return
* @return the element at the specified position in {@code iterable}
* @throws IndexOutOfBoundsException if {@code position} is negative or
* greater than or equal to the size of {@code iterable}
*/
public static <T> T get(Iterable<T> iterable, int position) {
checkNotNull(iterable);
if (iterable instanceof List) {
return ((List<T>) iterable).get(position);
}
if (iterable instanceof Collection) {
// Can check both ends
Collection<T> collection = (Collection<T>) iterable;
Preconditions.checkElementIndex(position, collection.size());
} else {
// Can only check the lower end
checkNonnegativeIndex(position);
}
return Iterators.get(iterable.iterator(), position);
}
private static void checkNonnegativeIndex(int position) {
if (position < 0) {
throw new IndexOutOfBoundsException(
"position cannot be negative: " + position);
}
}
/**
* Returns the element at the specified position in an iterable or a default
* value otherwise.
*
* @param position position of the element to return
* @param defaultValue the default value to return if {@code position} is
* greater than or equal to the size of the iterable
* @return the element at the specified position in {@code iterable} or
* {@code defaultValue} if {@code iterable} contains fewer than
* {@code position + 1} elements.
* @throws IndexOutOfBoundsException if {@code position} is negative
* @since 4.0
*/
@Nullable
public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) {
checkNotNull(iterable);
checkNonnegativeIndex(position);
try {
return get(iterable, position);
} catch (IndexOutOfBoundsException e) {
return defaultValue;
}
}
/**
* Returns the first element in {@code iterable} or {@code defaultValue} if
* the iterable is empty. The {@link Iterators} analog to this method is
* {@link Iterators#getNext}.
*
* @param defaultValue the default value to return if the iterable is empty
* @return the first element of {@code iterable} or the default value
* @since 7.0
*/
@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) {
return Iterators.getNext(iterable.iterator(), defaultValue);
}
/**
* Returns the last element of {@code iterable}.
*
* @return the last element of {@code iterable}
* @throws NoSuchElementException if the iterable is empty
*/
public static <T> T getLast(Iterable<T> iterable) {
// TODO(kevinb): Support a concurrently modified collection?
if (iterable instanceof List) {
List<T> list = (List<T>) iterable;
if (list.isEmpty()) {
throw new NoSuchElementException();
}
return getLastInNonemptyList(list);
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<T> sortedSet = (SortedSet<T>) iterable;
return sortedSet.last();
}
return Iterators.getLast(iterable.iterator());
}
/**
* Returns the last element of {@code iterable} or {@code defaultValue} if
* the iterable is empty.
*
* @param defaultValue the value to return if {@code iterable} is empty
* @return the last element of {@code iterable} or the default value
* @since 3.0
*/
@Nullable
public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) {
if (iterable instanceof Collection) {
Collection<? extends T> collection = Collections2.cast(iterable);
if (collection.isEmpty()) {
return defaultValue;
}
}
if (iterable instanceof List) {
List<? extends T> list = Lists.cast(iterable);
return getLastInNonemptyList(list);
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<? extends T> sortedSet = Sets.cast(iterable);
return sortedSet.last();
}
return Iterators.getLast(iterable.iterator(), defaultValue);
}
private static <T> T getLastInNonemptyList(List<T> list) {
return list.get(list.size() - 1);
}
/**
* Returns a view of {@code iterable} that skips its first
* {@code numberToSkip} elements. If {@code iterable} contains fewer than
* {@code numberToSkip} elements, the returned iterable skips all of its
* elements.
*
* <p>Modifications to the underlying {@link Iterable} before a call to
* {@code iterator()} are reflected in the returned iterator. That is, the
* iterator skips the first {@code numberToSkip} elements that exist when the
* {@code Iterator} is created, not when {@code skip()} is called.
*
* <p>The returned iterable's iterator supports {@code remove()} if the
* iterator of the underlying iterable supports it. Note that it is
* <i>not</i> possible to delete the last skipped element by immediately
* calling {@code remove()} on that iterator, as the {@code Iterator}
* contract states that a call to {@code remove()} before a call to
* {@code next()} will throw an {@link IllegalStateException}.
*
* @since 3.0
*/
public static <T> Iterable<T> skip(final Iterable<T> iterable,
final int numberToSkip) {
checkNotNull(iterable);
checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
if (iterable instanceof List) {
final List<T> list = (List<T>) iterable;
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
// TODO(kevinb): Support a concurrently modified collection?
return (numberToSkip >= list.size())
? Iterators.<T>emptyIterator()
: list.subList(numberToSkip, list.size()).iterator();
}
};
}
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
final Iterator<T> iterator = iterable.iterator();
Iterators.advance(iterator, numberToSkip);
/*
* We can't just return the iterator because an immediate call to its
* remove() method would remove one of the skipped elements instead of
* throwing an IllegalStateException.
*/
return new Iterator<T>() {
boolean atStart = true;
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return iterator.next();
} finally {
atStart = false;
}
}
@Override
public void remove() {
if (atStart) {
throw new IllegalStateException();
}
iterator.remove();
}
};
}
};
}
/**
* Creates an iterable with the first {@code limitSize} elements of the given
* iterable. If the original iterable does not contain that many elements, the
* returned iterator will have the same behavior as the original iterable. The
* returned iterable's iterator supports {@code remove()} if the original
* iterator does.
*
* @param iterable the iterable to limit
* @param limitSize the maximum number of elements in the returned iterator
* @throws IllegalArgumentException if {@code limitSize} is negative
* @since 3.0
*/
public static <T> Iterable<T> limit(
final Iterable<T> iterable, final int limitSize) {
checkNotNull(iterable);
checkArgument(limitSize >= 0, "limit is negative");
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.limit(iterable.iterator(), limitSize);
}
};
}
/**
* Returns a view of the supplied iterable that wraps each generated
* {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}.
*
* <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will
* get entries from {@link Queue#remove()} since {@link Queue}'s iteration
* order is undefined. Calling {@link Iterator#hasNext()} on a generated
* iterator from the returned iterable may cause an item to be immediately
* dequeued for return on a subsequent call to {@link Iterator#next()}.
*
* @param iterable the iterable to wrap
* @return a view of the supplied iterable that wraps each generated iterator
* through {@link Iterators#consumingIterator(Iterator)}; for queues,
* an iterable that generates iterators that return and consume the
* queue's elements in queue order
*
* @see Iterators#consumingIterator(Iterator)
* @since 2.0
*/
public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) {
if (iterable instanceof Queue) {
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return new ConsumingQueueIterator<T>((Queue<T>) iterable);
}
};
}
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.consumingIterator(iterable.iterator());
}
};
}
private static class ConsumingQueueIterator<T> extends AbstractIterator<T> {
private final Queue<T> queue;
private ConsumingQueueIterator(Queue<T> queue) {
this.queue = queue;
}
@Override public T computeNext() {
try {
return queue.remove();
} catch (NoSuchElementException e) {
return endOfData();
}
}
}
// Methods only in Iterables, not in Iterators
/**
* Determines if the given iterable contains no elements.
*
* <p>There is no precise {@link Iterator} equivalent to this method, since
* one can only ask an iterator whether it has any elements <i>remaining</i>
* (which one does using {@link Iterator#hasNext}).
*
* @return {@code true} if the iterable contains no elements
*/
public static boolean isEmpty(Iterable<?> iterable) {
if (iterable instanceof Collection) {
return ((Collection<?>) iterable).isEmpty();
}
return !iterable.iterator().hasNext();
}
/**
* Returns an iterable over the merged contents of all given
* {@code iterables}. Equivalent entries will not be de-duplicated.
*
* <p>Callers must ensure that the source {@code iterables} are in
* non-descending order as this method does not sort its input.
*
* <p>For any equivalent elements across all {@code iterables}, it is
* undefined which element is returned first.
*
* @since 11.0
*/
@Beta
public static <T> Iterable<T> mergeSorted(
final Iterable<? extends Iterable<? extends T>> iterables,
final Comparator<? super T> comparator) {
checkNotNull(iterables, "iterables");
checkNotNull(comparator, "comparator");
Iterable<T> iterable = new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.mergeSorted(
Iterables.transform(iterables, Iterables.<T>toIterator()),
comparator);
}
};
return new UnmodifiableIterable<T>(iterable);
}
// TODO(user): Is this the best place for this? Move to fluent functions?
// Useful as a public method?
private static <T> Function<Iterable<? extends T>, Iterator<? extends T>>
toIterator() {
return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
@Override
public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
return iterable.iterator();
}
};
}
}
| Java |
/*
* Copyright (C) 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;
/**
* GWT emulation of {@link EmptyImmutableSet}.
*
* @author Hayward Chan
*/
final class EmptyImmutableSet extends ForwardingImmutableSet<Object> {
private EmptyImmutableSet() {
super(Collections.emptySet());
}
static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
/**
* An {@code ImmutableSet} whose elements are derived by transforming another collection's elements,
* useful for {@code ImmutableMap.keySet()}.
*
* @author Jesse Wilson
*/
@GwtCompatible(emulated = true)
abstract class TransformedImmutableSet<D, E> extends ImmutableSet<E> {
/*
* TODO(cpovirk): using an abstract source() method instead of a field could simplify
* ImmutableMapKeySet, which currently has to pass in entrySet() manually
*/
final ImmutableCollection<D> source;
final int hashCode;
TransformedImmutableSet(ImmutableCollection<D> source) {
this.source = source;
this.hashCode = Sets.hashCodeImpl(this);
}
TransformedImmutableSet(ImmutableCollection<D> source, int hashCode) {
this.source = source;
this.hashCode = hashCode;
}
abstract E transform(D element);
@Override
public int size() {
return source.size();
}
@Override public boolean isEmpty() {
return false;
}
@Override public UnmodifiableIterator<E> iterator() {
final Iterator<D> backingIterator = source.iterator();
return new UnmodifiableIterator<E>() {
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public E next() {
return transform(backingIterator.next());
}
};
}
@Override public Object[] toArray() {
return toArray(new Object[size()]);
}
@Override public <T> T[] toArray(T[] array) {
return ObjectArrays.toArrayImpl(this, array);
}
@Override public final int hashCode() {
return hashCode;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.unmodifiableList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.util.AbstractSequentialList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An implementation of {@code ListMultimap} that supports deterministic
* iteration order for both keys and values. The iteration order is preserved
* across non-distinct key values. For example, for the following multimap
* definition: <pre> {@code
*
* Multimap<K, V> multimap = LinkedListMultimap.create();
* multimap.put(key1, foo);
* multimap.put(key2, bar);
* multimap.put(key1, baz);}</pre>
*
* ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]},
* and similarly for {@link #entries()}. Unlike {@link LinkedHashMultimap}, the
* iteration order is kept consistent between keys, entries and values. For
* example, calling: <pre> {@code
*
* map.remove(key1, foo);}</pre>
*
* changes the entries iteration order to {@code [key2=bar, key1=baz]} and the
* key iteration order to {@code [key2, key1]}. The {@link #entries()} iterator
* returns mutable map entries, and {@link #replaceValues} attempts to preserve
* iteration order as much as possible.
*
* <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate
* through the keys in the order they were first added to the multimap.
* Similarly, {@link #get}, {@link #removeAll}, and {@link #replaceValues}
* return collections that iterate through the values in the order they were
* added. The collections generated by {@link #entries()}, {@link #keys()}, and
* {@link #values} iterate across the key-value mappings in the order they were
* added to the multimap.
*
* <p>The {@link #values()} and {@link #entries()} methods both return a
* {@code List}, instead of the {@code Collection} specified by the {@link
* ListMultimap} interface.
*
* <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()},
* {@link #values}, {@link #entries()}, and {@link #asMap} return collections
* that are views of the multimap. If the multimap is modified while an
* iteration over any of those collections is in progress, except through the
* iterator's methods, the results of the iteration are undefined.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedListMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class LinkedListMultimap<K, V>
implements ListMultimap<K, V>, Serializable {
/*
* Order is maintained using a linked list containing all key-value pairs. In
* addition, a series of disjoint linked lists of "siblings", each containing
* the values for a specific key, is used to implement {@link
* ValueForKeyIterator} in constant time.
*/
private static final class Node<K, V> {
final K key;
V value;
Node<K, V> next; // the next node (with any key)
Node<K, V> previous; // the previous node (with any key)
Node<K, V> nextSibling; // the next node with the same key
Node<K, V> previousSibling; // the previous node with the same key
Node(@Nullable K key, @Nullable V value) {
this.key = key;
this.value = value;
}
@Override public String toString() {
return key + "=" + value;
}
}
private transient Node<K, V> head; // the head for all keys
private transient Node<K, V> tail; // the tail for all keys
private transient Multiset<K> keyCount; // the number of values for each key
private transient Map<K, Node<K, V>> keyToKeyHead; // the head for a given key
private transient Map<K, Node<K, V>> keyToKeyTail; // the tail for a given key
/**
* Creates a new, empty {@code LinkedListMultimap} with the default initial
* capacity.
*/
public static <K, V> LinkedListMultimap<K, V> create() {
return new LinkedListMultimap<K, V>();
}
/**
* Constructs an empty {@code LinkedListMultimap} with enough capacity to hold
* the specified number of keys without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @throws IllegalArgumentException if {@code expectedKeys} is negative
*/
public static <K, V> LinkedListMultimap<K, V> create(int expectedKeys) {
return new LinkedListMultimap<K, V>(expectedKeys);
}
/**
* Constructs a {@code LinkedListMultimap} with the same mappings as the
* specified {@code Multimap}. The new multimap has the same
* {@link Multimap#entries()} iteration order as the input multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> LinkedListMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new LinkedListMultimap<K, V>(multimap);
}
LinkedListMultimap() {
keyCount = LinkedHashMultiset.create();
keyToKeyHead = Maps.newHashMap();
keyToKeyTail = Maps.newHashMap();
}
private LinkedListMultimap(int expectedKeys) {
keyCount = LinkedHashMultiset.create(expectedKeys);
keyToKeyHead = Maps.newHashMapWithExpectedSize(expectedKeys);
keyToKeyTail = Maps.newHashMapWithExpectedSize(expectedKeys);
}
private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size());
putAll(multimap);
}
/**
* Adds a new node for the specified key-value pair before the specified
* {@code nextSibling} element, or at the end of the list if {@code
* nextSibling} is null. Note: if {@code nextSibling} is specified, it MUST be
* for an node for the same {@code key}!
*/
private Node<K, V> addNode(
@Nullable K key, @Nullable V value, @Nullable Node<K, V> nextSibling) {
Node<K, V> node = new Node<K, V>(key, value);
if (head == null) { // empty list
head = tail = node;
keyToKeyHead.put(key, node);
keyToKeyTail.put(key, node);
} else if (nextSibling == null) { // non-empty list, add to tail
tail.next = node;
node.previous = tail;
Node<K, V> keyTail = keyToKeyTail.get(key);
if (keyTail == null) { // first for this key
keyToKeyHead.put(key, node);
} else {
keyTail.nextSibling = node;
node.previousSibling = keyTail;
}
keyToKeyTail.put(key, node);
tail = node;
} else { // non-empty list, insert before nextSibling
node.previous = nextSibling.previous;
node.previousSibling = nextSibling.previousSibling;
node.next = nextSibling;
node.nextSibling = nextSibling;
if (nextSibling.previousSibling == null) { // nextSibling was key head
keyToKeyHead.put(key, node);
} else {
nextSibling.previousSibling.nextSibling = node;
}
if (nextSibling.previous == null) { // nextSibling was head
head = node;
} else {
nextSibling.previous.next = node;
}
nextSibling.previous = node;
nextSibling.previousSibling = node;
}
keyCount.add(key);
return node;
}
/**
* Removes the specified node from the linked list. This method is only
* intended to be used from the {@code Iterator} classes. See also {@link
* LinkedListMultimap#removeAllNodes(Object)}.
*/
private void removeNode(Node<K, V> node) {
if (node.previous != null) {
node.previous.next = node.next;
} else { // node was head
head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else { // node was tail
tail = node.previous;
}
if (node.previousSibling != null) {
node.previousSibling.nextSibling = node.nextSibling;
} else if (node.nextSibling != null) { // node was key head
keyToKeyHead.put(node.key, node.nextSibling);
} else {
keyToKeyHead.remove(node.key); // don't leak a key-null entry
}
if (node.nextSibling != null) {
node.nextSibling.previousSibling = node.previousSibling;
} else if (node.previousSibling != null) { // node was key tail
keyToKeyTail.put(node.key, node.previousSibling);
} else {
keyToKeyTail.remove(node.key); // don't leak a key-null entry
}
keyCount.remove(node.key);
}
/** Removes all nodes for the specified key. */
private void removeAllNodes(@Nullable Object key) {
for (Iterator<V> i = new ValueForKeyIterator(key); i.hasNext();) {
i.next();
i.remove();
}
}
/** Helper method for verifying that an iterator element is present. */
private static void checkElement(@Nullable Object node) {
if (node == null) {
throw new NoSuchElementException();
}
}
/** An {@code Iterator} over all nodes. */
private class NodeIterator implements ListIterator<Node<K, V>> {
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
NodeIterator() {
next = head;
}
NodeIterator(int index) {
int size = size();
Preconditions.checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = head;
while (index-- > 0) {
next();
}
}
current = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Node<K, V> next() {
checkElement(next);
previous = current = next;
next = next.next;
nextIndex++;
return current;
}
@Override
public void remove() {
checkState(current != null);
if (current != next) { // after call to next()
previous = current.previous;
nextIndex--;
} else { // after call to previous()
next = current.next;
}
removeNode(current);
current = null;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@Override
public Node<K, V> previous() {
checkElement(previous);
next = current = previous;
previous = previous.previous;
nextIndex--;
return current;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void set(Node<K, V> e) {
throw new UnsupportedOperationException();
}
@Override
public void add(Node<K, V> e) {
throw new UnsupportedOperationException();
}
void setValue(V value) {
checkState(current != null);
current.value = value;
}
}
/** An {@code Iterator} over distinct keys in key head order. */
private class DistinctKeyIterator implements Iterator<K> {
final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size());
Node<K, V> next = head;
Node<K, V> current;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public K next() {
checkElement(next);
current = next;
seenKeys.add(current.key);
do { // skip ahead to next unseen key
next = next.next;
} while ((next != null) && !seenKeys.add(next.key));
return current.key;
}
@Override
public void remove() {
checkState(current != null);
removeAllNodes(current.key);
current = null;
}
}
/** A {@code ListIterator} over values for a specified key. */
private class ValueForKeyIterator implements ListIterator<V> {
final Object key;
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
/** Constructs a new iterator over all values for the specified key. */
ValueForKeyIterator(@Nullable Object key) {
this.key = key;
next = keyToKeyHead.get(key);
}
/**
* Constructs a new iterator over all values for the specified key starting
* at the specified index. This constructor is optimized so that it starts
* at either the head or the tail, depending on which is closer to the
* specified index. This allows adds to the tail to be done in constant
* time.
*
* @throws IndexOutOfBoundsException if index is invalid
*/
public ValueForKeyIterator(@Nullable Object key, int index) {
int size = keyCount.count(key);
Preconditions.checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = keyToKeyTail.get(key);
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = keyToKeyHead.get(key);
while (index-- > 0) {
next();
}
}
this.key = key;
current = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public V next() {
checkElement(next);
previous = current = next;
next = next.nextSibling;
nextIndex++;
return current.value;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@Override
public V previous() {
checkElement(previous);
next = current = previous;
previous = previous.previousSibling;
nextIndex--;
return current.value;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void remove() {
checkState(current != null);
if (current != next) { // after call to next()
previous = current.previousSibling;
nextIndex--;
} else { // after call to previous()
next = current.nextSibling;
}
removeNode(current);
current = null;
}
@Override
public void set(V value) {
checkState(current != null);
current.value = value;
}
@Override
@SuppressWarnings("unchecked")
public void add(V value) {
previous = addNode((K) key, value, next);
nextIndex++;
current = null;
}
}
// Query Operations
@Override
public int size() {
return keyCount.size();
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public boolean containsKey(@Nullable Object key) {
return keyToKeyHead.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Iterator<Node<K, V>> i = new NodeIterator(); i.hasNext();) {
if (Objects.equal(i.next().value, value)) {
return true;
}
}
return false;
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
for (Iterator<V> i = new ValueForKeyIterator(key); i.hasNext();) {
if (Objects.equal(i.next(), value)) {
return true;
}
}
return false;
}
// Modification Operations
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} always
*/
@Override
public boolean put(@Nullable K key, @Nullable V value) {
addNode(key, value, null);
return true;
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
Iterator<V> values = new ValueForKeyIterator(key);
while (values.hasNext()) {
if (Objects.equal(values.next(), value)) {
values.remove();
return true;
}
}
return false;
}
// Bulk Operations
@Override
public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
boolean changed = false;
for (V value : values) {
changed |= put(key, value);
}
return changed;
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
boolean changed = false;
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
changed |= put(entry.getKey(), entry.getValue());
}
return changed;
}
/**
* {@inheritDoc}
*
* <p>If any entries for the specified {@code key} already exist in the
* multimap, their values are changed in-place without affecting the iteration
* order.
*
* <p>The returned list is immutable and implements
* {@link java.util.RandomAccess}.
*/
@Override
public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
List<V> oldValues = getCopy(key);
ListIterator<V> keyValues = new ValueForKeyIterator(key);
Iterator<? extends V> newValues = values.iterator();
// Replace existing values, if any.
while (keyValues.hasNext() && newValues.hasNext()) {
keyValues.next();
keyValues.set(newValues.next());
}
// Remove remaining old values, if any.
while (keyValues.hasNext()) {
keyValues.next();
keyValues.remove();
}
// Add remaining new values, if any.
while (newValues.hasNext()) {
keyValues.add(newValues.next());
}
return oldValues;
}
private List<V> getCopy(@Nullable Object key) {
return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key)));
}
/**
* {@inheritDoc}
*
* <p>The returned list is immutable and implements
* {@link java.util.RandomAccess}.
*/
@Override
public List<V> removeAll(@Nullable Object key) {
List<V> oldValues = getCopy(key);
removeAllNodes(key);
return oldValues;
}
@Override
public void clear() {
head = null;
tail = null;
keyCount.clear();
keyToKeyHead.clear();
keyToKeyTail.clear();
}
// Views
/**
* {@inheritDoc}
*
* <p>If the multimap is modified while an iteration over the list is in
* progress (except through the iterator's own {@code add}, {@code set} or
* {@code remove} operations) the results of the iteration are undefined.
*
* <p>The returned list is not serializable and does not have random access.
*/
@Override
public List<V> get(final @Nullable K key) {
return new AbstractSequentialList<V>() {
@Override public int size() {
return keyCount.count(key);
}
@Override public ListIterator<V> listIterator(int index) {
return new ValueForKeyIterator(key, index);
}
@Override public boolean removeAll(Collection<?> c) {
return Iterators.removeAll(iterator(), c);
}
@Override public boolean retainAll(Collection<?> c) {
return Iterators.retainAll(iterator(), c);
}
};
}
private transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
keySet = result = new Sets.ImprovedAbstractSet<K>() {
@Override public int size() {
return keyCount.elementSet().size();
}
@Override public Iterator<K> iterator() {
return new DistinctKeyIterator();
}
@Override public boolean contains(Object key) { // for performance
return containsKey(key);
}
@Override
public boolean remove(Object o) { // for performance
return !LinkedListMultimap.this.removeAll(o).isEmpty();
}
};
}
return result;
}
private transient Multiset<K> keys;
@Override
public Multiset<K> keys() {
Multiset<K> result = keys;
if (result == null) {
keys = result = new MultisetView();
}
return result;
}
private class MultisetView extends AbstractMultiset<K> {
@Override
public int size() {
return keyCount.size();
}
@Override
public int count(Object element) {
return keyCount.count(element);
}
@Override
Iterator<Entry<K>> entryIterator() {
return new TransformedIterator<K, Entry<K>>(new DistinctKeyIterator()) {
@Override
Entry<K> transform(final K key) {
return new Multisets.AbstractEntry<K>() {
@Override
public K getElement() {
return key;
}
@Override
public int getCount() {
return keyCount.count(key);
}
};
}
};
}
@Override
int distinctElements() {
return elementSet().size();
}
@Override public Iterator<K> iterator() {
return new TransformedIterator<Node<K, V>, K>(new NodeIterator()) {
@Override
K transform(Node<K, V> node) {
return node.key;
}
};
}
@Override
public int remove(@Nullable Object key, int occurrences) {
checkArgument(occurrences >= 0);
int oldCount = count(key);
Iterator<V> values = new ValueForKeyIterator(key);
while ((occurrences-- > 0) && values.hasNext()) {
values.next();
values.remove();
}
return oldCount;
}
@Override
public Set<K> elementSet() {
return keySet();
}
@Override public boolean equals(@Nullable Object object) {
return keyCount.equals(object);
}
@Override public int hashCode() {
return keyCount.hashCode();
}
@Override public String toString() {
return keyCount.toString(); // XXX observe order?
}
}
private transient List<V> valuesList;
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* in the order they were added to the multimap. Because the values may have
* duplicates and follow the insertion ordering, this method returns a {@link
* List}, instead of the {@link Collection} specified in the {@link
* ListMultimap} interface.
*/
@Override
public List<V> values() {
List<V> result = valuesList;
if (result == null) {
valuesList = result = new AbstractSequentialList<V>() {
@Override public int size() {
return keyCount.size();
}
@Override
public ListIterator<V> listIterator(int index) {
final NodeIterator nodes = new NodeIterator(index);
return new TransformedListIterator<Node<K, V>, V>(nodes) {
@Override
V transform(Node<K, V> node) {
return node.value;
}
@Override
public void set(V value) {
nodes.setValue(value);
}
};
}
};
}
return result;
}
private static <K, V> Entry<K, V> createEntry(final Node<K, V> node) {
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return node.key;
}
@Override public V getValue() {
return node.value;
}
@Override public V setValue(V value) {
V oldValue = node.value;
node.value = value;
return oldValue;
}
};
}
private transient List<Entry<K, V>> entries;
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the entries
* in the order they were added to the multimap. Because the entries may have
* duplicates and follow the insertion ordering, this method returns a {@link
* List}, instead of the {@link Collection} specified in the {@link
* ListMultimap} interface.
*
* <p>An entry's {@link Entry#getKey} method always returns the same key,
* regardless of what happens subsequently. As long as the corresponding
* key-value mapping is not removed from the multimap, {@link Entry#getValue}
* returns the value from the multimap, which may change over time, and {@link
* Entry#setValue} modifies that value. Removing the mapping from the
* multimap does not alter the value returned by {@code getValue()}, though a
* subsequent {@code setValue()} call won't update the multimap but will lead
* to a revised value being returned by {@code getValue()}.
*/
@Override
public List<Entry<K, V>> entries() {
List<Entry<K, V>> result = entries;
if (result == null) {
entries = result = new AbstractSequentialList<Entry<K, V>>() {
@Override public int size() {
return keyCount.size();
}
@Override public ListIterator<Entry<K, V>> listIterator(int index) {
return new TransformedListIterator<Node<K, V>, Entry<K, V>>(new NodeIterator(index)) {
@Override
Entry<K, V> transform(Node<K, V> node) {
return createEntry(node);
}
};
}
};
}
return result;
}
private transient Map<K, Collection<V>> map;
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = map;
if (result == null) {
map = result = new Multimaps.AsMap<K, V>() {
@Override
public int size() {
return keyCount.elementSet().size();
}
@Override
Multimap<K, V> multimap() {
return LinkedListMultimap.this;
}
@Override
Iterator<Entry<K, Collection<V>>> entryIterator() {
return new TransformedIterator<K, Entry<K, Collection<V>>>(new DistinctKeyIterator()) {
@Override
Entry<K, Collection<V>> transform(final K key) {
return new AbstractMapEntry<K, Collection<V>>() {
@Override public K getKey() {
return key;
}
@Override public Collection<V> getValue() {
return LinkedListMultimap.this.get(key);
}
};
}
};
}
};
}
return result;
}
// Comparison and hashing
/**
* Compares the specified object to this multimap for equality.
*
* <p>Two {@code ListMultimap} instances are equal if, for each key, they
* contain the same values in the same order. If the value orderings disagree,
* the multimaps will not be considered equal.
*/
@Override public boolean equals(@Nullable Object other) {
if (other == this) {
return true;
}
if (other instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) other;
return this.asMap().equals(that.asMap());
}
return false;
}
/**
* Returns the hash code for this multimap.
*
* <p>The hash code of a multimap is defined as the hash code of the map view,
* as returned by {@link Multimap#asMap}.
*/
@Override public int hashCode() {
return asMap().hashCode();
}
/**
* Returns a string representation of the multimap, generated by calling
* {@code toString} on the map returned by {@link Multimap#asMap}.
*
* @return a string representation of the multimap
*/
@Override public String toString() {
return asMap().toString();
}
}
| 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 ForwardingImmutableMap<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 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 static java.util.Collections.emptyList;
import java.util.List;
/**
* GWT emulated version of EmptyImmutableList.
*
* @author Hayward Chan
*/
final class EmptyImmutableList extends ForwardingImmutableList<Object> {
static final EmptyImmutableList INSTANCE = new EmptyImmutableList();
private EmptyImmutableList() {
}
@Override List<Object> delegateList() {
return emptyList();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map.Entry;
/**
* {@code values()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class ImmutableMapValues<K, V> extends ImmutableCollection<V> {
ImmutableMapValues() {}
abstract ImmutableMap<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public UnmodifiableIterator<V> iterator() {
return Maps.valueIterator(map().entrySet().iterator());
}
@Override
public boolean contains(Object object) {
return map().containsValue(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
ImmutableList<V> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map().entrySet().asList();
return new ImmutableAsList<V>() {
@Override
public V get(int index) {
return entryList.get(index).getValue();
}
@Override
ImmutableCollection<V> delegateCollection() {
return ImmutableMapValues.this;
}
};
}
}
| 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.Set;
/**
* GWT emulation of {@link ImmutableEnumSet}. The type parameter is not bounded
* by {@code Enum<E>} to avoid code-size bloat.
*
* @author Hayward Chan
*/
final class ImmutableEnumSet<E> extends ForwardingImmutableSet<E> {
public ImmutableEnumSet(Set<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 java.util.Map;
/**
* GWT emulation of {@link ImmutableBiMap}.
*
* @author Hayward Chan
*/
public abstract class ImmutableBiMap<K, V> extends ForwardingImmutableMap<K, V>
implements BiMap<K, V> {
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableBiMap<K, V> of() {
return (ImmutableBiMap<K, V>) EmptyImmutableBiMap.INSTANCE;
}
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();
}
}
| 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;
}
@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 static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* A multiset which maintains the ordering of its elements, according to either their natural order
* or an explicit {@link Comparator}. In all cases, this implementation uses
* {@link Comparable#compareTo} or {@link Comparator#compare} instead of {@link Object#equals} to
* determine equivalence of instances.
*
* <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as explained by the
* {@link Comparable} class specification. Otherwise, the resulting multiset will violate the
* {@link java.util.Collection} contract, which is specified in terms of {@link Object#equals}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Louis Wasserman
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class TreeMultiset<E> extends AbstractSortedMultiset<E> implements Serializable {
/**
* Creates a new, empty multiset, sorted according to the elements' natural order. All elements
* inserted into the multiset must implement the {@code Comparable} interface. Furthermore, all
* such elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the
* user attempts to add an element to the multiset that violates this constraint (for example,
* the user attempts to add a string element to a set whose elements are integers), the
* {@code add(Object)} call will throw a {@code ClassCastException}.
*
* <p>The type specification is {@code <E extends Comparable>}, instead of the more specific
* {@code <E extends Comparable<? super E>>}, to support classes defined without generics.
*/
public static <E extends Comparable> TreeMultiset<E> create() {
return new TreeMultiset<E>(Ordering.natural());
}
/**
* Creates a new, empty multiset, sorted according to the specified comparator. All elements
* inserted into the multiset must be <i>mutually comparable</i> by the specified comparator:
* {@code comparator.compare(e1,
* e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in
* the multiset. If the user attempts to add an element to the multiset that violates this
* constraint, the {@code add(Object)} call will throw a {@code ClassCastException}.
*
* @param comparator
* the comparator that will be used to sort this multiset. A null value indicates that
* the elements' <i>natural ordering</i> should be used.
*/
@SuppressWarnings("unchecked")
public static <E> TreeMultiset<E> create(@Nullable Comparator<? super E> comparator) {
return (comparator == null)
? new TreeMultiset<E>((Comparator) Ordering.natural())
: new TreeMultiset<E>(comparator);
}
/**
* Creates an empty multiset containing the given initial elements, sorted according to the
* elements' natural order.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
*
* <p>The type specification is {@code <E extends Comparable>}, instead of the more specific
* {@code <E extends Comparable<? super E>>}, to support classes defined without generics.
*/
public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) {
TreeMultiset<E> multiset = create();
Iterables.addAll(multiset, elements);
return multiset;
}
private final transient Reference<AvlNode<E>> rootReference;
private final transient GeneralRange<E> range;
private final transient AvlNode<E> header;
TreeMultiset(Reference<AvlNode<E>> rootReference, GeneralRange<E> range, AvlNode<E> endLink) {
super(range.comparator());
this.rootReference = rootReference;
this.range = range;
this.header = endLink;
}
TreeMultiset(Comparator<? super E> comparator) {
super(comparator);
this.range = GeneralRange.all(comparator);
this.header = new AvlNode<E>(null, 1);
successor(header, header);
this.rootReference = new Reference<AvlNode<E>>();
}
/**
* A function which can be summed across a subtree.
*/
private enum Aggregate {
SIZE {
@Override
int nodeAggregate(AvlNode<?> node) {
return node.elemCount;
}
@Override
long treeAggregate(@Nullable AvlNode<?> root) {
return (root == null) ? 0 : root.totalCount;
}
},
DISTINCT {
@Override
int nodeAggregate(AvlNode<?> node) {
return 1;
}
@Override
long treeAggregate(@Nullable AvlNode<?> root) {
return (root == null) ? 0 : root.distinctElements;
}
};
abstract int nodeAggregate(AvlNode<?> node);
abstract long treeAggregate(@Nullable AvlNode<?> root);
}
private long aggregateForEntries(Aggregate aggr) {
AvlNode<E> root = rootReference.get();
long total = aggr.treeAggregate(root);
if (range.hasLowerBound()) {
total -= aggregateBelowRange(aggr, root);
}
if (range.hasUpperBound()) {
total -= aggregateAboveRange(aggr, root);
}
return total;
}
private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode<E> node) {
if (node == null) {
return 0;
}
int cmp = comparator().compare(range.getLowerEndpoint(), node.elem);
if (cmp < 0) {
return aggregateBelowRange(aggr, node.left);
} else if (cmp == 0) {
switch (range.getLowerBoundType()) {
case OPEN:
return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left);
case CLOSED:
return aggr.treeAggregate(node.left);
default:
throw new AssertionError();
}
} else {
return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node)
+ aggregateBelowRange(aggr, node.right);
}
}
private long aggregateAboveRange(Aggregate aggr, @Nullable AvlNode<E> node) {
if (node == null) {
return 0;
}
int cmp = comparator().compare(range.getUpperEndpoint(), node.elem);
if (cmp > 0) {
return aggregateAboveRange(aggr, node.right);
} else if (cmp == 0) {
switch (range.getUpperBoundType()) {
case OPEN:
return aggr.nodeAggregate(node) + aggr.treeAggregate(node.right);
case CLOSED:
return aggr.treeAggregate(node.right);
default:
throw new AssertionError();
}
} else {
return aggr.treeAggregate(node.right) + aggr.nodeAggregate(node)
+ aggregateAboveRange(aggr, node.left);
}
}
@Override
public int size() {
return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE));
}
@Override
int distinctElements() {
return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT));
}
@Override
public int count(@Nullable Object element) {
try {
@SuppressWarnings("unchecked")
E e = (E) element;
AvlNode<E> root = rootReference.get();
if (!range.contains(e) || root == null) {
return 0;
}
return root.count(comparator(), e);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
@Override
public int add(@Nullable E element, int occurrences) {
checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences);
if (occurrences == 0) {
return count(element);
}
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
comparator().compare(element, element);
AvlNode<E> newRoot = new AvlNode<E>(element, occurrences);
successor(header, newRoot, header);
rootReference.checkAndSet(root, newRoot);
return 0;
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.add(comparator(), element, occurrences, result);
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences);
if (occurrences == 0) {
return count(element);
}
AvlNode<E> root = rootReference.get();
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot;
try {
@SuppressWarnings("unchecked")
E e = (E) element;
if (!range.contains(e) || root == null) {
return 0;
}
newRoot = root.remove(comparator(), e, occurrences, result);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public int setCount(@Nullable E element, int count) {
checkArgument(count >= 0);
if (!range.contains(element)) {
checkArgument(count == 0);
return 0;
}
AvlNode<E> root = rootReference.get();
if (root == null) {
if (count > 0) {
add(element, count);
}
return 0;
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.setCount(comparator(), element, count, result);
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public boolean setCount(@Nullable E element, int oldCount, int newCount) {
checkArgument(newCount >= 0);
checkArgument(oldCount >= 0);
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
if (oldCount == 0) {
if (newCount > 0) {
add(element, newCount);
}
return true;
} else {
return false;
}
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.setCount(comparator(), element, oldCount, newCount, result);
rootReference.checkAndSet(root, newRoot);
return result[0] == oldCount;
}
private Entry<E> wrapEntry(final AvlNode<E> baseEntry) {
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return baseEntry.getElement();
}
@Override
public int getCount() {
int result = baseEntry.getCount();
if (result == 0) {
return count(getElement());
} else {
return result;
}
}
};
}
/**
* Returns the first node in the tree that is in range.
*/
@Nullable private AvlNode<E> firstNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasLowerBound()) {
E endpoint = range.getLowerEndpoint();
node = rootReference.get().ceiling(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getLowerBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.succ;
}
} else {
node = header.succ;
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
@Nullable private AvlNode<E> lastNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasUpperBound()) {
E endpoint = range.getUpperEndpoint();
node = rootReference.get().floor(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getUpperBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.pred;
}
} else {
node = header.pred;
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
@Override
Iterator<Entry<E>> entryIterator() {
return new Iterator<Entry<E>>() {
AvlNode<E> current = firstNode();
Entry<E> prevEntry;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else if (range.tooHigh(current.getElement())) {
current = null;
return false;
} else {
return true;
}
}
@Override
public Entry<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<E> result = wrapEntry(current);
prevEntry = result;
if (current.succ == header) {
current = null;
} else {
current = current.succ;
}
return result;
}
@Override
public void remove() {
checkState(prevEntry != null);
setCount(prevEntry.getElement(), 0);
prevEntry = null;
}
};
}
@Override
Iterator<Entry<E>> descendingEntryIterator() {
return new Iterator<Entry<E>>() {
AvlNode<E> current = lastNode();
Entry<E> prevEntry = null;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else if (range.tooLow(current.getElement())) {
current = null;
return false;
} else {
return true;
}
}
@Override
public Entry<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<E> result = wrapEntry(current);
prevEntry = result;
if (current.pred == header) {
current = null;
} else {
current = current.pred;
}
return result;
}
@Override
public void remove() {
checkState(prevEntry != null);
setCount(prevEntry.getElement(), 0);
prevEntry = null;
}
};
}
@Override
public SortedMultiset<E> headMultiset(@Nullable E upperBound, BoundType boundType) {
return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.upTo(
comparator(),
upperBound,
boundType)), header);
}
@Override
public SortedMultiset<E> tailMultiset(@Nullable E lowerBound, BoundType boundType) {
return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.downTo(
comparator(),
lowerBound,
boundType)), header);
}
static int distinctElements(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.distinctElements;
}
private static final class Reference<T> {
@Nullable private T value;
@Nullable public T get() {
return value;
}
public void checkAndSet(@Nullable T expected, T newValue) {
if (value != expected) {
throw new ConcurrentModificationException();
}
value = newValue;
}
}
private static final class AvlNode<E> extends Multisets.AbstractEntry<E> {
@Nullable private final E elem;
// elemCount is 0 iff this node has been deleted.
private int elemCount;
private int distinctElements;
private long totalCount;
private int height;
private AvlNode<E> left;
private AvlNode<E> right;
private AvlNode<E> pred;
private AvlNode<E> succ;
AvlNode(@Nullable E elem, int elemCount) {
checkArgument(elemCount > 0);
this.elem = elem;
this.elemCount = elemCount;
this.totalCount = elemCount;
this.distinctElements = 1;
this.height = 1;
this.left = null;
this.right = null;
}
public int count(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
return (left == null) ? 0 : left.count(comparator, e);
} else if (cmp > 0) {
return (right == null) ? 0 : right.count(comparator, e);
} else {
return elemCount;
}
}
private AvlNode<E> addRightChild(E e, int count) {
right = new AvlNode<E>(e, count);
successor(this, right, succ);
height = Math.max(2, height);
distinctElements++;
totalCount += count;
return this;
}
private AvlNode<E> addLeftChild(E e, int count) {
left = new AvlNode<E>(e, count);
successor(pred, left, this);
height = Math.max(2, height);
distinctElements++;
totalCount += count;
return this;
}
AvlNode<E> add(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
/*
* It speeds things up considerably to unconditionally add count to totalCount here,
* but that destroys failure atomicity in the case of count overflow. =(
*/
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return addLeftChild(e, count);
}
int initHeight = initLeft.height;
left = initLeft.add(comparator, e, count, result);
if (result[0] == 0) {
distinctElements++;
}
this.totalCount += count;
return (left.height == initHeight) ? this : rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return addRightChild(e, count);
}
int initHeight = initRight.height;
right = initRight.add(comparator, e, count, result);
if (result[0] == 0) {
distinctElements++;
}
this.totalCount += count;
return (right.height == initHeight) ? this : rebalance();
}
// adding count to me! No rebalance possible.
result[0] = elemCount;
long resultCount = (long) elemCount + count;
checkArgument(resultCount <= Integer.MAX_VALUE);
this.elemCount += count;
this.totalCount += count;
return this;
}
AvlNode<E> remove(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return this;
}
left = initLeft.remove(comparator, e, count, result);
if (result[0] > 0) {
if (count >= result[0]) {
this.distinctElements--;
this.totalCount -= result[0];
} else {
this.totalCount -= count;
}
}
return (result[0] == 0) ? this : rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return this;
}
right = initRight.remove(comparator, e, count, result);
if (result[0] > 0) {
if (count >= result[0]) {
this.distinctElements--;
this.totalCount -= result[0];
} else {
this.totalCount -= count;
}
}
return rebalance();
}
// removing count from me!
result[0] = elemCount;
if (count >= elemCount) {
return deleteMe();
} else {
this.elemCount -= count;
this.totalCount -= count;
return this;
}
}
AvlNode<E> setCount(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return (count > 0) ? addLeftChild(e, count) : this;
}
left = initLeft.setCount(comparator, e, count, result);
if (count == 0 && result[0] != 0) {
this.distinctElements--;
} else if (count > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += count - result[0];
return rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return (count > 0) ? addRightChild(e, count) : this;
}
right = initRight.setCount(comparator, e, count, result);
if (count == 0 && result[0] != 0) {
this.distinctElements--;
} else if (count > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += count - result[0];
return rebalance();
}
// setting my count
result[0] = elemCount;
if (count == 0) {
return deleteMe();
}
this.totalCount += count - elemCount;
this.elemCount = count;
return this;
}
AvlNode<E> setCount(
Comparator<? super E> comparator,
@Nullable E e,
int expectedCount,
int newCount,
int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
if (expectedCount == 0 && newCount > 0) {
return addLeftChild(e, newCount);
}
return this;
}
left = initLeft.setCount(comparator, e, expectedCount, newCount, result);
if (result[0] == expectedCount) {
if (newCount == 0 && result[0] != 0) {
this.distinctElements--;
} else if (newCount > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += newCount - result[0];
}
return rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
if (expectedCount == 0 && newCount > 0) {
return addRightChild(e, newCount);
}
return this;
}
right = initRight.setCount(comparator, e, expectedCount, newCount, result);
if (result[0] == expectedCount) {
if (newCount == 0 && result[0] != 0) {
this.distinctElements--;
} else if (newCount > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += newCount - result[0];
}
return rebalance();
}
// setting my count
result[0] = elemCount;
if (expectedCount == elemCount) {
if (newCount == 0) {
return deleteMe();
}
this.totalCount += newCount - elemCount;
this.elemCount = newCount;
}
return this;
}
private AvlNode<E> deleteMe() {
int oldElemCount = this.elemCount;
this.elemCount = 0;
successor(pred, succ);
if (left == null) {
return right;
} else if (right == null) {
return left;
} else if (left.height >= right.height) {
AvlNode<E> newTop = pred;
// newTop is the maximum node in my left subtree
newTop.left = left.removeMax(newTop);
newTop.right = right;
newTop.distinctElements = distinctElements - 1;
newTop.totalCount = totalCount - oldElemCount;
return newTop.rebalance();
} else {
AvlNode<E> newTop = succ;
newTop.right = right.removeMin(newTop);
newTop.left = left;
newTop.distinctElements = distinctElements - 1;
newTop.totalCount = totalCount - oldElemCount;
return newTop.rebalance();
}
}
// Removes the minimum node from this subtree to be reused elsewhere
private AvlNode<E> removeMin(AvlNode<E> node) {
if (left == null) {
return right;
} else {
left = left.removeMin(node);
distinctElements--;
totalCount -= node.elemCount;
return rebalance();
}
}
// Removes the maximum node from this subtree to be reused elsewhere
private AvlNode<E> removeMax(AvlNode<E> node) {
if (right == null) {
return left;
} else {
right = right.removeMax(node);
distinctElements--;
totalCount -= node.elemCount;
return rebalance();
}
}
private void recomputeMultiset() {
this.distinctElements = 1 + TreeMultiset.distinctElements(left)
+ TreeMultiset.distinctElements(right);
this.totalCount = elemCount + totalCount(left) + totalCount(right);
}
private void recomputeHeight() {
this.height = 1 + Math.max(height(left), height(right));
}
private void recompute() {
recomputeMultiset();
recomputeHeight();
}
private AvlNode<E> rebalance() {
switch (balanceFactor()) {
case -2:
if (right.balanceFactor() > 0) {
right = right.rotateRight();
}
return rotateLeft();
case 2:
if (left.balanceFactor() < 0) {
left = left.rotateLeft();
}
return rotateRight();
default:
recomputeHeight();
return this;
}
}
private int balanceFactor() {
return height(left) - height(right);
}
private AvlNode<E> rotateLeft() {
checkState(right != null);
AvlNode<E> newTop = right;
this.right = newTop.left;
newTop.left = this;
newTop.totalCount = this.totalCount;
newTop.distinctElements = this.distinctElements;
this.recompute();
newTop.recomputeHeight();
return newTop;
}
private AvlNode<E> rotateRight() {
checkState(left != null);
AvlNode<E> newTop = left;
this.left = newTop.right;
newTop.right = this;
newTop.totalCount = this.totalCount;
newTop.distinctElements = this.distinctElements;
this.recompute();
newTop.recomputeHeight();
return newTop;
}
private static long totalCount(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.totalCount;
}
private static int height(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.height;
}
@Nullable private AvlNode<E> ceiling(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this);
} else if (cmp == 0) {
return this;
} else {
return (right == null) ? null : right.ceiling(comparator, e);
}
}
@Nullable private AvlNode<E> floor(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp > 0) {
return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this);
} else if (cmp == 0) {
return this;
} else {
return (left == null) ? null : left.floor(comparator, e);
}
}
@Override
public E getElement() {
return elem;
}
@Override
public int getCount() {
return elemCount;
}
@Override
public String toString() {
return Multisets.immutableEntry(getElement(), getCount()).toString();
}
}
private static <T> void successor(AvlNode<T> a, AvlNode<T> b) {
a.succ = b;
b.pred = a;
}
private static <T> void successor(AvlNode<T> a, AvlNode<T> b, AvlNode<T> c) {
successor(a, b);
successor(b, c);
}
/*
* TODO(jlevy): Decide whether entrySet() should return entries with an equals() method that
* calls the comparator to compare the two keys. If that change is made,
* AbstractMultiset.equals() can simply check whether two multisets have equal entry sets.
*/
}
| 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 java.util.Collections.unmodifiableList;
import java.util.List;
/**
* GWT emulated version of {@link RegularImmutableList}.
*
* @author Hayward Chan
*/
class RegularImmutableList<E> extends ForwardingImmutableList<E> {
private final List<E> delegate;
RegularImmutableList(List<E> delegate) {
// TODO(cpovirk): avoid redundant unmodifiableList wrapping
this.delegate = unmodifiableList(delegate);
}
@Override List<E> delegateList() {
return delegate;
}
}
| 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 = 3;
@VisibleForTesting transient int expectedValuesPerKey;
/**
* Creates a new, empty {@code ArrayListMultimap} with the default initial
* capacities.
*/
public static <K, V> ArrayListMultimap<K, V> create() {
return new ArrayListMultimap<K, V>();
}
/**
* Constructs an empty {@code ArrayListMultimap} with enough capacity to hold
* the specified numbers of keys and values without resizing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> ArrayListMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey);
}
/**
* Constructs an {@code ArrayListMultimap} with the same mappings as the
* specified multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> ArrayListMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new ArrayListMultimap<K, V>(multimap);
}
private ArrayListMultimap() {
super(new HashMap<K, Collection<V>>());
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
}
private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
checkArgument(expectedValuesPerKey >= 0);
this.expectedValuesPerKey = expectedValuesPerKey;
}
private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size(),
(multimap instanceof ArrayListMultimap) ?
((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey :
DEFAULT_VALUES_PER_KEY);
putAll(multimap);
}
/**
* Creates a new, empty {@code ArrayList} to hold the collection of values for
* an arbitrary key.
*/
@Override List<V> createCollection() {
return new ArrayList<V>(expectedValuesPerKey);
}
/**
* Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
*/
public void trimToSize() {
for (Collection<V> collection : backingMap().values()) {
ArrayList<V> arrayList = (ArrayList<V>) collection;
arrayList.trimToSize();
}
}
}
| 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;
/**
* GWT emulation of {@link EmptyImmutableBiMap}.
*
* @author Hayward Chan
*/
@SuppressWarnings("serial")
final class EmptyImmutableBiMap extends ImmutableBiMap<Object, Object> {
static final EmptyImmutableBiMap INSTANCE = new EmptyImmutableBiMap();
private EmptyImmutableBiMap() {
super(Collections.emptyMap());
}
@Override public ImmutableBiMap<Object, Object> inverse() {
return this;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* A sorted set of contiguous values in a given {@link DiscreteDomain}.
*
* <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as
* {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomains.integers()}). Certain
* operations on such a set can be performed efficiently, but others (such as {@link Set#hashCode}
* or {@link Collections#frequency}) can cause major performance problems.
*
* @author Gregory Kick
* @since 10.0
*/
@Beta
@GwtCompatible(emulated = true)
@SuppressWarnings("rawtypes") // allow ungenerified Comparable types
public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
/**
* Returns a {@code ContiguousSet} containing the same values in the given domain
* {@linkplain Range#contains contained} by the range.
*
* @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if
* neither has an upper bound
*
* @since 13.0
*/
public static <C extends Comparable> ContiguousSet<C> create(
Range<C> range, DiscreteDomain<C> domain) {
checkNotNull(range);
checkNotNull(domain);
Range<C> effectiveRange = range;
try {
if (!range.hasLowerBound()) {
effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue()));
}
if (!range.hasUpperBound()) {
effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue()));
}
} catch (NoSuchElementException e) {
throw new IllegalArgumentException(e);
}
// Per class spec, we are allowed to throw CCE if necessary
boolean empty = effectiveRange.isEmpty()
|| Range.compareOrThrow(
range.lowerBound.leastValueAbove(domain),
range.upperBound.greatestValueBelow(domain)) > 0;
return empty
? new EmptyContiguousSet<C>(domain)
: new RegularContiguousSet<C>(effectiveRange, domain);
}
final DiscreteDomain<C> domain;
ContiguousSet(DiscreteDomain<C> domain) {
super(Ordering.natural());
this.domain = domain;
}
@Override public ContiguousSet<C> headSet(C toElement) {
return headSetImpl(checkNotNull(toElement), false);
}
@Override public ContiguousSet<C> subSet(C fromElement, C toElement) {
checkNotNull(fromElement);
checkNotNull(toElement);
checkArgument(comparator().compare(fromElement, toElement) <= 0);
return subSetImpl(fromElement, true, toElement, false);
}
@Override public ContiguousSet<C> tailSet(C fromElement) {
return tailSetImpl(checkNotNull(fromElement), true);
}
/*
* These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
*/
/*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
/*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive,
C toElement, boolean toInclusive);
/*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
/**
* Returns the set of values that are contained in both this set and the other.
*
* <p>This method should always be used instead of
* {@link Sets#intersection} for {@link ContiguousSet} instances.
*/
public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
/**
* Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
* contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}.
*
* @throws NoSuchElementException if this set is empty
*/
public abstract Range<C> range();
/**
* Returns the minimal range with the given boundary types for which all values in this set are
* {@linkplain Range#contains(Comparable) contained} within the range.
*
* <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
* is requested for a domain minimum or maximum. For example, if {@code set} was created from the
* range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
* {@code [1..∞)}.
*
* @throws NoSuchElementException if this set is empty
*/
public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
/** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
@Override public String toString() {
return range().toString();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.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.Map.Entry;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Synchronized collection views. The returned synchronized collection views are
* serializable if the backing collection and the mutex are serializable.
*
* <p>If {@code null} is passed as the {@code mutex} parameter to any of this
* class's top-level methods or inner class constructors, the created object
* uses itself as the synchronization mutex.
*
* <p>This class should be used by other collection classes only.
*
* @author Mike Bostock
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
final class Synchronized {
private Synchronized() {}
static class SynchronizedObject implements Serializable {
final Object delegate;
final Object mutex;
SynchronizedObject(Object delegate, @Nullable Object mutex) {
this.delegate = checkNotNull(delegate);
this.mutex = (mutex == null) ? this : mutex;
}
Object delegate() {
return delegate;
}
// No equals and hashCode; see ForwardingObject for details.
@Override public String toString() {
synchronized (mutex) {
return delegate.toString();
}
}
// Serialization invokes writeObject only when it's private.
// The SynchronizedObject subclasses don't need a writeObject method since
// they don't contain any non-transient member variables, while the
// following writeObject() handles the SynchronizedObject members.
}
private static <E> Collection<E> collection(
Collection<E> collection, @Nullable Object mutex) {
return new SynchronizedCollection<E>(collection, mutex);
}
@VisibleForTesting static class SynchronizedCollection<E>
extends SynchronizedObject implements Collection<E> {
private SynchronizedCollection(
Collection<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked")
@Override Collection<E> delegate() {
return (Collection<E>) super.delegate();
}
@Override
public boolean add(E e) {
synchronized (mutex) {
return delegate().add(e);
}
}
@Override
public boolean addAll(Collection<? extends E> c) {
synchronized (mutex) {
return delegate().addAll(c);
}
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public boolean contains(Object o) {
synchronized (mutex) {
return delegate().contains(o);
}
}
@Override
public boolean containsAll(Collection<?> c) {
synchronized (mutex) {
return delegate().containsAll(c);
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public Iterator<E> iterator() {
return delegate().iterator(); // manually synchronized
}
@Override
public boolean remove(Object o) {
synchronized (mutex) {
return delegate().remove(o);
}
}
@Override
public boolean removeAll(Collection<?> c) {
synchronized (mutex) {
return delegate().removeAll(c);
}
}
@Override
public boolean retainAll(Collection<?> c) {
synchronized (mutex) {
return delegate().retainAll(c);
}
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public Object[] toArray() {
synchronized (mutex) {
return delegate().toArray();
}
}
@Override
public <T> T[] toArray(T[] a) {
synchronized (mutex) {
return delegate().toArray(a);
}
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) {
return new SynchronizedSet<E>(set, mutex);
}
static class SynchronizedSet<E>
extends SynchronizedCollection<E> implements Set<E> {
SynchronizedSet(Set<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Set<E> delegate() {
return (Set<E>) super.delegate();
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
private static <E> SortedSet<E> sortedSet(
SortedSet<E> set, @Nullable Object mutex) {
return new SynchronizedSortedSet<E>(set, mutex);
}
static class SynchronizedSortedSet<E> extends SynchronizedSet<E>
implements SortedSet<E> {
SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedSet<E> delegate() {
return (SortedSet<E>) super.delegate();
}
@Override
public Comparator<? super E> comparator() {
synchronized (mutex) {
return delegate().comparator();
}
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
synchronized (mutex) {
return sortedSet(delegate().subSet(fromElement, toElement), mutex);
}
}
@Override
public SortedSet<E> headSet(E toElement) {
synchronized (mutex) {
return sortedSet(delegate().headSet(toElement), mutex);
}
}
@Override
public SortedSet<E> tailSet(E fromElement) {
synchronized (mutex) {
return sortedSet(delegate().tailSet(fromElement), mutex);
}
}
@Override
public E first() {
synchronized (mutex) {
return delegate().first();
}
}
@Override
public E last() {
synchronized (mutex) {
return delegate().last();
}
}
private static final long serialVersionUID = 0;
}
private static <E> List<E> list(List<E> list, @Nullable Object mutex) {
return (list instanceof RandomAccess)
? new SynchronizedRandomAccessList<E>(list, mutex)
: new SynchronizedList<E>(list, mutex);
}
private static class SynchronizedList<E> extends SynchronizedCollection<E>
implements List<E> {
SynchronizedList(List<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override List<E> delegate() {
return (List<E>) super.delegate();
}
@Override
public void add(int index, E element) {
synchronized (mutex) {
delegate().add(index, element);
}
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
synchronized (mutex) {
return delegate().addAll(index, c);
}
}
@Override
public E get(int index) {
synchronized (mutex) {
return delegate().get(index);
}
}
@Override
public int indexOf(Object o) {
synchronized (mutex) {
return delegate().indexOf(o);
}
}
@Override
public int lastIndexOf(Object o) {
synchronized (mutex) {
return delegate().lastIndexOf(o);
}
}
@Override
public ListIterator<E> listIterator() {
return delegate().listIterator(); // manually synchronized
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate().listIterator(index); // manually synchronized
}
@Override
public E remove(int index) {
synchronized (mutex) {
return delegate().remove(index);
}
}
@Override
public E set(int index, E element) {
synchronized (mutex) {
return delegate().set(index, element);
}
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) {
return list(delegate().subList(fromIndex, toIndex), mutex);
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedRandomAccessList<E>
extends SynchronizedList<E> implements RandomAccess {
SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) {
super(list, mutex);
}
private static final long serialVersionUID = 0;
}
static <E> Multiset<E> multiset(
Multiset<E> multiset, @Nullable Object mutex) {
if (multiset instanceof SynchronizedMultiset ||
multiset instanceof ImmutableMultiset) {
return multiset;
}
return new SynchronizedMultiset<E>(multiset, mutex);
}
private static class SynchronizedMultiset<E> extends SynchronizedCollection<E>
implements Multiset<E> {
transient Set<E> elementSet;
transient Set<Entry<E>> entrySet;
SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Multiset<E> delegate() {
return (Multiset<E>) super.delegate();
}
@Override
public int count(Object o) {
synchronized (mutex) {
return delegate().count(o);
}
}
@Override
public int add(E e, int n) {
synchronized (mutex) {
return delegate().add(e, n);
}
}
@Override
public int remove(Object o, int n) {
synchronized (mutex) {
return delegate().remove(o, n);
}
}
@Override
public int setCount(E element, int count) {
synchronized (mutex) {
return delegate().setCount(element, count);
}
}
@Override
public boolean setCount(E element, int oldCount, int newCount) {
synchronized (mutex) {
return delegate().setCount(element, oldCount, newCount);
}
}
@Override
public Set<E> elementSet() {
synchronized (mutex) {
if (elementSet == null) {
elementSet = typePreservingSet(delegate().elementSet(), mutex);
}
return elementSet;
}
}
@Override
public Set<Entry<E>> entrySet() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = typePreservingSet(delegate().entrySet(), mutex);
}
return entrySet;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> Multimap<K, V> multimap(
Multimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedMultimap ||
multimap instanceof ImmutableMultimap) {
return multimap;
}
return new SynchronizedMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedMultimap<K, V> extends SynchronizedObject
implements Multimap<K, V> {
transient Set<K> keySet;
transient Collection<V> valuesCollection;
transient Collection<Map.Entry<K, V>> entries;
transient Map<K, Collection<V>> asMap;
transient Multiset<K> keys;
@SuppressWarnings("unchecked")
@Override Multimap<K, V> delegate() {
return (Multimap<K, V>) super.delegate();
}
SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public boolean containsKey(Object key) {
synchronized (mutex) {
return delegate().containsKey(key);
}
}
@Override
public boolean containsValue(Object value) {
synchronized (mutex) {
return delegate().containsValue(value);
}
}
@Override
public boolean containsEntry(Object key, Object value) {
synchronized (mutex) {
return delegate().containsEntry(key, value);
}
}
@Override
public Collection<V> get(K key) {
synchronized (mutex) {
return typePreservingCollection(delegate().get(key), mutex);
}
}
@Override
public boolean put(K key, V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().putAll(key, values);
}
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
synchronized (mutex) {
return delegate().putAll(multimap);
}
}
@Override
public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override
public boolean remove(Object key, Object value) {
synchronized (mutex) {
return delegate().remove(key, value);
}
}
@Override
public Collection<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public Set<K> keySet() {
synchronized (mutex) {
if (keySet == null) {
keySet = typePreservingSet(delegate().keySet(), mutex);
}
return keySet;
}
}
@Override
public Collection<V> values() {
synchronized (mutex) {
if (valuesCollection == null) {
valuesCollection = collection(delegate().values(), mutex);
}
return valuesCollection;
}
}
@Override
public Collection<Map.Entry<K, V>> entries() {
synchronized (mutex) {
if (entries == null) {
entries = typePreservingCollection(delegate().entries(), mutex);
}
return entries;
}
}
@Override
public Map<K, Collection<V>> asMap() {
synchronized (mutex) {
if (asMap == null) {
asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex);
}
return asMap;
}
}
@Override
public Multiset<K> keys() {
synchronized (mutex) {
if (keys == null) {
keys = multiset(delegate().keys(), mutex);
}
return keys;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> ListMultimap<K, V> listMultimap(
ListMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedListMultimap ||
multimap instanceof ImmutableListMultimap) {
return multimap;
}
return new SynchronizedListMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedListMultimap<K, V>
extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> {
SynchronizedListMultimap(
ListMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
synchronized (mutex) {
return list(delegate().get(key), mutex);
}
}
@Override public List<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SetMultimap<K, V> setMultimap(
SetMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedSetMultimap ||
multimap instanceof ImmutableSetMultimap) {
return multimap;
}
return new SynchronizedSetMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedSetMultimap<K, V>
extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> {
transient Set<Map.Entry<K, V>> entrySet;
SynchronizedSetMultimap(
SetMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
synchronized (mutex) {
return set(delegate().get(key), mutex);
}
}
@Override public Set<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override public Set<Map.Entry<K, V>> entries() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = set(delegate().entries(), mutex);
}
return entrySet;
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SortedSetMultimap<K, V> sortedSetMultimap(
SortedSetMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedSortedSetMultimap) {
return multimap;
}
return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedSortedSetMultimap<K, V>
extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> {
SynchronizedSortedSetMultimap(
SortedSetMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
synchronized (mutex) {
return sortedSet(delegate().get(key), mutex);
}
}
@Override public SortedSet<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override
public Comparator<? super V> valueComparator() {
synchronized (mutex) {
return delegate().valueComparator();
}
}
private static final long serialVersionUID = 0;
}
private static <E> Collection<E> typePreservingCollection(
Collection<E> collection, @Nullable Object mutex) {
if (collection instanceof SortedSet) {
return sortedSet((SortedSet<E>) collection, mutex);
}
if (collection instanceof Set) {
return set((Set<E>) collection, mutex);
}
if (collection instanceof List) {
return list((List<E>) collection, mutex);
}
return collection(collection, mutex);
}
private static <E> Set<E> typePreservingSet(
Set<E> set, @Nullable Object mutex) {
if (set instanceof SortedSet) {
return sortedSet((SortedSet<E>) set, mutex);
} else {
return set(set, mutex);
}
}
private static class SynchronizedAsMapEntries<K, V>
extends SynchronizedSet<Map.Entry<K, Collection<V>>> {
SynchronizedAsMapEntries(
Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
// Must be manually synchronized.
final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator();
return new ForwardingIterator<Map.Entry<K, Collection<V>>>() {
@Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() {
return iterator;
}
@Override public Map.Entry<K, Collection<V>> next() {
final Map.Entry<K, Collection<V>> entry = super.next();
return new ForwardingMapEntry<K, Collection<V>>() {
@Override protected Map.Entry<K, Collection<V>> delegate() {
return entry;
}
@Override public Collection<V> getValue() {
return typePreservingCollection(entry.getValue(), mutex);
}
};
}
};
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
synchronized (mutex) {
return ObjectArrays.toArrayImpl(delegate());
}
}
@Override public <T> T[] toArray(T[] array) {
synchronized (mutex) {
return ObjectArrays.toArrayImpl(delegate(), array);
}
}
@Override public boolean contains(Object o) {
synchronized (mutex) {
return Maps.containsEntryImpl(delegate(), o);
}
}
@Override public boolean containsAll(Collection<?> c) {
synchronized (mutex) {
return Collections2.containsAllImpl(delegate(), c);
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return Sets.equalsImpl(delegate(), o);
}
}
@Override public boolean remove(Object o) {
synchronized (mutex) {
return Maps.removeEntryImpl(delegate(), o);
}
}
@Override public boolean removeAll(Collection<?> c) {
synchronized (mutex) {
return Iterators.removeAll(delegate().iterator(), c);
}
}
@Override public boolean retainAll(Collection<?> c) {
synchronized (mutex) {
return Iterators.retainAll(delegate().iterator(), c);
}
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting
static <K, V> Map<K, V> map(Map<K, V> map, @Nullable Object mutex) {
return new SynchronizedMap<K, V>(map, mutex);
}
private static class SynchronizedMap<K, V> extends SynchronizedObject
implements Map<K, V> {
transient Set<K> keySet;
transient Collection<V> values;
transient Set<Map.Entry<K, V>> entrySet;
SynchronizedMap(Map<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked")
@Override Map<K, V> delegate() {
return (Map<K, V>) super.delegate();
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public boolean containsKey(Object key) {
synchronized (mutex) {
return delegate().containsKey(key);
}
}
@Override
public boolean containsValue(Object value) {
synchronized (mutex) {
return delegate().containsValue(value);
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = set(delegate().entrySet(), mutex);
}
return entrySet;
}
}
@Override
public V get(Object key) {
synchronized (mutex) {
return delegate().get(key);
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public Set<K> keySet() {
synchronized (mutex) {
if (keySet == null) {
keySet = set(delegate().keySet(), mutex);
}
return keySet;
}
}
@Override
public V put(K key, V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
synchronized (mutex) {
delegate().putAll(map);
}
}
@Override
public V remove(Object key) {
synchronized (mutex) {
return delegate().remove(key);
}
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public Collection<V> values() {
synchronized (mutex) {
if (values == null) {
values = collection(delegate().values(), mutex);
}
return values;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SortedMap<K, V> sortedMap(
SortedMap<K, V> sortedMap, @Nullable Object mutex) {
return new SynchronizedSortedMap<K, V>(sortedMap, mutex);
}
static class SynchronizedSortedMap<K, V> extends SynchronizedMap<K, V>
implements SortedMap<K, V> {
SynchronizedSortedMap(SortedMap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedMap<K, V> delegate() {
return (SortedMap<K, V>) super.delegate();
}
@Override public Comparator<? super K> comparator() {
synchronized (mutex) {
return delegate().comparator();
}
}
@Override public K firstKey() {
synchronized (mutex) {
return delegate().firstKey();
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
synchronized (mutex) {
return sortedMap(delegate().headMap(toKey), mutex);
}
}
@Override public K lastKey() {
synchronized (mutex) {
return delegate().lastKey();
}
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
synchronized (mutex) {
return sortedMap(delegate().subMap(fromKey, toKey), mutex);
}
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
synchronized (mutex) {
return sortedMap(delegate().tailMap(fromKey), mutex);
}
}
private static final long serialVersionUID = 0;
}
static <K, V> BiMap<K, V> biMap(BiMap<K, V> bimap, @Nullable Object mutex) {
if (bimap instanceof SynchronizedBiMap ||
bimap instanceof ImmutableBiMap) {
return bimap;
}
return new SynchronizedBiMap<K, V>(bimap, mutex, null);
}
@VisibleForTesting static class SynchronizedBiMap<K, V>
extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable {
private transient Set<V> valueSet;
private transient BiMap<V, K> inverse;
private SynchronizedBiMap(BiMap<K, V> delegate, @Nullable Object mutex,
@Nullable BiMap<V, K> inverse) {
super(delegate, mutex);
this.inverse = inverse;
}
@Override BiMap<K, V> delegate() {
return (BiMap<K, V>) super.delegate();
}
@Override public Set<V> values() {
synchronized (mutex) {
if (valueSet == null) {
valueSet = set(delegate().values(), mutex);
}
return valueSet;
}
}
@Override
public V forcePut(K key, V value) {
synchronized (mutex) {
return delegate().forcePut(key, value);
}
}
@Override
public BiMap<V, K> inverse() {
synchronized (mutex) {
if (inverse == null) {
inverse
= new SynchronizedBiMap<V, K>(delegate().inverse(), mutex, this);
}
return inverse;
}
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedAsMap<K, V>
extends SynchronizedMap<K, Collection<V>> {
transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet;
transient Collection<Collection<V>> asMapValues;
SynchronizedAsMap(Map<K, Collection<V>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Collection<V> get(Object key) {
synchronized (mutex) {
Collection<V> collection = super.get(key);
return (collection == null) ? null
: typePreservingCollection(collection, mutex);
}
}
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
synchronized (mutex) {
if (asMapEntrySet == null) {
asMapEntrySet = new SynchronizedAsMapEntries<K, V>(
delegate().entrySet(), mutex);
}
return asMapEntrySet;
}
}
@Override public Collection<Collection<V>> values() {
synchronized (mutex) {
if (asMapValues == null) {
asMapValues
= new SynchronizedAsMapValues<V>(delegate().values(), mutex);
}
return asMapValues;
}
}
@Override public boolean containsValue(Object o) {
// values() and its contains() method are both synchronized.
return values().contains(o);
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedAsMapValues<V>
extends SynchronizedCollection<Collection<V>> {
SynchronizedAsMapValues(
Collection<Collection<V>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Iterator<Collection<V>> iterator() {
// Must be manually synchronized.
final Iterator<Collection<V>> iterator = super.iterator();
return new ForwardingIterator<Collection<V>>() {
@Override protected Iterator<Collection<V>> delegate() {
return iterator;
}
@Override public Collection<V> next() {
return typePreservingCollection(super.next(), mutex);
}
};
}
private static final long serialVersionUID = 0;
}
static <E> Queue<E> queue(Queue<E> queue, @Nullable Object mutex) {
return (queue instanceof SynchronizedQueue)
? queue
: new SynchronizedQueue<E>(queue, mutex);
}
private static class SynchronizedQueue<E> extends SynchronizedCollection<E>
implements Queue<E> {
SynchronizedQueue(Queue<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Queue<E> delegate() {
return (Queue<E>) super.delegate();
}
@Override
public E element() {
synchronized (mutex) {
return delegate().element();
}
}
@Override
public boolean offer(E e) {
synchronized (mutex) {
return delegate().offer(e);
}
}
@Override
public E peek() {
synchronized (mutex) {
return delegate().peek();
}
}
@Override
public E poll() {
synchronized (mutex) {
return delegate().poll();
}
}
@Override
public E remove() {
synchronized (mutex) {
return delegate().remove();
}
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.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) 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 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 {
ImmutableMap() {}
// 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);
}
}
abstract boolean isPartialView();
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();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(@Nullable Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(@Nullable Object value) {
return value != null && Maps.containsValueImpl(this, value);
}
private transient ImmutableSet<Entry<K, V>> cachedEntrySet = null;
public final ImmutableSet<Entry<K, V>> entrySet() {
if (cachedEntrySet != null) {
return cachedEntrySet;
}
return cachedEntrySet = createEntrySet();
}
abstract ImmutableSet<Entry<K, V>> createEntrySet();
private transient ImmutableSet<K> cachedKeySet = null;
public ImmutableSet<K> keySet() {
if (cachedKeySet != null) {
return cachedKeySet;
}
return cachedKeySet = createKeySet();
}
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<K, V>(entrySet()) {
@Override ImmutableMap<K, V> map() {
return ImmutableMap.this;
}
};
}
private transient ImmutableCollection<V> cachedValues = null;
public ImmutableCollection<V> values() {
if (cachedValues != null) {
return cachedValues;
}
return cachedValues = createValues();
}
ImmutableCollection<V> createValues() {
return new ImmutableMapValues<K, V>() {
@Override ImmutableMap<K, V> map() {
return ImmutableMap.this;
}
};
}
@Override public boolean equals(@Nullable Object object) {
return Maps.equalsImpl(this, object);
}
@Override public int hashCode() {
// not caching hash code since it could change if map values are mutable
// in a way that modifies their hash codes
return entrySet().hashCode();
}
@Override public String toString() {
return Maps.toStringImpl(this);
}
}
| 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(Sets.newTreeSet(comparator));
}
}
| 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;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* GWT implementation of {@link ImmutableMap} that forwards to another map.
*
* @author Hayward Chan
*/
public abstract class ForwardingImmutableMap<K, V> extends ImmutableMap<K, V> {
private final transient Map<K, V> delegate;
ForwardingImmutableMap(Map<? extends K, ? extends V> delegate) {
this.delegate = Collections.unmodifiableMap(delegate);
}
@SuppressWarnings("unchecked")
ForwardingImmutableMap(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);
}
boolean isPartialView() {
return false;
}
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 V get(@Nullable Object key) {
return (key == null) ? null : Maps.safeGet(delegate, key);
}
@Override ImmutableSet<Entry<K, V>> createEntrySet() {
return 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;
}
});
}
@Override ImmutableSet<K> createKeySet() {
return ImmutableSet.unsafeDelegate(delegate.keySet());
}
@Override ImmutableCollection<V> createValues() {
return ImmutableCollection.unsafeDelegate(delegate.values());
}
@Override 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.