code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.collect.MapMaker.RemovalCause; import com.google.common.collect.MapMaker.RemovalListener; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ref.ReferenceQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReferenceArray; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** * Adds computing functionality to {@link MapMakerInternalMap}. * * @author Bob Lee * @author Charles Fry */ class ComputingConcurrentHashMap<K, V> extends MapMakerInternalMap<K, V> { final Function<? super K, ? extends V> computingFunction; /** * Creates a new, empty map with the specified strategy, initial capacity, load factor and * concurrency level. */ ComputingConcurrentHashMap(MapMaker builder, Function<? super K, ? extends V> computingFunction) { super(builder); this.computingFunction = checkNotNull(computingFunction); } @Override Segment<K, V> createSegment(int initialCapacity, int maxSegmentSize) { return new ComputingSegment<K, V>(this, initialCapacity, maxSegmentSize); } @Override ComputingSegment<K, V> segmentFor(int hash) { return (ComputingSegment<K, V>) super.segmentFor(hash); } V getOrCompute(K key) throws ExecutionException { int hash = hash(checkNotNull(key)); return segmentFor(hash).getOrCompute(key, hash, computingFunction); } @SuppressWarnings("serial") // This class is never serialized. static final class ComputingSegment<K, V> extends Segment<K, V> { ComputingSegment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) { super(map, initialCapacity, maxSegmentSize); } V getOrCompute(K key, int hash, Function<? super K, ? extends V> computingFunction) throws ExecutionException { try { outer: while (true) { // don't call getLiveEntry, which would ignore computing values ReferenceEntry<K, V> e = getEntry(key, hash); if (e != null) { V value = getLiveValue(e); if (value != null) { recordRead(e); return value; } } // at this point e is either null, computing, or expired; // avoid locking if it's already computing if (e == null || !e.getValueReference().isComputingReference()) { boolean createNewEntry = true; ComputingValueReference<K, V> computingValueReference = null; lock(); try { preWriteCleanup(); int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); if (valueReference.isComputingReference()) { createNewEntry = false; } else { V value = e.getValueReference().get(); if (value == null) { enqueueNotification(entryKey, hash, value, RemovalCause.COLLECTED); } else if (map.expires() && map.isExpired(e)) { // This is a duplicate check, as preWriteCleanup already purged expired // entries, but let's accomodate an incorrect expiration queue. enqueueNotification(entryKey, hash, value, RemovalCause.EXPIRED); } else { recordLockedRead(e); return value; } // immediately reuse invalid entries evictionQueue.remove(e); expirationQueue.remove(e); this.count = newCount; // write-volatile } break; } } if (createNewEntry) { computingValueReference = new ComputingValueReference<K, V>(computingFunction); if (e == null) { e = newEntry(key, hash, first); e.setValueReference(computingValueReference); table.set(index, e); } else { e.setValueReference(computingValueReference); } } } finally { unlock(); postWriteCleanup(); } if (createNewEntry) { // This thread solely created the entry. return compute(key, hash, e, computingValueReference); } } // The entry already exists. Wait for the computation. checkState(!Thread.holdsLock(e), "Recursive computation"); // don't consider expiration as we're concurrent with computation V value = e.getValueReference().waitForValue(); if (value != null) { recordRead(e); return value; } // else computing thread will clearValue continue outer; } } finally { postReadCleanup(); } } V compute(K key, int hash, ReferenceEntry<K, V> e, ComputingValueReference<K, V> computingValueReference) throws ExecutionException { V value = null; long start = System.nanoTime(); long end = 0; try { // Synchronizes on the entry to allow failing fast when a recursive computation is // detected. This is not fool-proof since the entry may be copied when the segment // is written to. synchronized (e) { value = computingValueReference.compute(key, hash); end = System.nanoTime(); } if (value != null) { // putIfAbsent V oldValue = put(key, hash, value, true); if (oldValue != null) { // the computed value was already clobbered enqueueNotification(key, hash, value, RemovalCause.REPLACED); } } return value; } finally { if (end == 0) { end = System.nanoTime(); } if (value == null) { clearValue(key, hash, computingValueReference); } } } } /** * Used to provide computation exceptions to other threads. */ private static final class ComputationExceptionReference<K, V> implements ValueReference<K, V> { final Throwable t; ComputationExceptionReference(Throwable t) { this.t = t; } @Override public V get() { return null; } @Override public ReferenceEntry<K, V> getEntry() { return null; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return this; } @Override public boolean isComputingReference() { return false; } @Override public V waitForValue() throws ExecutionException { throw new ExecutionException(t); } @Override public void clear(ValueReference<K, V> newValue) {} } /** * Used to provide computation result to other threads. */ private static final class ComputedReference<K, V> implements ValueReference<K, V> { final V value; ComputedReference(@Nullable V value) { this.value = value; } @Override public V get() { return value; } @Override public ReferenceEntry<K, V> getEntry() { return null; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return this; } @Override public boolean isComputingReference() { return false; } @Override public V waitForValue() { return get(); } @Override public void clear(ValueReference<K, V> newValue) {} } private static final class ComputingValueReference<K, V> implements ValueReference<K, V> { final Function<? super K, ? extends V> computingFunction; @GuardedBy("ComputingValueReference.this") // writes volatile ValueReference<K, V> computedReference = unset(); public ComputingValueReference(Function<? super K, ? extends V> computingFunction) { this.computingFunction = computingFunction; } @Override public V get() { // All computation lookups go through waitForValue. This method thus is // only used by put, to whom we always want to appear absent. return null; } @Override public ReferenceEntry<K, V> getEntry() { return null; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry) { return this; } @Override public boolean isComputingReference() { return true; } /** * Waits for a computation to complete. Returns the result of the computation. */ @Override public V waitForValue() throws ExecutionException { if (computedReference == UNSET) { boolean interrupted = false; try { synchronized (this) { while (computedReference == UNSET) { try { wait(); } catch (InterruptedException ie) { interrupted = true; } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } return computedReference.waitForValue(); } @Override public void clear(ValueReference<K, V> newValue) { // The pending computation was clobbered by a manual write. Unblock all // pending gets, and have them return the new value. setValueReference(newValue); // TODO(fry): could also cancel computation if we had a thread handle } V compute(K key, int hash) throws ExecutionException { V value; try { value = computingFunction.apply(key); } catch (Throwable t) { setValueReference(new ComputationExceptionReference<K, V>(t)); throw new ExecutionException(t); } setValueReference(new ComputedReference<K, V>(value)); return value; } void setValueReference(ValueReference<K, V> valueReference) { synchronized (this) { if (computedReference == UNSET) { computedReference = valueReference; notifyAll(); } } } } // Serialization Support private static final long serialVersionUID = 4; @Override Object writeReplace() { return new ComputingSerializationProxy<K, V>(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, this, computingFunction); } static final class ComputingSerializationProxy<K, V> extends AbstractSerializationProxy<K, V> { final Function<? super K, ? extends V> computingFunction; ComputingSerializationProxy(Strength keyStrength, Strength valueStrength, Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence, long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize, int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener, ConcurrentMap<K, V> delegate, Function<? super K, ? extends V> computingFunction) { super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate); this.computingFunction = computingFunction; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); writeMapTo(out); } @SuppressWarnings("deprecation") // self-use private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); MapMaker mapMaker = readMapMaker(in); delegate = mapMaker.makeComputingMap(computingFunction); readEntries(in); } Object readResolve() { return delegate; } private static final long serialVersionUID = 4; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ComputingConcurrentHashMap.java
Java
asf20
13,460
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Basic implementation of the {@link SetMultimap} interface. It's a wrapper * around {@link AbstractMapBasedMultimap} that converts the returned collections into * {@code Sets}. The {@link #createCollection} method must return a {@code Set}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractSetMultimap<K, V> extends AbstractMapBasedMultimap<K, V> implements SetMultimap<K, V> { /** * Creates a new multimap that uses the provided map. * * @param map place to store the mapping from each key to its corresponding * values */ protected AbstractSetMultimap(Map<K, Collection<V>> map) { super(map); } @Override abstract Set<V> createCollection(); @Override Set<V> createUnmodifiableEmptyCollection() { return ImmutableSet.of(); } // Following Javadoc copied from SetMultimap. /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link Collection} specified * in the {@link Multimap} interface. */ @Override public Set<V> get(@Nullable K key) { return (Set<V>) super.get(key); } /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link Collection} specified * in the {@link Multimap} interface. */ @Override public Set<Map.Entry<K, V>> entries() { return (Set<Map.Entry<K, V>>) super.entries(); } /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link Collection} specified * in the {@link Multimap} interface. */ @Override public Set<V> removeAll(@Nullable Object key) { return (Set<V>) super.removeAll(key); } /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link Collection} specified * in the {@link Multimap} interface. * * <p>Any duplicates in {@code values} will be stored in the multimap once. */ @Override public Set<V> replaceValues( @Nullable K key, Iterable<? extends V> values) { return (Set<V>) super.replaceValues(key, values); } /** * {@inheritDoc} * * <p>Though the method signature doesn't say so explicitly, the returned map * has {@link Set} values. */ @Override public Map<K, Collection<V>> asMap() { return super.asMap(); } /** * Stores a key-value pair in the multimap. * * @param key key to store in the multimap * @param value value to store in the multimap * @return {@code true} if the method increased the size of the multimap, or * {@code false} if the multimap already contained the key-value pair */ @Override public boolean put(@Nullable K key, @Nullable V value) { return super.put(key, value); } /** * Compares the specified object to this multimap for equality. * * <p>Two {@code SetMultimap} instances are equal if, for each key, they * contain the same values. Equality does not depend on the ordering of keys * or values. */ @Override public boolean equals(@Nullable Object object) { return super.equals(object); } private static final long serialVersionUID = 7431625294878419160L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractSetMultimap.java
Java
asf20
4,192
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.SortedSet; import javax.annotation.Nullable; /** * A sorted set multimap which forwards all its method calls to another sorted * set multimap. Subclasses should override one or more methods to modify the * behavior of the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 3.0 */ @GwtCompatible public abstract class ForwardingSortedSetMultimap<K, V> extends ForwardingSetMultimap<K, V> implements SortedSetMultimap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingSortedSetMultimap() {} @Override protected abstract SortedSetMultimap<K, V> delegate(); @Override public SortedSet<V> get(@Nullable K key) { return delegate().get(key); } @Override public SortedSet<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } @Override public Comparator<? super V> valueComparator() { return delegate().valueComparator(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingSortedSetMultimap.java
Java
asf20
1,898
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.Deque; import java.util.Iterator; /** * A deque which forwards all its method calls to another deque. Subclasses * should override one or more methods to modify the behavior of the backing * deque as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingDeque} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #offer} which can lead to unexpected behavior. In this case, you should * override {@code offer} as well. * * @author Kurt Alfred Kluever * @since 12.0 */ public abstract class ForwardingDeque<E> extends ForwardingQueue<E> implements Deque<E> { /** Constructor for use by subclasses. */ protected ForwardingDeque() {} @Override protected abstract Deque<E> delegate(); @Override public void addFirst(E e) { delegate().addFirst(e); } @Override public void addLast(E e) { delegate().addLast(e); } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); } @Override public E getFirst() { return delegate().getFirst(); } @Override public E getLast() { return delegate().getLast(); } @Override public boolean offerFirst(E e) { return delegate().offerFirst(e); } @Override public boolean offerLast(E e) { return delegate().offerLast(e); } @Override public E peekFirst() { return delegate().peekFirst(); } @Override public E peekLast() { return delegate().peekLast(); } @Override public E pollFirst() { return delegate().pollFirst(); } @Override public E pollLast() { return delegate().pollLast(); } @Override public E pop() { return delegate().pop(); } @Override public void push(E e) { delegate().push(e); } @Override public E removeFirst() { return delegate().removeFirst(); } @Override public E removeLast() { return delegate().removeLast(); } @Override public boolean removeFirstOccurrence(Object o) { return delegate().removeFirstOccurrence(o); } @Override public boolean removeLastOccurrence(Object o) { return delegate().removeLastOccurrence(o); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingDeque.java
Java
asf20
2,974
/* * 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.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractMap; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * A {@link BiMap} backed by two hash tables. 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 Louis Wasserman * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class HashBiMap<K, V> extends AbstractMap<K, V> implements BiMap<K, V>, Serializable { /** * Returns a new, empty {@code HashBiMap} with the default initial capacity (16). */ public static <K, V> HashBiMap<K, V> create() { return create(16); } /** * 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 static final class BiEntry<K, V> extends ImmutableEntry<K, V> { final int keyHash; final int valueHash; @Nullable BiEntry<K, V> nextInKToVBucket; @Nullable BiEntry<K, V> nextInVToKBucket; BiEntry(K key, int keyHash, V value, int valueHash) { super(key, value); this.keyHash = keyHash; this.valueHash = valueHash; } } private static final double LOAD_FACTOR = 1.0; private transient BiEntry<K, V>[] hashTableKToV; private transient BiEntry<K, V>[] hashTableVToK; private transient int size; private transient int mask; private transient int modCount; private HashBiMap(int expectedSize) { init(expectedSize); } private void init(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); this.hashTableKToV = createTable(tableSize); this.hashTableVToK = createTable(tableSize); this.mask = tableSize - 1; this.modCount = 0; this.size = 0; } /** * Finds and removes {@code entry} from the bucket linked lists in both the * key-to-value direction and the value-to-key direction. */ private void delete(BiEntry<K, V> entry) { int keyBucket = entry.keyHash & mask; BiEntry<K, V> prevBucketEntry = null; for (BiEntry<K, V> bucketEntry = hashTableKToV[keyBucket]; true; bucketEntry = bucketEntry.nextInKToVBucket) { if (bucketEntry == entry) { if (prevBucketEntry == null) { hashTableKToV[keyBucket] = entry.nextInKToVBucket; } else { prevBucketEntry.nextInKToVBucket = entry.nextInKToVBucket; } break; } prevBucketEntry = bucketEntry; } int valueBucket = entry.valueHash & mask; prevBucketEntry = null; for (BiEntry<K, V> bucketEntry = hashTableVToK[valueBucket];; bucketEntry = bucketEntry.nextInVToKBucket) { if (bucketEntry == entry) { if (prevBucketEntry == null) { hashTableVToK[valueBucket] = entry.nextInVToKBucket; } else { prevBucketEntry.nextInVToKBucket = entry.nextInVToKBucket; } break; } prevBucketEntry = bucketEntry; } size--; modCount++; } private void insert(BiEntry<K, V> entry) { int keyBucket = entry.keyHash & mask; entry.nextInKToVBucket = hashTableKToV[keyBucket]; hashTableKToV[keyBucket] = entry; int valueBucket = entry.valueHash & mask; entry.nextInVToKBucket = hashTableVToK[valueBucket]; hashTableVToK[valueBucket] = entry; size++; modCount++; } private static int hash(@Nullable Object o) { return Hashing.smear((o == null) ? 0 : o.hashCode()); } private BiEntry<K, V> seekByKey(@Nullable Object key, int keyHash) { for (BiEntry<K, V> entry = hashTableKToV[keyHash & mask]; entry != null; entry = entry.nextInKToVBucket) { if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) { return entry; } } return null; } private BiEntry<K, V> seekByValue(@Nullable Object value, int valueHash) { for (BiEntry<K, V> entry = hashTableVToK[valueHash & mask]; entry != null; entry = entry.nextInVToKBucket) { if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) { return entry; } } return null; } @Override public boolean containsKey(@Nullable Object key) { return seekByKey(key, hash(key)) != null; } @Override public boolean containsValue(@Nullable Object value) { return seekByValue(value, hash(value)) != null; } @Nullable @Override public V get(@Nullable Object key) { BiEntry<K, V> entry = seekByKey(key, hash(key)); return (entry == null) ? null : entry.value; } @Override public V put(@Nullable K key, @Nullable V value) { return put(key, value, false); } @Override public V forcePut(@Nullable K key, @Nullable V value) { return put(key, value, true); } private V put(@Nullable K key, @Nullable V value, boolean force) { int keyHash = hash(key); int valueHash = hash(value); BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash); if (oldEntryForKey != null && valueHash == oldEntryForKey.valueHash && Objects.equal(value, oldEntryForKey.value)) { return value; } BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash); if (oldEntryForValue != null) { if (force) { delete(oldEntryForValue); } else { throw new IllegalArgumentException("value already present: " + value); } } if (oldEntryForKey != null) { delete(oldEntryForKey); } BiEntry<K, V> newEntry = new BiEntry<K, V>(key, keyHash, value, valueHash); insert(newEntry); rehashIfNecessary(); return (oldEntryForKey == null) ? null : oldEntryForKey.value; } @Nullable private K putInverse(@Nullable V value, @Nullable K key, boolean force) { int valueHash = hash(value); int keyHash = hash(key); BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash); if (oldEntryForValue != null && keyHash == oldEntryForValue.keyHash && Objects.equal(key, oldEntryForValue.key)) { return key; } BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash); if (oldEntryForKey != null) { if (force) { delete(oldEntryForKey); } else { throw new IllegalArgumentException("value already present: " + key); } } if (oldEntryForValue != null) { delete(oldEntryForValue); } BiEntry<K, V> newEntry = new BiEntry<K, V>(key, keyHash, value, valueHash); insert(newEntry); rehashIfNecessary(); return (oldEntryForValue == null) ? null : oldEntryForValue.key; } private void rehashIfNecessary() { BiEntry<K, V>[] oldKToV = hashTableKToV; if (Hashing.needsResizing(size, oldKToV.length, LOAD_FACTOR)) { int newTableSize = oldKToV.length * 2; this.hashTableKToV = createTable(newTableSize); this.hashTableVToK = createTable(newTableSize); this.mask = newTableSize - 1; this.size = 0; for (int bucket = 0; bucket < oldKToV.length; bucket++) { BiEntry<K, V> entry = oldKToV[bucket]; while (entry != null) { BiEntry<K, V> nextEntry = entry.nextInKToVBucket; insert(entry); entry = nextEntry; } } this.modCount++; } } @SuppressWarnings("unchecked") private BiEntry<K, V>[] createTable(int length) { return new BiEntry[length]; } @Override public V remove(@Nullable Object key) { BiEntry<K, V> entry = seekByKey(key, hash(key)); if (entry == null) { return null; } else { delete(entry); return entry.value; } } @Override public void clear() { size = 0; Arrays.fill(hashTableKToV, null); Arrays.fill(hashTableVToK, null); modCount++; } @Override public int size() { return size; } abstract class Itr<T> implements Iterator<T> { int nextBucket = 0; BiEntry<K, V> next = null; BiEntry<K, V> toRemove = null; int expectedModCount = modCount; private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); if (next != null) { return true; } while (nextBucket < hashTableKToV.length) { if (hashTableKToV[nextBucket] != null) { next = hashTableKToV[nextBucket++]; return true; } nextBucket++; } return false; } @Override public T next() { checkForConcurrentModification(); if (!hasNext()) { throw new NoSuchElementException(); } BiEntry<K, V> entry = next; next = entry.nextInKToVBucket; toRemove = entry; return output(entry); } @Override public void remove() { checkForConcurrentModification(); checkRemove(toRemove != null); delete(toRemove); expectedModCount = modCount; toRemove = null; } abstract T output(BiEntry<K, V> entry); } @Override public Set<K> keySet() { return new KeySet(); } private final class KeySet extends Maps.KeySet<K, V> { KeySet() { super(HashBiMap.this); } @Override public Iterator<K> iterator() { return new Itr<K>() { @Override K output(BiEntry<K, V> entry) { return entry.key; } }; } @Override public boolean remove(@Nullable Object o) { BiEntry<K, V> entry = seekByKey(o, hash(o)); if (entry == null) { return false; } else { delete(entry); return true; } } } @Override public Set<V> values() { return inverse().keySet(); } @Override public Set<Entry<K, V>> entrySet() { return new EntrySet(); } private final class EntrySet extends Maps.EntrySet<K, V> { @Override Map<K, V> map() { return HashBiMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new Itr<Entry<K, V>>() { @Override Entry<K, V> output(BiEntry<K, V> entry) { return new MapEntry(entry); } class MapEntry extends AbstractMapEntry<K, V> { BiEntry<K, V> delegate; MapEntry(BiEntry<K, V> entry) { this.delegate = entry; } @Override public K getKey() { return delegate.key; } @Override public V getValue() { return delegate.value; } @Override public V setValue(V value) { V oldValue = delegate.value; int valueHash = hash(value); if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) { return value; } checkArgument( seekByValue(value, valueHash) == null, "value already present: %s", value); delete(delegate); BiEntry<K, V> newEntry = new BiEntry<K, V>(delegate.key, delegate.keyHash, value, valueHash); insert(newEntry); expectedModCount = modCount; if (toRemove == delegate) { toRemove = newEntry; } delegate = newEntry; return oldValue; } } }; } } private transient BiMap<V, K> inverse; @Override public BiMap<V, K> inverse() { return (inverse == null) ? inverse = new Inverse() : inverse; } private final class Inverse extends AbstractMap<V, K> implements BiMap<V, K>, Serializable { BiMap<K, V> forward() { return HashBiMap.this; } @Override public int size() { return size; } @Override public void clear() { forward().clear(); } @Override public boolean containsKey(@Nullable Object value) { return forward().containsValue(value); } @Override public K get(@Nullable Object value) { BiEntry<K, V> entry = seekByValue(value, hash(value)); return (entry == null) ? null : entry.key; } @Override public K put(@Nullable V value, @Nullable K key) { return putInverse(value, key, false); } @Override public K forcePut(@Nullable V value, @Nullable K key) { return putInverse(value, key, true); } @Override public K remove(@Nullable Object value) { BiEntry<K, V> entry = seekByValue(value, hash(value)); if (entry == null) { return null; } else { delete(entry); return entry.key; } } @Override public BiMap<K, V> inverse() { return forward(); } @Override public Set<V> keySet() { return new InverseKeySet(); } private final class InverseKeySet extends Maps.KeySet<V, K> { InverseKeySet() { super(Inverse.this); } @Override public boolean remove(@Nullable Object o) { BiEntry<K, V> entry = seekByValue(o, hash(o)); if (entry == null) { return false; } else { delete(entry); return true; } } @Override public Iterator<V> iterator() { return new Itr<V>() { @Override V output(BiEntry<K, V> entry) { return entry.value; } }; } } @Override public Set<K> values() { return forward().keySet(); } @Override public Set<Entry<V, K>> entrySet() { return new Maps.EntrySet<V, K>() { @Override Map<V, K> map() { return Inverse.this; } @Override public Iterator<Entry<V, K>> iterator() { return new Itr<Entry<V, K>>() { @Override Entry<V, K> output(BiEntry<K, V> entry) { return new InverseEntry(entry); } class InverseEntry extends AbstractMapEntry<V, K> { BiEntry<K, V> delegate; InverseEntry(BiEntry<K, V> entry) { this.delegate = entry; } @Override public V getKey() { return delegate.value; } @Override public K getValue() { return delegate.key; } @Override public K setValue(K key) { K oldKey = delegate.key; int keyHash = hash(key); if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) { return key; } checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key); delete(delegate); BiEntry<K, V> newEntry = new BiEntry<K, V>(key, keyHash, delegate.value, delegate.valueHash); insert(newEntry); expectedModCount = modCount; // This is safe because entries can only get bumped up to earlier in the iteration, // so they can't get revisited. return oldKey; } } }; } }; } Object writeReplace() { return new InverseSerializedForm<K, V>(HashBiMap.this); } } private static final class InverseSerializedForm<K, V> implements Serializable { private final HashBiMap<K, V> bimap; InverseSerializedForm(HashBiMap<K, V> bimap) { this.bimap = bimap; } Object readResolve() { return bimap.inverse(); } } /** * @serialData the number of entries, first key, first value, second key, second value, and so on. */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int size = Serialization.readCount(stream); init(size); Serialization.populateMap(this, stream, size); } @GwtIncompatible("Not needed in emulated source") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/HashBiMap.java
Java
asf20
18,268
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Optional; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.Iterator; /** * A variant of {@link TreeTraverser} for binary trees, providing additional traversals specific to * binary trees. * * @author Louis Wasserman * @since 15.0 */ @Beta @GwtCompatible(emulated = true) public abstract class BinaryTreeTraverser<T> extends TreeTraverser<T> { // TODO(user): make this GWT-compatible when we've checked in ArrayDeque and BitSet emulation /** * Returns the left child of the specified node, or {@link Optional#absent()} if the specified * node has no left child. */ public abstract Optional<T> leftChild(T root); /** * Returns the right child of the specified node, or {@link Optional#absent()} if the specified * node has no right child. */ public abstract Optional<T> rightChild(T root); /** * Returns the children of this node, in left-to-right order. */ @Override public final Iterable<T> children(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { boolean doneLeft; boolean doneRight; @Override protected T computeNext() { if (!doneLeft) { doneLeft = true; Optional<T> left = leftChild(root); if (left.isPresent()) { return left.get(); } } if (!doneRight) { doneRight = true; Optional<T> right = rightChild(root); if (right.isPresent()) { return right.get(); } } return endOfData(); } }; } }; } @Override UnmodifiableIterator<T> preOrderIterator(T root) { return new PreOrderIterator(root); } /* * Optimized implementation of preOrderIterator for binary trees. */ private final class PreOrderIterator extends UnmodifiableIterator<T> implements PeekingIterator<T> { private final Deque<T> stack; PreOrderIterator(T root) { this.stack = new ArrayDeque<T>(); stack.addLast(root); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { T result = stack.removeLast(); pushIfPresent(stack, rightChild(result)); pushIfPresent(stack, leftChild(result)); return result; } @Override public T peek() { return stack.getLast(); } } @Override UnmodifiableIterator<T> postOrderIterator(T root) { return new PostOrderIterator(root); } /* * Optimized implementation of postOrderIterator for binary trees. */ private final class PostOrderIterator extends UnmodifiableIterator<T> { private final Deque<T> stack; private final BitSet hasExpanded; PostOrderIterator(T root) { this.stack = new ArrayDeque<T>(); stack.addLast(root); this.hasExpanded = new BitSet(); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { while (true) { T node = stack.getLast(); boolean expandedNode = hasExpanded.get(stack.size() - 1); if (expandedNode) { stack.removeLast(); hasExpanded.clear(stack.size()); return node; } else { hasExpanded.set(stack.size() - 1); pushIfPresent(stack, rightChild(node)); pushIfPresent(stack, leftChild(node)); } } } } // TODO(user): see if any significant optimizations are possible for breadthFirstIterator public final FluentIterable<T> inOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return new InOrderIterator(root); } }; } private final class InOrderIterator extends AbstractIterator<T> { private final Deque<T> stack; private final BitSet hasExpandedLeft; InOrderIterator(T root) { this.stack = new ArrayDeque<T>(); this.hasExpandedLeft = new BitSet(); stack.addLast(root); } @Override protected T computeNext() { while (!stack.isEmpty()) { T node = stack.getLast(); if (hasExpandedLeft.get(stack.size() - 1)) { stack.removeLast(); hasExpandedLeft.clear(stack.size()); pushIfPresent(stack, rightChild(node)); return node; } else { hasExpandedLeft.set(stack.size() - 1); pushIfPresent(stack, leftChild(node)); } } return endOfData(); } } private static <T> void pushIfPresent(Deque<T> stack, Optional<T> node) { if (node.isPresent()) { stack.addLast(node.get()); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/BinaryTreeTraverser.java
Java
asf20
5,728
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import javax.annotation.Nullable; /** * A list which forwards all its method calls to another list. Subclasses should * override one or more methods to modify the behavior of the backing list as * desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>This class does not implement {@link java.util.RandomAccess}. If the * delegate supports random access, the {@code ForwardingList} subclass should * implement the {@code RandomAccess} interface. * * <p><b>Warning:</b> The methods of {@code ForwardingList} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #addAll}, which can lead to unexpected behavior. In this case, you should * override {@code addAll} as well, either providing your own implementation, or * delegating to the provided {@code standardAddAll} method. * * <p>The {@code standard} methods and any collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingList<E> extends ForwardingCollection<E> implements List<E> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingList() {} @Override protected abstract List<E> delegate(); @Override public void add(int index, E element) { delegate().add(index, element); } @Override public boolean addAll(int index, Collection<? extends E> elements) { return delegate().addAll(index, elements); } @Override public E get(int index) { return delegate().get(index); } @Override public int indexOf(Object element) { return delegate().indexOf(element); } @Override public int lastIndexOf(Object element) { return delegate().lastIndexOf(element); } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); } @Override public E remove(int index) { return delegate().remove(index); } @Override public E set(int index, E element) { return delegate().set(index, element); } @Override public List<E> subList(int fromIndex, int toIndex) { return delegate().subList(fromIndex, toIndex); } @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } /** * A sensible default implementation of {@link #add(Object)}, in terms of * {@link #add(int, Object)}. If you override {@link #add(int, Object)}, you * may wish to override {@link #add(Object)} to forward to this * implementation. * * @since 7.0 */ protected boolean standardAdd(E element) { add(size(), element); return true; } /** * A sensible default implementation of {@link #addAll(int, Collection)}, in * terms of the {@code add} method of {@link #listIterator(int)}. If you * override {@link #listIterator(int)}, you may wish to override {@link * #addAll(int, Collection)} to forward to this implementation. * * @since 7.0 */ protected boolean standardAddAll( int index, Iterable<? extends E> elements) { return Lists.addAllImpl(this, index, elements); } /** * A sensible default implementation of {@link #indexOf}, in terms of {@link * #listIterator()}. If you override {@link #listIterator()}, you may wish to * override {@link #indexOf} to forward to this implementation. * * @since 7.0 */ protected int standardIndexOf(@Nullable Object element) { return Lists.indexOfImpl(this, element); } /** * A sensible default implementation of {@link #lastIndexOf}, in terms of * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you * may wish to override {@link #lastIndexOf} to forward to this * implementation. * * @since 7.0 */ protected int standardLastIndexOf(@Nullable Object element) { return Lists.lastIndexOfImpl(this, element); } /** * A sensible default implementation of {@link #iterator}, in terms of * {@link #listIterator()}. If you override {@link #listIterator()}, you may * wish to override {@link #iterator} to forward to this implementation. * * @since 7.0 */ protected Iterator<E> standardIterator() { return listIterator(); } /** * A sensible default implementation of {@link #listIterator()}, in terms of * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you * may wish to override {@link #listIterator()} to forward to this * implementation. * * @since 7.0 */ protected ListIterator<E> standardListIterator() { return listIterator(0); } /** * A sensible default implementation of {@link #listIterator(int)}, in terms * of {@link #size}, {@link #get(int)}, {@link #set(int, Object)}, {@link * #add(int, Object)}, and {@link #remove(int)}. If you override any of these * methods, you may wish to override {@link #listIterator(int)} to forward to * this implementation. * * @since 7.0 */ @Beta protected ListIterator<E> standardListIterator(int start) { return Lists.listIteratorImpl(this, start); } /** * A sensible default implementation of {@link #subList(int, int)}. If you * override any other methods, you may wish to override {@link #subList(int, * int)} to forward to this implementation. * * @since 7.0 */ @Beta protected List<E> standardSubList(int fromIndex, int toIndex) { return Lists.subListImpl(this, fromIndex, toIndex); } /** * A sensible definition of {@link #equals(Object)} in terms of {@link #size} * and {@link #iterator}. If you override either of those methods, you may * wish to override {@link #equals(Object)} to forward to this implementation. * * @since 7.0 */ @Beta protected boolean standardEquals(@Nullable Object object) { return Lists.equalsImpl(this, object); } /** * A sensible definition of {@link #hashCode} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link * #hashCode} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardHashCode() { return Lists.hashCodeImpl(this); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingList.java
Java
asf20
7,504
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.util.ArrayDeque; import java.util.Collection; import java.util.Queue; /** * A non-blocking queue which automatically evicts elements from the head of the queue when * attempting to add new elements onto the queue and it is full. * * <p>An evicting queue must be configured with a maximum size. Each time an element is added * to a full queue, the queue automatically removes its head element. This is different from * conventional bounded queues, which either block or reject new elements when full. * * <p>This class is not thread-safe, and does not accept null elements. * * @author Kurt Alfred Kluever * @since 15.0 */ @Beta @GwtIncompatible("java.util.ArrayDeque") public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serializable { private final Queue<E> delegate; @VisibleForTesting final int maxSize; private EvictingQueue(int maxSize) { checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize); this.delegate = new ArrayDeque<E>(maxSize); this.maxSize = maxSize; } /** * Creates and returns a new evicting queue that will hold up to {@code maxSize} elements. * * <p>When {@code maxSize} is zero, elements will be evicted immediately after being added to the * queue. */ public static <E> EvictingQueue<E> create(int maxSize) { return new EvictingQueue<E>(maxSize); } /** * Returns the number of additional elements that this queue can accept without evicting; * zero if the queue is currently full. * * @since 16.0 */ public int remainingCapacity() { return maxSize - size(); } @Override protected Queue<E> delegate() { return delegate; } /** * Adds the given element to this queue. If the queue is currently full, the element at the head * of the queue is evicted to make room. * * @return {@code true} always */ @Override public boolean offer(E e) { return add(e); } /** * Adds the given element to this queue. If the queue is currently full, the element at the head * of the queue is evicted to make room. * * @return {@code true} always */ @Override public boolean add(E e) { checkNotNull(e); // check before removing if (maxSize == 0) { return true; } if (size() == maxSize) { delegate.remove(); } delegate.add(e); return true; } @Override public boolean addAll(Collection<? extends E> collection) { return standardAddAll(collection); } @Override public boolean contains(Object object) { return delegate().contains(checkNotNull(object)); } @Override public boolean remove(Object object) { return delegate().remove(checkNotNull(object)); } // TODO(user): Do we want to checkNotNull each element in containsAll, removeAll, and retainAll? private static final long serialVersionUID = 0L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EvictingQueue.java
Java
asf20
3,817
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Booleans; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import java.util.Comparator; import javax.annotation.Nullable; /** * A utility for performing a chained comparison statement. For example: * <pre> {@code * * public int compareTo(Foo that) { * return ComparisonChain.start() * .compare(this.aString, that.aString) * .compare(this.anInt, that.anInt) * .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()) * .result(); * }}</pre> * * <p>The value of this expression will have the same sign as the <i>first * nonzero</i> comparison result in the chain, or will be zero if every * comparison result was zero. * * <p>Performance note: Even though the {@code ComparisonChain} caller always * invokes its {@code compare} methods unconditionally, the {@code * ComparisonChain} implementation stops calling its inputs' {@link * Comparable#compareTo compareTo} and {@link Comparator#compare compare} * methods as soon as one of them returns a nonzero result. This optimization is * typically important only in the presence of expensive {@code compareTo} and * {@code compare} implementations. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#compare/compareTo"> * {@code ComparisonChain}</a>. * * @author Mark Davis * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible public abstract class ComparisonChain { private ComparisonChain() {} /** * Begins a new chained comparison statement. See example in the class * documentation. */ public static ComparisonChain start() { return ACTIVE; } private static final ComparisonChain ACTIVE = new ComparisonChain() { @SuppressWarnings("unchecked") @Override public ComparisonChain compare( Comparable left, Comparable right) { return classify(left.compareTo(right)); } @Override public <T> ComparisonChain compare( @Nullable T left, @Nullable T right, Comparator<T> comparator) { return classify(comparator.compare(left, right)); } @Override public ComparisonChain compare(int left, int right) { return classify(Ints.compare(left, right)); } @Override public ComparisonChain compare(long left, long right) { return classify(Longs.compare(left, right)); } @Override public ComparisonChain compare(float left, float right) { return classify(Float.compare(left, right)); } @Override public ComparisonChain compare(double left, double right) { return classify(Double.compare(left, right)); } @Override public ComparisonChain compareTrueFirst(boolean left, boolean right) { return classify(Booleans.compare(right, left)); // reversed } @Override public ComparisonChain compareFalseFirst(boolean left, boolean right) { return classify(Booleans.compare(left, right)); } ComparisonChain classify(int result) { return (result < 0) ? LESS : (result > 0) ? GREATER : ACTIVE; } @Override public int result() { return 0; } }; private static final ComparisonChain LESS = new InactiveComparisonChain(-1); private static final ComparisonChain GREATER = new InactiveComparisonChain(1); private static final class InactiveComparisonChain extends ComparisonChain { final int result; InactiveComparisonChain(int result) { this.result = result; } @Override public ComparisonChain compare( @Nullable Comparable left, @Nullable Comparable right) { return this; } @Override public <T> ComparisonChain compare(@Nullable T left, @Nullable T right, @Nullable Comparator<T> comparator) { return this; } @Override public ComparisonChain compare(int left, int right) { return this; } @Override public ComparisonChain compare(long left, long right) { return this; } @Override public ComparisonChain compare(float left, float right) { return this; } @Override public ComparisonChain compare(double left, double right) { return this; } @Override public ComparisonChain compareTrueFirst(boolean left, boolean right) { return this; } @Override public ComparisonChain compareFalseFirst(boolean left, boolean right) { return this; } @Override public int result() { return result; } } /** * Compares two comparable objects as specified by {@link * Comparable#compareTo}, <i>if</i> the result of this comparison chain * has not already been determined. */ public abstract ComparisonChain compare( Comparable<?> left, Comparable<?> right); /** * Compares two objects using a comparator, <i>if</i> the result of this * comparison chain has not already been determined. */ public abstract <T> ComparisonChain compare( @Nullable T left, @Nullable T right, Comparator<T> comparator); /** * Compares two {@code int} values as specified by {@link Ints#compare}, * <i>if</i> the result of this comparison chain has not already been * determined. */ public abstract ComparisonChain compare(int left, int right); /** * Compares two {@code long} values as specified by {@link Longs#compare}, * <i>if</i> the result of this comparison chain has not already been * determined. */ public abstract ComparisonChain compare(long left, long right); /** * Compares two {@code float} values as specified by {@link * Float#compare}, <i>if</i> the result of this comparison chain has not * already been determined. */ public abstract ComparisonChain compare(float left, float right); /** * Compares two {@code double} values as specified by {@link * Double#compare}, <i>if</i> the result of this comparison chain has not * already been determined. */ public abstract ComparisonChain compare(double left, double right); /** * Compares two {@code boolean} values, considering {@code true} to be less * than {@code false}, <i>if</i> the result of this comparison chain has not * already been determined. * * @since 12.0 */ public abstract ComparisonChain compareTrueFirst(boolean left, boolean right); /** * Compares two {@code boolean} values, considering {@code false} to be less * than {@code true}, <i>if</i> the result of this comparison chain has not * already been determined. * * @since 12.0 (present as {@code compare} since 2.0) */ public abstract ComparisonChain compareFalseFirst(boolean left, boolean right); /** * Ends this comparison chain and returns its result: a value having the * same sign as the first nonzero comparison result in the chain, or zero if * every result was zero. */ public abstract int result(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ComparisonChain.java
Java
asf20
7,584
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Nullable; /** * A collection that supports order-independent equality, like {@link Set}, but * may have duplicate elements. A multiset is also sometimes called a * <i>bag</i>. * * <p>Elements of a multiset that are equal to one another are referred to as * <i>occurrences</i> of the same single element. The total number of * occurrences of an element in a multiset is called the <i>count</i> of that * element (the terms "frequency" and "multiplicity" are equivalent, but not * used in this API). Since the count of an element is represented as an {@code * int}, a multiset may never contain more than {@link Integer#MAX_VALUE} * occurrences of any one element. * * <p>{@code Multiset} refines the specifications of several methods from * {@code Collection}. It also defines an additional query operation, {@link * #count}, which returns the count of an element. There are five new * bulk-modification operations, for example {@link #add(Object, int)}, to add * or remove multiple occurrences of an element at once, or to set the count of * an element to a specific value. These modification operations are optional, * but implementations which support the standard collection operations {@link * #add(Object)} or {@link #remove(Object)} are encouraged to implement the * related methods as well. Finally, two collection views are provided: {@link * #elementSet} contains the distinct elements of the multiset "with duplicates * collapsed", and {@link #entrySet} is similar but contains {@link Entry * Multiset.Entry} instances, each providing both a distinct element and the * count of that element. * * <p>In addition to these required methods, implementations of {@code * Multiset} are expected to provide two {@code static} creation methods: * {@code create()}, returning an empty multiset, and {@code * create(Iterable<? extends E>)}, returning a multiset containing the * given initial elements. This is simply a refinement of {@code Collection}'s * constructor recommendations, reflecting the new developments of Java 5. * * <p>As with other collection types, the modification operations are optional, * and should throw {@link UnsupportedOperationException} when they are not * implemented. Most implementations should support either all add operations * or none of them, all removal operations or none of them, and if and only if * all of these are supported, the {@code setCount} methods as well. * * <p>A multiset uses {@link Object#equals} to determine whether two instances * should be considered "the same," <i>unless specified otherwise</i> by the * implementation. * * <p>Common implementations include {@link ImmutableMultiset}, {@link * HashMultiset}, and {@link ConcurrentHashMultiset}. * * <p>If your values may be zero, negative, or outside the range of an int, you * may wish to use {@link com.google.common.util.concurrent.AtomicLongMap} * instead. Note, however, that unlike {@code Multiset}, {@code AtomicLongMap} * does not automatically remove zeros. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Multiset<E> extends Collection<E> { // Query Operations /** * Returns the number of occurrences of an element in this multiset (the * <i>count</i> of the element). Note that for an {@link Object#equals}-based * multiset, this gives the same result as {@link Collections#frequency} * (which would presumably perform more poorly). * * <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes * this operation; it correctly delegates to this method when dealing with a * multiset, but it can also accept any other iterable type. * * @param element the element to count occurrences of * @return the number of occurrences of the element in this multiset; possibly * zero but never negative */ int count(@Nullable Object element); // Bulk Operations /** * Adds a number of occurrences of an element to this multiset. Note that if * {@code occurrences == 1}, this method has the identical effect to {@link * #add(Object)}. This method is functionally equivalent (except in the case * of overflow) to the call {@code addAll(Collections.nCopies(element, * occurrences))}, which would presumably perform much more poorly. * * @param element the element to add occurrences of; may be null only if * explicitly allowed by the implementation * @param occurrences the number of occurrences of the element to add. May be * zero, in which case no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative, or if * this operation would result in more than {@link Integer#MAX_VALUE} * occurrences of the element * @throws NullPointerException if {@code element} is null and this * implementation does not permit null elements. Note that if {@code * occurrences} is zero, the implementation may opt to return normally. */ int add(@Nullable E element, int occurrences); /** * Removes a number of occurrences of the specified element from this * multiset. If the multiset contains fewer than this number of occurrences to * begin with, all occurrences will be removed. Note that if * {@code occurrences == 1}, this is functionally equivalent to the call * {@code remove(element)}. * * @param element the element to conditionally remove occurrences of * @param occurrences the number of occurrences of the element to remove. May * be zero, in which case no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative */ int remove(@Nullable Object element, int occurrences); /** * Adds or removes the necessary occurrences of an element such that the * element attains the desired count. * * @param element the element to add or remove occurrences of; may be null * only if explicitly allowed by the implementation * @param count the desired count of the element in this multiset * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code count} is negative * @throws NullPointerException if {@code element} is null and this * implementation does not permit null elements. Note that if {@code * count} is zero, the implementor may optionally return zero instead. */ int setCount(E element, int count); /** * Conditionally sets the count of an element to a new value, as described in * {@link #setCount(Object, int)}, provided that the element has the expected * current count. If the current count is not {@code oldCount}, no change is * made. * * @param element the element to conditionally set the count of; may be null * only if explicitly allowed by the implementation * @param oldCount the expected present count of the element in this multiset * @param newCount the desired count of the element in this multiset * @return {@code true} if the condition for modification was met. This * implies that the multiset was indeed modified, unless * {@code oldCount == newCount}. * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is * negative * @throws NullPointerException if {@code element} is null and the * implementation does not permit null elements. Note that if {@code * oldCount} and {@code newCount} are both zero, the implementor may * optionally return {@code true} instead. */ boolean setCount(E element, int oldCount, int newCount); // Views /** * Returns the set of distinct elements contained in this multiset. The * element set is backed by the same data as the multiset, so any change to * either is immediately reflected in the other. The order of the elements in * the element set is unspecified. * * <p>If the element set supports any removal operations, these necessarily * cause <b>all</b> occurrences of the removed element(s) to be removed from * the multiset. Implementations are not expected to support the add * operations, although this is possible. * * <p>A common use for the element set is to find the number of distinct * elements in the multiset: {@code elementSet().size()}. * * @return a view of the set of distinct elements in this multiset */ Set<E> elementSet(); /** * Returns a view of the contents of this multiset, grouped into {@code * Multiset.Entry} instances, each providing an element of the multiset and * the count of that element. This set contains exactly one entry for each * distinct element in the multiset (thus it always has the same size as the * {@link #elementSet}). The order of the elements in the element set is * unspecified. * * <p>The entry set is backed by the same data as the multiset, so any change * to either is immediately reflected in the other. However, multiset changes * may or may not be reflected in any {@code Entry} instances already * retrieved from the entry set (this is implementation-dependent). * Furthermore, implementations are not required to support modifications to * the entry set at all, and the {@code Entry} instances themselves don't * even have methods for modification. See the specific implementation class * for more details on how its entry set handles modifications. * * @return a set of entries representing the data of this multiset */ Set<Entry<E>> entrySet(); /** * An unmodifiable element-count pair for a multiset. The {@link * Multiset#entrySet} method returns a view of the multiset whose elements * are of this class. A multiset implementation may return Entry instances * that are either live "read-through" views to the Multiset, or immutable * snapshots. Note that this type is unrelated to the similarly-named type * {@code Map.Entry}. * * @since 2.0 (imported from Google Collections Library) */ interface Entry<E> { /** * Returns the multiset element corresponding to this entry. Multiple calls * to this method always return the same instance. * * @return the element corresponding to this entry */ E getElement(); /** * Returns the count of the associated element in the underlying multiset. * This count may either be an unchanging snapshot of the count at the time * the entry was retrieved, or a live view of the current count of the * element in the multiset, depending on the implementation. Note that in * the former case, this method can never return zero, while in the latter, * it will return zero if all occurrences of the element were since removed * from the multiset. * * @return the count of the element; never negative */ int getCount(); /** * {@inheritDoc} * * <p>Returns {@code true} if the given object is also a multiset entry and * the two entries represent the same element and count. That is, two * entries {@code a} and {@code b} are equal if: <pre> {@code * * Objects.equal(a.getElement(), b.getElement()) * && a.getCount() == b.getCount()}</pre> */ @Override // TODO(kevinb): check this wrt TreeMultiset? boolean equals(Object o); /** * {@inheritDoc} * * <p>The hash code of a multiset entry for element {@code element} and * count {@code count} is defined as: <pre> {@code * * ((element == null) ? 0 : element.hashCode()) ^ count}</pre> */ @Override int hashCode(); /** * Returns the canonical string representation of this entry, defined as * follows. If the count for this entry is one, this is simply the string * representation of the corresponding element. Otherwise, it is the string * representation of the element, followed by the three characters {@code * " x "} (space, letter x, space), followed by the count. */ @Override String toString(); } // Comparison and hashing /** * Compares the specified object with this multiset for equality. Returns * {@code true} if the given object is also a multiset and contains equal * elements with equal counts, regardless of order. */ @Override // TODO(kevinb): caveats about equivalence-relation? boolean equals(@Nullable Object object); /** * Returns the hash code for this multiset. This is defined as the sum of * <pre> {@code * * ((element == null) ? 0 : element.hashCode()) ^ count(element)}</pre> * * <p>over all distinct elements in the multiset. It follows that a multiset and * its entry set always have the same hash code. */ @Override int hashCode(); /** * {@inheritDoc} * * <p>It is recommended, though not mandatory, that this method return the * result of invoking {@link #toString} on the {@link #entrySet}, yielding a * result such as {@code [a x 3, c, d x 2, e]}. */ @Override String toString(); // Refined Collection Methods /** * {@inheritDoc} * * <p>Elements that occur multiple times in the multiset will appear * multiple times in this iterator, though not necessarily sequentially. */ @Override Iterator<E> iterator(); /** * Determines whether this multiset contains the specified element. * * <p>This method refines {@link Collection#contains} to further specify that * it <b>may not</b> throw an exception in response to {@code element} being * null or of the wrong type. * * @param element the element to check for * @return {@code true} if this multiset contains at least one occurrence of * the element */ @Override boolean contains(@Nullable Object element); /** * Returns {@code true} if this multiset contains at least one occurrence of * each element in the specified collection. * * <p>This method refines {@link Collection#containsAll} to further specify * that it <b>may not</b> throw an exception in response to any of {@code * elements} being null or of the wrong type. * * <p><b>Note:</b> this method does not take into account the occurrence * count of an element in the two collections; it may still return {@code * true} even if {@code elements} contains several occurrences of an element * and this multiset contains only one. This is no different than any other * collection type like {@link List}, but it may be unexpected to the user of * a multiset. * * @param elements the collection of elements to be checked for containment in * this multiset * @return {@code true} if this multiset contains at least one occurrence of * each element contained in {@code elements} * @throws NullPointerException if {@code elements} is null */ @Override boolean containsAll(Collection<?> elements); /** * Adds a single occurrence of the specified element to this multiset. * * <p>This method refines {@link Collection#add}, which only <i>ensures</i> * the presence of the element, to further specify that a successful call must * always increment the count of the element, and the overall size of the * collection, by one. * * @param element the element to add one occurrence of; may be null only if * explicitly allowed by the implementation * @return {@code true} always, since this call is required to modify the * multiset, unlike other {@link Collection} types * @throws NullPointerException if {@code element} is null and this * implementation does not permit null elements * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences * of {@code element} are already contained in this multiset */ @Override boolean add(E element); /** * Removes a <i>single</i> occurrence of the specified element from this * multiset, if present. * * <p>This method refines {@link Collection#remove} to further specify that it * <b>may not</b> throw an exception in response to {@code element} being null * or of the wrong type. * * @param element the element to remove one occurrence of * @return {@code true} if an occurrence was found and removed */ @Override boolean remove(@Nullable Object element); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in * {@code c}, and only cares whether or not an element appears at all. * If you wish to remove one occurrence in this multiset for every occurrence * in {@code c}, see {@link Multisets#removeOccurrences(Multiset, Multiset)}. * * <p>This method refines {@link Collection#removeAll} to further specify that * it <b>may not</b> throw an exception in response to any of {@code elements} * being null or of the wrong type. */ @Override boolean removeAll(Collection<?> c); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in * {@code c}, and only cares whether or not an element appears at all. * If you wish to remove one occurrence in this multiset for every occurrence * in {@code c}, see {@link Multisets#retainOccurrences(Multiset, Multiset)}. * * <p>This method refines {@link Collection#retainAll} to further specify that * it <b>may not</b> throw an exception in response to any of {@code elements} * being null or of the wrong type. * * @see Multisets#retainOccurrences(Multiset, Multiset) */ @Override boolean retainAll(Collection<?> c); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Multiset.java
Java
asf20
18,832
/* * 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.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.SortedMap; import javax.annotation.Nullable; /** * A sorted map which forwards all its method calls to another sorted map. * Subclasses should override one or more methods to modify the behavior of * the backing sorted map as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingSortedMap} forward * <i>indiscriminately</i> to the methods of the delegate. For example, * overriding {@link #put} alone <i>will not</i> change the behavior of {@link * #putAll}, which can lead to unexpected behavior. In this case, you should * override {@code putAll} as well, either providing your own implementation, or * delegating to the provided {@code standardPutAll} method. * * <p>Each of the {@code standard} methods, where appropriate, use the * comparator of the map to test equality for both keys and values, unlike * {@code ForwardingMap}. * * <p>The {@code standard} methods and the collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSortedMap<K, V> extends ForwardingMap<K, V> implements SortedMap<K, V> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingSortedMap() {} @Override protected abstract SortedMap<K, V> delegate(); @Override public Comparator<? super K> comparator() { return delegate().comparator(); } @Override public K firstKey() { return delegate().firstKey(); } @Override public SortedMap<K, V> headMap(K toKey) { return delegate().headMap(toKey); } @Override public K lastKey() { return delegate().lastKey(); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return delegate().subMap(fromKey, toKey); } @Override public SortedMap<K, V> tailMap(K fromKey) { return delegate().tailMap(fromKey); } /** * A sensible implementation of {@link SortedMap#keySet} in terms of the methods of * {@code ForwardingSortedMap}. In many cases, you may wish to override * {@link ForwardingSortedMap#keySet} to forward to this implementation or a subclass thereof. * * @since 15.0 */ @Beta protected class StandardKeySet extends Maps.SortedKeySet<K, V> { /** Constructor for use by subclasses. */ public StandardKeySet() { super(ForwardingSortedMap.this); } } // unsafe, but worst case is a CCE is thrown, which callers will be expecting @SuppressWarnings("unchecked") private int unsafeCompare(Object k1, Object k2) { Comparator<? super K> comparator = comparator(); if (comparator == null) { return ((Comparable<Object>) k1).compareTo(k2); } else { return ((Comparator<Object>) comparator).compare(k1, k2); } } /** * A sensible definition of {@link #containsKey} in terms of the {@code * firstKey()} method of {@link #tailMap}. If you override {@link #tailMap}, * you may wish to override {@link #containsKey} to forward to this * implementation. * * @since 7.0 */ @Override @Beta protected boolean standardContainsKey(@Nullable Object key) { try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Object ceilingKey = self.tailMap(key).firstKey(); return unsafeCompare(ceilingKey, key) == 0; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; } catch (NullPointerException e) { return false; } } /** * A sensible default implementation of {@link #subMap(Object, Object)} in * terms of {@link #headMap(Object)} and {@link #tailMap(Object)}. In some * situations, you may wish to override {@link #subMap(Object, Object)} to * forward to this implementation. * * @since 7.0 */ @Beta protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) { checkArgument(unsafeCompare(fromKey, toKey) <= 0, "fromKey must be <= toKey"); return tailMap(fromKey).headMap(toKey); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingSortedMap.java
Java
asf20
5,222
/* * 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; /** * A constraint that an element must satisfy in order to be added to a * collection. For example, {@link Constraints#notNull()}, which prevents a * collection from including any null elements, could be implemented like this: * <pre> {@code * * public Object checkElement(Object element) { * if (element == null) { * throw new NullPointerException(); * } * return element; * }}</pre> * * <p>In order to be effective, constraints should be deterministic; that is, * they should not depend on state that can change (such as external state, * random variables, and time) and should only depend on the value of the * passed-in element. A non-deterministic constraint cannot reliably enforce * that all the collection's elements meet the constraint, since the constraint * is only enforced when elements are added. * * @author Mike Bostock */ @GwtCompatible interface Constraint<E> { /** * Throws a suitable {@code RuntimeException} if the specified element is * illegal. Typically this is either a {@link NullPointerException}, an * {@link IllegalArgumentException}, or a {@link ClassCastException}, though * an application-specific exception class may be used if appropriate. * * @param element the element to check * @return the provided element */ E checkElement(E element); /** * Returns a brief human readable description of this constraint, such as * "Not null" or "Positive number". */ @Override String toString(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Constraint.java
Java
asf20
2,202
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import java.util.ArrayList; import java.util.Arrays; 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.NoSuchElementException; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * A comparator, with additional methods to support common operations. This is * an "enriched" version of {@code Comparator}, in the same sense that {@link * FluentIterable} is an enriched {@link Iterable}. * * <p>The common ways to get an instance of {@code Ordering} are: * * <ul> * <li>Subclass it and implement {@link #compare} instead of implementing * {@link Comparator} directly * <li>Pass a <i>pre-existing</i> {@link Comparator} instance to {@link * #from(Comparator)} * <li>Use the natural ordering, {@link Ordering#natural} * </ul> * * <p>Then you can use the <i>chaining</i> methods to get an altered version of * that {@code Ordering}, including: * * <ul> * <li>{@link #reverse} * <li>{@link #compound(Comparator)} * <li>{@link #onResultOf(Function)} * <li>{@link #nullsFirst} / {@link #nullsLast} * </ul> * * <p>Finally, use the resulting {@code Ordering} anywhere a {@link Comparator} * is required, or use any of its special operations, such as:</p> * * <ul> * <li>{@link #immutableSortedCopy} * <li>{@link #isOrdered} / {@link #isStrictlyOrdered} * <li>{@link #min} / {@link #max} * </ul> * * <p>Except as noted, the orderings returned by the factory methods of this * class are serializable if and only if the provided instances that back them * are. For example, if {@code ordering} and {@code function} can themselves be * serialized, then {@code ordering.onResultOf(function)} can as well. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/OrderingExplained"> * {@code Ordering}</a>. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class Ordering<T> implements Comparator<T> { // Natural order /** * Returns a serializable ordering that uses the natural order of the values. * The ordering throws a {@link NullPointerException} when passed a null * parameter. * * <p>The type specification is {@code <C extends Comparable>}, instead of * the technically correct {@code <C extends Comparable<? super C>>}, to * support legacy types from before Java 5. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this?? public static <C extends Comparable> Ordering<C> natural() { return (Ordering<C>) NaturalOrdering.INSTANCE; } // Static factories /** * Returns an ordering based on an <i>existing</i> comparator instance. Note * that it is unnecessary to create a <i>new</i> anonymous inner class * implementing {@code Comparator} just to pass it in here. Instead, simply * subclass {@code Ordering} and implement its {@code compare} method * directly. * * @param comparator the comparator that defines the order * @return comparator itself if it is already an {@code Ordering}; otherwise * an ordering that wraps that comparator */ @GwtCompatible(serializable = true) public static <T> Ordering<T> from(Comparator<T> comparator) { return (comparator instanceof Ordering) ? (Ordering<T>) comparator : new ComparatorOrdering<T>(comparator); } /** * Simply returns its argument. * * @deprecated no need to use this */ @GwtCompatible(serializable = true) @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) { return checkNotNull(ordering); } /** * Returns an ordering that compares objects according to the order in * which they appear in the given list. Only objects present in the list * (according to {@link Object#equals}) may be compared. This comparator * imposes a "partial ordering" over the type {@code T}. Subsequent changes * to the {@code valuesInOrder} list will have no effect on the returned * comparator. Null values in the list are not supported. * * <p>The returned comparator throws an {@link ClassCastException} when it * receives an input parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are * serializable. * * @param valuesInOrder the values that the returned comparator will be able * to compare, in the order the comparator should induce * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if {@code valuesInOrder} contains any * duplicate values (according to {@link Object#equals}) */ @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit(List<T> valuesInOrder) { return new ExplicitOrdering<T>(valuesInOrder); } /** * Returns an ordering that compares objects according to the order in * which they are given to this method. Only objects present in the argument * list (according to {@link Object#equals}) may be compared. This comparator * imposes a "partial ordering" over the type {@code T}. Null values in the * argument list are not supported. * * <p>The returned comparator throws a {@link ClassCastException} when it * receives an input parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are * serializable. * * @param leastValue the value which the returned comparator should consider * the "least" of all values * @param remainingValuesInOrder the rest of the values that the returned * comparator will be able to compare, in the order the comparator should * follow * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if any duplicate values (according to * {@link Object#equals(Object)}) are present among the method arguments */ @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit( T leastValue, T... remainingValuesInOrder) { return explicit(Lists.asList(leastValue, remainingValuesInOrder)); } // Ordering<Object> singletons /** * Returns an ordering which treats all values as equal, indicating "no * ordering." Passing this ordering to any <i>stable</i> sort algorithm * results in no change to the order of elements. Note especially that {@link * #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the * returned instance these are implemented by simply copying the source list. * * <p>Example: <pre> {@code * * Ordering.allEqual().nullsLast().sortedCopy( * asList(t, null, e, s, null, t, null))}</pre> * * <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison * order of those three values (which might not even implement {@link * Comparable} at all). * * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with * equals</i> (as defined {@linkplain Comparator here}). Avoid its use in * APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency * is expected. * * <p>The returned comparator is serializable. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") public static Ordering<Object> allEqual() { return AllEqualOrdering.INSTANCE; } /** * Returns an ordering that compares objects by the natural ordering of their * string representations as returned by {@code toString()}. It does not * support null values. * * <p>The comparator is serializable. */ @GwtCompatible(serializable = true) public static Ordering<Object> usingToString() { return UsingToStringOrdering.INSTANCE; } /** * Returns an arbitrary ordering over all objects, for which {@code compare(a, * b) == 0} implies {@code a == b} (identity equality). There is no meaning * whatsoever to the order imposed, but it is constant for the life of the VM. * * <p>Because the ordering is identity-based, it is not "consistent with * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use * caution when building a {@link SortedSet} or {@link SortedMap} from it, as * the resulting collection will not behave exactly according to spec. * * <p>This ordering is not serializable, as its implementation relies on * {@link System#identityHashCode(Object)}, so its behavior cannot be * preserved across serialization. * * @since 2.0 */ public static Ordering<Object> arbitrary() { return ArbitraryOrderingHolder.ARBITRARY_ORDERING; } private static class ArbitraryOrderingHolder { static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering(); } @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> { @SuppressWarnings("deprecation") // TODO(kevinb): ? private Map<Object, Integer> uids = Platform.tryWeakKeys(new MapMaker()).makeComputingMap( new Function<Object, Integer>() { final AtomicInteger counter = new AtomicInteger(0); @Override public Integer apply(Object from) { return counter.getAndIncrement(); } }); @Override public int compare(Object left, Object right) { if (left == right) { return 0; } else if (left == null) { return -1; } else if (right == null) { return 1; } int leftCode = identityHashCode(left); int rightCode = identityHashCode(right); if (leftCode != rightCode) { return leftCode < rightCode ? -1 : 1; } // identityHashCode collision (rare, but not as rare as you'd think) int result = uids.get(left).compareTo(uids.get(right)); if (result == 0) { throw new AssertionError(); // extremely, extremely unlikely. } return result; } @Override public String toString() { return "Ordering.arbitrary()"; } /* * We need to be able to mock identityHashCode() calls for tests, because it * can take 1-10 seconds to find colliding objects. Mocking frameworks that * can do magic to mock static method calls still can't do so for a system * class, so we need the indirection. In production, Hotspot should still * recognize that the call is 1-morphic and should still be willing to * inline it if necessary. */ int identityHashCode(Object object) { return System.identityHashCode(object); } } // Constructor /** * Constructs a new instance of this class (only invokable by the subclass * constructor, typically implicit). */ protected Ordering() {} // Instance-based factories (and any static equivalents) /** * Returns the reverse of this ordering; the {@code Ordering} equivalent to * {@link Collections#reverseOrder(Comparator)}. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().reverse(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> reverse() { return new ReverseOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as less than all other values * and uses {@code this} to compare non-null values. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsFirst(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> nullsFirst() { return new NullsFirstOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as greater than all other * values and uses this ordering to compare non-null values. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsLast(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> nullsLast() { return new NullsLastOrdering<S>(this); } /** * Returns a new ordering on {@code F} which orders elements by first applying * a function to them, then comparing those results using {@code this}. For * example, to compare objects by their string forms, in a case-insensitive * manner, use: <pre> {@code * * Ordering.from(String.CASE_INSENSITIVE_ORDER) * .onResultOf(Functions.toStringFunction())}</pre> */ @GwtCompatible(serializable = true) public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) { return new ByFunctionOrdering<F, T>(function, this); } <T2 extends T> Ordering<Map.Entry<T2, ?>> onKeys() { return onResultOf(Maps.<T2>keyFunction()); } /** * Returns an ordering which first uses the ordering {@code this}, but which * in the event of a "tie", then delegates to {@code secondaryComparator}. * For example, to sort a bug list first by status and second by priority, you * might use {@code byStatus.compound(byPriority)}. For a compound ordering * with three or more components, simply chain multiple calls to this method. * * <p>An ordering produced by this method, or a chain of calls to this method, * is equivalent to one created using {@link Ordering#compound(Iterable)} on * the same component comparators. */ @GwtCompatible(serializable = true) public <U extends T> Ordering<U> compound( Comparator<? super U> secondaryComparator) { return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator)); } /** * Returns an ordering which tries each given comparator in order until a * non-zero result is found, returning that result, and returning zero only if * all comparators return zero. The returned ordering is based on the state of * the {@code comparators} iterable at the time it was provided to this * method. * * <p>The returned ordering is equivalent to that produced using {@code * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. * * <p><b>Warning:</b> Supplying an argument with undefined iteration order, * such as a {@link HashSet}, will produce non-deterministic results. * * @param comparators the comparators to try in order */ @GwtCompatible(serializable = true) public static <T> Ordering<T> compound( Iterable<? extends Comparator<? super T>> comparators) { return new CompoundOrdering<T>(comparators); } /** * Returns a new ordering which sorts iterables by comparing corresponding * elements pairwise until a nonzero result is found; imposes "dictionary * order". If the end of one iterable is reached, but not the other, the * shorter iterable is considered to be less than the longer one. For example, * a lexicographical natural ordering over integers considers {@code * [] < [1] < [1, 1] < [1, 2] < [2]}. * * <p>Note that {@code ordering.lexicographical().reverse()} is not * equivalent to {@code ordering.reverse().lexicographical()} (consider how * each would order {@code [1]} and {@code [1, 1]}). * * @since 2.0 */ @GwtCompatible(serializable = true) // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<Iterable<String>> o = // Ordering.<String>natural().lexicographical(); public <S extends T> Ordering<Iterable<S>> lexicographical() { /* * Note that technically the returned ordering should be capable of * handling not just {@code Iterable<S>} instances, but also any {@code * Iterable<? extends S>}. However, the need for this comes up so rarely * that it doesn't justify making everyone else deal with the very ugly * wildcard. */ return new LexicographicalOrdering<S>(this); } // Regular instance methods // Override to add @Nullable @Override public abstract int compare(@Nullable T left, @Nullable T right); /** * Returns the least of the specified values according to this ordering. If * there are multiple least values, the first of those is returned. The * iterator will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @param iterator the iterator whose minimum element is to be determined * @throws NoSuchElementException if {@code iterator} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. * * @since 11.0 */ public <E extends T> E min(Iterator<E> iterator) { // let this throw NoSuchElementException as necessary E minSoFar = iterator.next(); while (iterator.hasNext()) { minSoFar = min(minSoFar, iterator.next()); } return minSoFar; } /** * Returns the least of the specified values according to this ordering. If * there are multiple least values, the first of those is returned. * * @param iterable the iterable whose minimum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(Iterable<E> iterable) { return min(iterable.iterator()); } /** * Returns the lesser of the two values according to this ordering. If the * values compare as 0, the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default * implementations of the other {@code min} overloads, so overriding it will * affect their behavior. * * @param a value to compare, returned if less than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(@Nullable E a, @Nullable E b) { return (compare(a, b) <= 0) ? a : b; } /** * Returns the least of the specified values according to this ordering. If * there are multiple least values, the first of those is returned. * * @param a value to compare, returned if less than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min( @Nullable E a, @Nullable E b, @Nullable E c, E... rest) { E minSoFar = min(min(a, b), c); for (E r : rest) { minSoFar = min(minSoFar, r); } return minSoFar; } /** * Returns the greatest of the specified values according to this ordering. If * there are multiple greatest values, the first of those is returned. The * iterator will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @param iterator the iterator whose maximum element is to be determined * @throws NoSuchElementException if {@code iterator} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. * * @since 11.0 */ public <E extends T> E max(Iterator<E> iterator) { // let this throw NoSuchElementException as necessary E maxSoFar = iterator.next(); while (iterator.hasNext()) { maxSoFar = max(maxSoFar, iterator.next()); } return maxSoFar; } /** * Returns the greatest of the specified values according to this ordering. If * there are multiple greatest values, the first of those is returned. * * @param iterable the iterable whose maximum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(Iterable<E> iterable) { return max(iterable.iterator()); } /** * Returns the greater of the two values according to this ordering. If the * values compare as 0, the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default * implementations of the other {@code max} overloads, so overriding it will * affect their behavior. * * @param a value to compare, returned if greater than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(@Nullable E a, @Nullable E b) { return (compare(a, b) >= 0) ? a : b; } /** * Returns the greatest of the specified values according to this ordering. If * there are multiple greatest values, the first of those is returned. * * @param a value to compare, returned if greater than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max( @Nullable E a, @Nullable E b, @Nullable E c, E... rest) { E maxSoFar = max(max(a, b), c); for (E r : rest) { maxSoFar = max(maxSoFar, r); } return maxSoFar; } /** * Returns the {@code k} least elements of the given iterable according to * this ordering, in order from least to greatest. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} least * elements in ascending order * @throws IllegalArgumentException if {@code k} is negative * @since 8.0 */ public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { if (iterable instanceof Collection) { Collection<E> collection = (Collection<E>) iterable; if (collection.size() <= 2L * k) { // In this case, just dumping the collection to an array and sorting is // faster than using the implementation for Iterator, which is // specialized for k much smaller than n. @SuppressWarnings("unchecked") // c only contains E's and doesn't escape E[] array = (E[]) collection.toArray(); Arrays.sort(array, this); if (array.length > k) { array = ObjectArrays.arraysCopyOf(array, k); } return Collections.unmodifiableList(Arrays.asList(array)); } } return leastOf(iterable.iterator(), k); } /** * Returns the {@code k} least elements from the given iterator according to * this ordering, in order from least to greatest. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} least * elements in ascending order * @throws IllegalArgumentException if {@code k} is negative * @since 14.0 */ public <E extends T> List<E> leastOf(Iterator<E> elements, int k) { checkNotNull(elements); checkNonnegative(k, "k"); if (k == 0 || !elements.hasNext()) { return ImmutableList.of(); } else if (k >= Integer.MAX_VALUE / 2) { // k is really large; just do a straightforward sorted-copy-and-sublist ArrayList<E> list = Lists.newArrayList(elements); Collections.sort(list, this); if (list.size() > k) { list.subList(k, list.size()).clear(); } list.trimToSize(); return Collections.unmodifiableList(list); } /* * Our goal is an O(n) algorithm using only one pass and O(k) additional * memory. * * We use the following algorithm: maintain a buffer of size 2*k. Every time * the buffer gets full, find the median and partition around it, keeping * only the lowest k elements. This requires n/k find-median-and-partition * steps, each of which take O(k) time with a traditional quickselect. * * After sorting the output, the whole algorithm is O(n + k log k). It * degrades gracefully for worst-case input (descending order), performs * competitively or wins outright for randomly ordered input, and doesn't * require the whole collection to fit into memory. */ int bufferCap = k * 2; @SuppressWarnings("unchecked") // we'll only put E's in E[] buffer = (E[]) new Object[bufferCap]; E threshold = elements.next(); buffer[0] = threshold; int bufferSize = 1; // threshold is the kth smallest element seen so far. Once bufferSize >= k, // anything larger than threshold can be ignored immediately. while (bufferSize < k && elements.hasNext()) { E e = elements.next(); buffer[bufferSize++] = e; threshold = max(threshold, e); } while (elements.hasNext()) { E e = elements.next(); if (compare(e, threshold) >= 0) { continue; } buffer[bufferSize++] = e; if (bufferSize == bufferCap) { // We apply the quickselect algorithm to partition about the median, // and then ignore the last k elements. int left = 0; int right = bufferCap - 1; int minThresholdPosition = 0; // The leftmost position at which the greatest of the k lower elements // -- the new value of threshold -- might be found. while (left < right) { int pivotIndex = (left + right + 1) >>> 1; int pivotNewIndex = partition(buffer, left, right, pivotIndex); if (pivotNewIndex > k) { right = pivotNewIndex - 1; } else if (pivotNewIndex < k) { left = Math.max(pivotNewIndex, left + 1); minThresholdPosition = pivotNewIndex; } else { break; } } bufferSize = k; threshold = buffer[minThresholdPosition]; for (int i = minThresholdPosition + 1; i < bufferSize; i++) { threshold = max(threshold, buffer[i]); } } } Arrays.sort(buffer, 0, bufferSize, this); bufferSize = Math.min(bufferSize, k); return Collections.unmodifiableList( Arrays.asList(ObjectArrays.arraysCopyOf(buffer, bufferSize))); // We can't use ImmutableList; we have to be null-friendly! } private <E extends T> int partition( E[] values, int left, int right, int pivotIndex) { E pivotValue = values[pivotIndex]; values[pivotIndex] = values[right]; values[right] = pivotValue; int storeIndex = left; for (int i = left; i < right; i++) { if (compare(values[i], pivotValue) < 0) { ObjectArrays.swap(values, storeIndex, i); storeIndex++; } } ObjectArrays.swap(values, right, storeIndex); return storeIndex; } /** * Returns the {@code k} greatest elements of the given iterable according to * this ordering, in order from greatest to least. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} greatest * elements in <i>descending order</i> * @throws IllegalArgumentException if {@code k} is negative * @since 8.0 */ public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) { // TODO(kevinb): see if delegation is hurting performance noticeably // TODO(kevinb): if we change this implementation, add full unit tests. return reverse().leastOf(iterable, k); } /** * Returns the {@code k} greatest elements from the given iterator according to * this ordering, in order from greatest to least. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} greatest * elements in <i>descending order</i> * @throws IllegalArgumentException if {@code k} is negative * @since 14.0 */ public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) { return reverse().leastOf(iterator, k); } /** * Returns a <b>mutable</b> list containing {@code elements} sorted by this * ordering; use this only when the resulting list may need further * modification, or may contain {@code null}. The input is not modified. The * returned list is serializable and has random access. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard * elements that are duplicates according to the comparator. The sort * performed is <i>stable</i>, meaning that such elements will appear in the * returned list in the same order they appeared in {@code elements}. * * <p><b>Performance note:</b> According to our * benchmarking * on Open JDK 7, {@link #immutableSortedCopy} generally performs better (in * both time and space) than this method, and this method in turn generally * performs better than copying the list and calling {@link * Collections#sort(List)}. */ public <E extends T> List<E> sortedCopy(Iterable<E> elements) { @SuppressWarnings("unchecked") // does not escape, and contains only E's E[] array = (E[]) Iterables.toArray(elements); Arrays.sort(array, this); return Lists.newArrayList(Arrays.asList(array)); } /** * Returns an <b>immutable</b> list containing {@code elements} sorted by this * ordering. The input is not modified. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard * elements that are duplicates according to the comparator. The sort * performed is <i>stable</i>, meaning that such elements will appear in the * returned list in the same order they appeared in {@code elements}. * * <p><b>Performance note:</b> According to our * benchmarking * on Open JDK 7, this method is the most efficient way to make a sorted copy * of a collection. * * @throws NullPointerException if any of {@code elements} (or {@code * elements} itself) is null * @since 3.0 */ public <E extends T> ImmutableList<E> immutableSortedCopy( Iterable<E> elements) { @SuppressWarnings("unchecked") // we'll only ever have E's in here E[] array = (E[]) Iterables.toArray(elements); for (E e : array) { checkNotNull(e); } Arrays.sort(array, this); return ImmutableList.asImmutableList(array); } /** * Returns {@code true} if each element in {@code iterable} after the first is * greater than or equal to the element that preceded it, according to this * ordering. Note that this is always true when the iterable has fewer than * two elements. */ public boolean isOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) > 0) { return false; } prev = next; } } return true; } /** * Returns {@code true} if each element in {@code iterable} after the first is * <i>strictly</i> greater than the element that preceded it, according to * this ordering. Note that this is always true when the iterable has fewer * than two elements. */ public boolean isStrictlyOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) >= 0) { return false; } prev = next; } } return true; } /** * {@link Collections#binarySearch(List, Object, Comparator) Searches} * {@code sortedList} for {@code key} using the binary search algorithm. The * list must be sorted using this ordering. * * @param sortedList the list to be searched * @param key the key to be searched for */ public int binarySearch(List<? extends T> sortedList, @Nullable T key) { return Collections.binarySearch(sortedList, key, this); } /** * Exception thrown by a {@link Ordering#explicit(List)} or {@link * Ordering#explicit(Object, Object[])} comparator when comparing a value * outside the set of values it can compare. Extending {@link * ClassCastException} may seem odd, but it is required. */ // TODO(kevinb): make this public, document it right @VisibleForTesting static class IncomparableValueException extends ClassCastException { final Object value; IncomparableValueException(Object value) { super("Cannot compare value: " + value); this.value = value; } private static final long serialVersionUID = 0; } // Never make these public static final int LEFT_IS_GREATER = 1; static final int RIGHT_IS_GREATER = -1; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Ordering.java
Java
asf20
34,842
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import java.util.Map; import javax.annotation.Nullable; /** * A mapping from disjoint nonempty ranges to non-null values. Queries look up the value * associated with the range (if any) that contains a specified key. * * <p>In contrast to {@link RangeSet}, no "coalescing" is done of {@linkplain * Range#isConnected(Range) connected} ranges, even if they are mapped to the same value. * * @author Louis Wasserman * @since 14.0 */ @Beta public interface RangeMap<K extends Comparable, V> { /** * Returns the value associated with the specified key, or {@code null} if there is no * such value. * * <p>Specifically, if any range in this range map contains the specified key, the value * associated with that range is returned. */ @Nullable V get(K key); /** * Returns the range containing this key and its associated value, if such a range is present * in the range map, or {@code null} otherwise. */ @Nullable Map.Entry<Range<K>, V> getEntry(K key); /** * Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the ranges * in this {@code RangeMap}. * * @throws NoSuchElementException if this range map is empty */ Range<K> span(); /** * Maps a range to a specified value (optional operation). * * <p>Specifically, after a call to {@code put(range, value)}, if * {@link Range#contains(Comparable) range.contains(k)}, then {@link #get(Comparable) get(k)} * will return {@code value}. * * <p>If {@code range} {@linkplain Range#isEmpty() is empty}, then this is a no-op. */ void put(Range<K> range, V value); /** * Puts all the associations from {@code rangeMap} into this range map (optional operation). */ void putAll(RangeMap<K, V> rangeMap); /** * Removes all associations from this range map (optional operation). */ void clear(); /** * Removes all associations from this range map in the specified range (optional operation). * * <p>If {@code !range.contains(k)}, {@link #get(Comparable) get(k)} will return the same result * before and after a call to {@code remove(range)}. If {@code range.contains(k)}, then * after a call to {@code remove(range)}, {@code get(k)} will return {@code null}. */ void remove(Range<K> range); /** * Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. * Modifications to this range map are guaranteed to read through to the returned {@code Map}. * * <p>It is guaranteed that no empty ranges will be in the returned {@code Map}. */ Map<Range<K>, V> asMapOfRanges(); /** * Returns a view of the part of this range map that intersects with {@code range}. * * <p>For example, if {@code rangeMap} had the entries * {@code [1, 5] => "foo", (6, 8) => "bar", (10, \u2025) => "baz"} * then {@code rangeMap.subRangeMap(Range.open(3, 12))} would return a range map * with the entries {@code (3, 5) => "foo", (6, 8) => "bar", (10, 12) => "baz"}. * * <p>The returned range map supports all optional operations that this range map supports, * except for {@code asMapOfRanges().iterator().remove()}. * * <p>The returned range map will throw an {@link IllegalArgumentException} on an attempt to * insert a range not {@linkplain Range#encloses(Range) enclosed} by {@code range}. */ RangeMap<K, V> subRangeMap(Range<K> range); /** * Returns {@code true} if {@code obj} is another {@code RangeMap} that has an equivalent * {@link #asMapOfRanges()}. */ @Override boolean equals(@Nullable Object o); /** * Returns {@code asMapOfRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range map. */ @Override String toString(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RangeMap.java
Java
asf20
4,474
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import java.util.ListIterator; /** * An iterator that transforms a backing list iterator; for internal use. This * avoids the object overhead of constructing a {@link Function} for internal * methods. * * @author Louis Wasserman */ @GwtCompatible abstract class TransformedListIterator<F, T> extends TransformedIterator<F, T> implements ListIterator<T> { TransformedListIterator(ListIterator<? extends F> backingIterator) { super(backingIterator); } private ListIterator<? extends F> backingIterator() { return Iterators.cast(backingIterator); } @Override public final boolean hasPrevious() { return backingIterator().hasPrevious(); } @Override public final T previous() { return transform(backingIterator().previous()); } @Override public final int nextIndex() { return backingIterator().nextIndex(); } @Override public final int previousIndex() { return backingIterator().previousIndex(); } @Override public void set(T element) { throw new UnsupportedOperationException(); } @Override public void add(T element) { throw new UnsupportedOperationException(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/TransformedListIterator.java
Java
asf20
1,888
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Map.Entry; import javax.annotation.Nullable; /** * {@code values()} implementation for {@link ImmutableMap}. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) final class ImmutableMapValues<K, V> extends ImmutableCollection<V> { private final ImmutableMap<K, V> map; ImmutableMapValues(ImmutableMap<K, V> map) { this.map = map; } @Override public int size() { return map.size(); } @Override public UnmodifiableIterator<V> iterator() { return Maps.valueIterator(map.entrySet().iterator()); } @Override public boolean contains(@Nullable Object object) { return object != null && Iterators.contains(iterator(), 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; } }; } @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm<V>(map); } @GwtIncompatible("serialization") private static class SerializedForm<V> implements Serializable { final ImmutableMap<?, V> map; SerializedForm(ImmutableMap<?, V> map) { this.map = map; } Object readResolve() { return map.values(); } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableMapValues.java
Java
asf20
2,401
/* * 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 iterator which forwards all its method calls to another iterator. * Subclasses should override one or more methods to modify the behavior of the * backing iterator as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingIterator<T> extends ForwardingObject implements Iterator<T> { /** Constructor for use by subclasses. */ protected ForwardingIterator() {} @Override protected abstract Iterator<T> delegate(); @Override public boolean hasNext() { return delegate().hasNext(); } @Override public T next() { return delegate().next(); } @Override public void remove() { delegate().remove(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingIterator.java
Java
asf20
1,555
/* * 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 java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.Collection; import java.util.Map; /** * Provides static methods for serializing collection classes. * * <p>This class assists the implementation of collection classes. Do not use * this class to serialize collections that are defined elsewhere. * * @author Jared Levy */ final class Serialization { private Serialization() {} /** * Reads a count corresponding to a serialized map, multiset, or multimap. It * returns the size of a map serialized by {@link * #writeMap(Map, ObjectOutputStream)}, the number of distinct elements in a * multiset serialized by {@link * #writeMultiset(Multiset, ObjectOutputStream)}, or the number of distinct * keys in a multimap serialized by {@link * #writeMultimap(Multimap, ObjectOutputStream)}. * * <p>The returned count may be used to construct an empty collection of the * appropriate capacity before calling any of the {@code populate} methods. */ static int readCount(ObjectInputStream stream) throws IOException { return stream.readInt(); } /** * Stores the contents of a map in an output stream, as part of serialization. * It does not support concurrent maps whose content may change while the * method is running. * * <p>The serialized output consists of the number of entries, first key, * first value, second key, second value, and so on. */ static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream) throws IOException { stream.writeInt(map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } /** * Populates a map by reading an input stream, as part of deserialization. * See {@link #writeMap} for the data format. */ static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream) throws IOException, ClassNotFoundException { int size = stream.readInt(); populateMap(map, stream, size); } /** * Populates a map by reading an input stream, as part of deserialization. * See {@link #writeMap} for the data format. The size is determined by a * prior call to {@link #readCount}. */ static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream, int size) throws IOException, ClassNotFoundException { for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") // reading data stored by writeMap K key = (K) stream.readObject(); @SuppressWarnings("unchecked") // reading data stored by writeMap V value = (V) stream.readObject(); map.put(key, value); } } /** * Stores the contents of a multiset in an output stream, as part of * serialization. It does not support concurrent multisets whose content may * change while the method is running. * * <p>The serialized output consists of the number of distinct elements, the * first element, its count, the second element, its count, and so on. */ static <E> void writeMultiset( Multiset<E> multiset, ObjectOutputStream stream) throws IOException { int entryCount = multiset.entrySet().size(); stream.writeInt(entryCount); for (Multiset.Entry<E> entry : multiset.entrySet()) { stream.writeObject(entry.getElement()); stream.writeInt(entry.getCount()); } } /** * Populates a multiset by reading an input stream, as part of * deserialization. See {@link #writeMultiset} for the data format. */ static <E> void populateMultiset( Multiset<E> multiset, ObjectInputStream stream) throws IOException, ClassNotFoundException { int distinctElements = stream.readInt(); populateMultiset(multiset, stream, distinctElements); } /** * Populates a multiset by reading an input stream, as part of * deserialization. See {@link #writeMultiset} for the data format. The number * of distinct elements is determined by a prior call to {@link #readCount}. */ static <E> void populateMultiset( Multiset<E> multiset, ObjectInputStream stream, int distinctElements) throws IOException, ClassNotFoundException { for (int i = 0; i < distinctElements; i++) { @SuppressWarnings("unchecked") // reading data stored by writeMultiset E element = (E) stream.readObject(); int count = stream.readInt(); multiset.add(element, count); } } /** * Stores the contents of a multimap in an output stream, as part of * serialization. It does not support concurrent multimaps whose content may * change while the method is running. The {@link Multimap#asMap} view * determines the ordering in which data is written to the stream. * * <p>The serialized output consists of the number of distinct keys, and then * for each distinct key: the key, the number of values for that key, and the * key's values. */ static <K, V> void writeMultimap( Multimap<K, V> multimap, ObjectOutputStream stream) throws IOException { stream.writeInt(multimap.asMap().size()); for (Map.Entry<K, Collection<V>> entry : multimap.asMap().entrySet()) { stream.writeObject(entry.getKey()); stream.writeInt(entry.getValue().size()); for (V value : entry.getValue()) { stream.writeObject(value); } } } /** * Populates a multimap by reading an input stream, as part of * deserialization. See {@link #writeMultimap} for the data format. */ static <K, V> void populateMultimap( Multimap<K, V> multimap, ObjectInputStream stream) throws IOException, ClassNotFoundException { int distinctKeys = stream.readInt(); populateMultimap(multimap, stream, distinctKeys); } /** * Populates a multimap by reading an input stream, as part of * deserialization. See {@link #writeMultimap} for the data format. The number * of distinct keys is determined by a prior call to {@link #readCount}. */ static <K, V> void populateMultimap( Multimap<K, V> multimap, ObjectInputStream stream, int distinctKeys) throws IOException, ClassNotFoundException { for (int i = 0; i < distinctKeys; i++) { @SuppressWarnings("unchecked") // reading data stored by writeMultimap K key = (K) stream.readObject(); Collection<V> values = multimap.get(key); int valueCount = stream.readInt(); for (int j = 0; j < valueCount; j++) { @SuppressWarnings("unchecked") // reading data stored by writeMultimap V value = (V) stream.readObject(); values.add(value); } } } // Secret sauce for setting final fields; don't make it public. static <T> FieldSetter<T> getFieldSetter( final Class<T> clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); return new FieldSetter<T>(field); } catch (NoSuchFieldException e) { throw new AssertionError(e); // programmer error } } // Secret sauce for setting final fields; don't make it public. static final class FieldSetter<T> { private final Field field; private FieldSetter(Field field) { this.field = field; field.setAccessible(true); } void set(T instance, Object value) { try { field.set(instance, value); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); } } void set(T instance, int value) { try { field.set(instance, value); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Serialization.java
Java
asf20
8,338
/* * 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.io.Serializable; import java.util.Collection; import java.util.EnumSet; /** * Implementation of {@link ImmutableSet} backed by a non-empty {@link * java.util.EnumSet}. * * @author Jared Levy */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> { static <E extends Enum<E>> ImmutableSet<E> asImmutable(EnumSet<E> set) { switch (set.size()) { case 0: return ImmutableSet.of(); case 1: return ImmutableSet.of(Iterables.getOnlyElement(set)); default: return new ImmutableEnumSet<E>(set); } } /* * Notes on EnumSet and <E extends Enum<E>>: * * This class isn't an arbitrary ForwardingImmutableSet because we need to * know that calling {@code clone()} during deserialization will return an * object that no one else has a reference to, allowing us to guarantee * immutability. Hence, we support only {@link EnumSet}. */ private final transient EnumSet<E> delegate; private ImmutableEnumSet(EnumSet<E> delegate) { this.delegate = delegate; } @Override boolean isPartialView() { return false; } @Override public UnmodifiableIterator<E> iterator() { return Iterators.unmodifiableIterator(delegate.iterator()); } @Override public int size() { return delegate.size(); } @Override public boolean contains(Object object) { return delegate.contains(object); } @Override public boolean containsAll(Collection<?> collection) { return delegate.containsAll(collection); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean equals(Object object) { return object == this || delegate.equals(object); } private transient int hashCode; @Override public int hashCode() { int result = hashCode; return (result == 0) ? hashCode = delegate.hashCode() : result; } @Override public String toString() { return delegate.toString(); } // All callers of the constructor are restricted to <E extends Enum<E>>. @Override Object writeReplace() { return new EnumSerializedForm<E>(delegate); } /* * This class is used to serialize ImmutableEnumSet instances. */ private static class EnumSerializedForm<E extends Enum<E>> implements Serializable { final EnumSet<E> delegate; EnumSerializedForm(EnumSet<E> delegate) { this.delegate = delegate; } Object readResolve() { // EJ2 #76: Write readObject() methods defensively. return new ImmutableEnumSet<E>(delegate.clone()); } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableEnumSet.java
Java
asf20
3,431
/* * 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; /** * An immutable {@link BiMap} with reliable user-specified iteration order. Does * not permit null keys or values. An {@code ImmutableBiMap} and its inverse * have the same iteration ordering. * * <p>An instance of {@code ImmutableBiMap} contains its own data and will * <i>never</i> change. {@code ImmutableBiMap} is convenient for * {@code public static final} maps ("constant maps") and also lets you easily * make a "defensive copy" of a bimap provided to your class by a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this class are * guaranteed to be immutable. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> { /** * Returns the empty bimap. */ // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableBiMap<K, V> of() { return (ImmutableBiMap<K, V>) EmptyImmutableBiMap.INSTANCE; } /** * Returns an immutable bimap containing a single entry. */ public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { return new SingletonImmutableBiMap<K, V>(k1, v1); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * A builder for creating immutable bimap instances, especially {@code public * static final} bimaps ("constant bimaps"). Example: <pre> {@code * * static final ImmutableBiMap<String, Integer> WORD_TO_INT = * new ImmutableBiMap.Builder<String, Integer>() * .put("one", 1) * .put("two", 2) * .put("three", 3) * .build();}</pre> * * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods * are even more convenient. * * <p>Builder instances can be reused - it is safe to call {@link #build} * multiple times to build multiple bimaps in series. Each bimap is a superset * of the bimaps created before it. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableBiMap#builder}. */ public Builder() {} /** * Associates {@code key} with {@code value} in the built bimap. Duplicate * keys or values are not allowed, and will cause {@link #build} to fail. */ @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } /** * Associates all of the given map's keys and values in the built bimap. * Duplicate keys or values are not allowed, and will cause {@link #build} * to fail. * * @throws NullPointerException if any key or value in {@code map} is null */ @Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { super.putAll(map); return this; } /** * Returns a newly-created immutable bimap. * * @throws IllegalArgumentException if duplicate keys or values were added */ @Override public ImmutableBiMap<K, V> build() { switch (size) { case 0: return of(); case 1: return of(entries[0].getKey(), entries[0].getValue()); default: return new RegularImmutableBiMap<K, V>(size, entries); } } } /** * Returns an immutable bimap containing the same entries as {@code map}. If * {@code map} somehow contains entries with duplicate keys (for example, if * it is a {@code SortedMap} whose comparator is not <i>consistent with * equals</i>), the results of this method are undefined. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws IllegalArgumentException if two keys have the same value * @throws NullPointerException if any key or value in {@code map} is null */ public static <K, V> ImmutableBiMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if (map instanceof ImmutableBiMap) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; // TODO(user): if we need to make a copy of a BiMap because the // forward map is a view, don't make a copy of the non-view delegate map if (!bimap.isPartialView()) { return bimap; } } Entry<?, ?>[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); switch (entries.length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // safe covariant cast in this context Entry<K, V> entry = (Entry<K, V>) entries[0]; return of(entry.getKey(), entry.getValue()); default: return new RegularImmutableBiMap<K, V>(entries); } } private static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0]; ImmutableBiMap() {} /** * {@inheritDoc} * * <p>The inverse of an {@code ImmutableBiMap} is another * {@code ImmutableBiMap}. */ @Override public abstract ImmutableBiMap<V, K> inverse(); /** * Returns an immutable set of the values in this map. The values are in the * same order as the parameters used to build this map. */ @Override public ImmutableSet<V> values() { return inverse().keySet(); } /** * Guaranteed to throw an exception and leave the bimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); } /** * Serialized type for all ImmutableBiMap instances. It captures the logical * contents and they are reconstructed using public factory methods. This * ensures that the implementation types remain as implementation details. * * Since the bimap is immutable, ImmutableBiMap doesn't require special logic * for keeping the bimap and its inverse in sync during serialization, the way * AbstractBiMap does. */ private static class SerializedForm extends ImmutableMap.SerializedForm { SerializedForm(ImmutableBiMap<?, ?> bimap) { super(bimap); } @Override Object readResolve() { Builder<Object, Object> builder = new Builder<Object, Object>(); return createMap(builder); } private static final long serialVersionUID = 0; } @Override Object writeReplace() { return new SerializedForm(this); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableBiMap.java
Java
asf20
9,362
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Predicate; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedSet; import javax.annotation.Nullable; /** * A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some * {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not * possible to <i>iterate</i> over these contained values. To do so, pass this range instance and * an appropriate {@link DiscreteDomain} to {@link ContiguousSet#create}. * * <h3>Types of ranges</h3> * * <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated * <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the * endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each * side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket * ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means * it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all * <i>x</i> such that <i>statement</i>.") * * <blockquote><table> * <tr><td><b>Notation</b> <td><b>Definition</b> <td><b>Factory method</b> * <tr><td>{@code (a..b)} <td>{@code {x | a < x < b}} <td>{@link Range#open open} * <tr><td>{@code [a..b]} <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed} * <tr><td>{@code (a..b]} <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed} * <tr><td>{@code [a..b)} <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen} * <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}} <td>{@link Range#greaterThan greaterThan} * <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}} <td>{@link Range#atLeast atLeast} * <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}} <td>{@link Range#lessThan lessThan} * <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}} <td>{@link Range#atMost atMost} * <tr><td>{@code (-∞..+∞)}<td>{@code {x}} <td>{@link Range#all all} * </table></blockquote> * * <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints * may be equal only if at least one of the bounds is closed: * * <ul> * <li>{@code [a..a]} : a singleton range * <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid * <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown * </ul> * * <h3>Warnings</h3> * * <ul> * <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do * not</b> allow the endpoint instances to mutate after the range is created! * <li>Your value type's comparison method should be {@linkplain Comparable consistent with equals} * if at all possible. Otherwise, be aware that concepts used throughout this documentation such * as "equal", "same", "unique" and so on actually refer to whether {@link Comparable#compareTo * compareTo} returns zero, not whether {@link Object#equals equals} returns {@code true}. * <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause * undefined horrible things to happen in {@code Range}. For now, the Range API does not prevent * its use, because this would also rule out all ungenerified (pre-JDK1.5) data types. <b>This * may change in the future.</b> * </ul> * * <h3>Other notes</h3> * * <ul> * <li>Instances of this type are obtained using the static factory methods in this class. * <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them must * also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C}, {@code * r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a {@code * Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from 1 to * 100." * <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link * #contains}. * <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property * <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}. * Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having * property <i>P</i>. See, for example, the definition of {@link #intersection intersection}. * </ul> * * <h3>Further reading</h3> * * <p>See the Guava User Guide article on * <a href="http://code.google.com/p/guava-libraries/wiki/RangesExplained">{@code Range}</a>. * * @author Kevin Bourrillion * @author Gregory Kick * @since 10.0 */ @GwtCompatible @SuppressWarnings("rawtypes") public final class Range<C extends Comparable> implements Predicate<C>, Serializable { private static final Function<Range, Cut> LOWER_BOUND_FN = new Function<Range, Cut>() { @Override public Cut apply(Range range) { return range.lowerBound; } }; @SuppressWarnings("unchecked") static <C extends Comparable<?>> Function<Range<C>, Cut<C>> lowerBoundFn() { return (Function) LOWER_BOUND_FN; } private static final Function<Range, Cut> UPPER_BOUND_FN = new Function<Range, Cut>() { @Override public Cut apply(Range range) { return range.upperBound; } }; @SuppressWarnings("unchecked") static <C extends Comparable<?>> Function<Range<C>, Cut<C>> upperBoundFn() { return (Function) UPPER_BOUND_FN; } static final Ordering<Range<?>> RANGE_LEX_ORDERING = new Ordering<Range<?>>() { @Override public int compare(Range<?> left, Range<?> right) { return ComparisonChain.start() .compare(left.lowerBound, right.lowerBound) .compare(left.upperBound, right.upperBound) .result(); } }; static <C extends Comparable<?>> Range<C> create( Cut<C> lowerBound, Cut<C> upperBound) { return new Range<C>(lowerBound, upperBound); } /** * Returns a range that contains all values strictly greater than {@code * lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than <i>or * equal to</i> {@code upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> open(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) { return create(Cut.belowValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closedOpen( C lower, C upper) { return create(Cut.belowValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values strictly greater than {@code * lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> openClosed( C lower, C upper) { return create(Cut.aboveValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains any value from {@code lower} to {@code * upper}, where each endpoint may be either inclusive (closed) or exclusive * (open). * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> range( C lower, BoundType lowerType, C upper, BoundType upperType) { checkNotNull(lowerType); checkNotNull(upperType); Cut<C> lowerBound = (lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower); Cut<C> upperBound = (upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper); return create(lowerBound, upperBound); } /** * Returns a range that contains all values strictly less than {@code * endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) { return create(Cut.<C>belowAll(), Cut.belowValue(endpoint)); } /** * Returns a range that contains all values less than or equal to * {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atMost(C endpoint) { return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint)); } /** * Returns a range with no lower bound up to the given endpoint, which may be * either inclusive (closed) or exclusive (open). * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> upTo( C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return lessThan(endpoint); case CLOSED: return atMost(endpoint); default: throw new AssertionError(); } } /** * Returns a range that contains all values strictly greater than {@code * endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) { return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range that contains all values greater than or equal to * {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) { return create(Cut.belowValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range from the given endpoint, which may be either inclusive * (closed) or exclusive (open), with no upper bound. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> downTo( C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return greaterThan(endpoint); case CLOSED: return atLeast(endpoint); default: throw new AssertionError(); } } private static final Range<Comparable> ALL = new Range<Comparable>(Cut.belowAll(), Cut.aboveAll()); /** * Returns a range that contains every value of type {@code C}. * * @since 14.0 */ @SuppressWarnings("unchecked") public static <C extends Comparable<?>> Range<C> all() { return (Range) ALL; } /** * Returns a range that {@linkplain Range#contains(Comparable) contains} only * the given value. The returned range is {@linkplain BoundType#CLOSED closed} * on both ends. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> singleton(C value) { return closed(value, value); } /** * Returns the minimal range that * {@linkplain Range#contains(Comparable) contains} all of the given values. * The returned range is {@linkplain BoundType#CLOSED closed} on both ends. * * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> * @throws NoSuchElementException if {@code values} is empty * @throws NullPointerException if any of {@code values} is null * @since 14.0 */ public static <C extends Comparable<?>> Range<C> encloseAll( Iterable<C> values) { checkNotNull(values); if (values instanceof ContiguousSet) { return ((ContiguousSet<C>) values).range(); } Iterator<C> valueIterator = values.iterator(); C min = checkNotNull(valueIterator.next()); C max = min; while (valueIterator.hasNext()) { C value = checkNotNull(valueIterator.next()); min = Ordering.natural().min(min, value); max = Ordering.natural().max(max, value); } return closed(min, max); } final Cut<C> lowerBound; final Cut<C> upperBound; private Range(Cut<C> lowerBound, Cut<C> upperBound) { if (lowerBound.compareTo(upperBound) > 0 || lowerBound == Cut.<C>aboveAll() || upperBound == Cut.<C>belowAll()) { throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound)); } this.lowerBound = checkNotNull(lowerBound); this.upperBound = checkNotNull(upperBound); } /** * Returns {@code true} if this range has a lower endpoint. */ public boolean hasLowerBound() { return lowerBound != Cut.belowAll(); } /** * Returns the lower endpoint of this range. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public C lowerEndpoint() { return lowerBound.endpoint(); } /** * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes * its lower endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public BoundType lowerBoundType() { return lowerBound.typeAsLowerBound(); } /** * Returns {@code true} if this range has an upper endpoint. */ public boolean hasUpperBound() { return upperBound != Cut.aboveAll(); } /** * Returns the upper endpoint of this range. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public C upperEndpoint() { return upperBound.endpoint(); } /** * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes * its upper endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public BoundType upperBoundType() { return upperBound.typeAsUpperBound(); } /** * Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does * not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and * can't be constructed at all.) * * <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b> * considered empty, even though they contain no actual values. In these cases, it may be * helpful to preprocess ranges with {@link #canonical(DiscreteDomain)}. */ public boolean isEmpty() { return lowerBound.equals(upperBound); } /** * Returns {@code true} if {@code value} is within the bounds of this range. For example, on the * range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)} * returns {@code false}. */ public boolean contains(C value) { checkNotNull(value); // let this throw CCE if there is some trickery going on return lowerBound.isLessThan(value) && !upperBound.isLessThan(value); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #contains} * instead. */ @Deprecated @Override public boolean apply(C input) { return contains(input); } /** * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in * this range. */ public boolean containsAll(Iterable<? extends C> values) { if (Iterables.isEmpty(values)) { return true; } // this optimizes testing equality of two range-backed sets if (values instanceof SortedSet) { SortedSet<? extends C> set = cast(values); Comparator<?> comparator = set.comparator(); if (Ordering.natural().equals(comparator) || comparator == null) { return contains(set.first()) && contains(set.last()); } } for (C value : values) { if (!contains(value)) { return false; } } return true; } /** * Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this * range. Examples: * * <ul> * <li>{@code [3..6]} encloses {@code [4..5]} * <li>{@code (3..6)} encloses {@code (3..6)} * <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty) * <li>{@code (3..6]} does not enclose {@code [3..6]} * <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value * contained by the latter range) * <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value * contained by the latter range) * </ul> * * <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies * {@code a.contains(v)}, but as the last two examples illustrate, the converse is not always * true. * * <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a * <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range * according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure * also implies {@linkplain #isConnected connectedness}. */ public boolean encloses(Range<C> other) { return lowerBound.compareTo(other.lowerBound) <= 0 && upperBound.compareTo(other.upperBound) >= 0; } /** * Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses * enclosed} by both this range and {@code other}. * * <p>For example, * <ul> * <li>{@code [2, 4)} and {@code [5, 7)} are not connected * <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)} * <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range * {@code [4, 4)} * </ul> * * <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and * {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this * method returns {@code true}. * * <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain * Equivalence equivalence relation} as it is not transitive. * * <p>Note that certain discrete ranges are not considered connected, even though there are no * elements "between them." For example, {@code [3, 5]} is not considered connected to {@code * [6, 10]}. In these cases, it may be desirable for both input ranges to be preprocessed with * {@link #canonical(DiscreteDomain)} before testing for connectedness. */ public boolean isConnected(Range<C> other) { return lowerBound.compareTo(other.upperBound) <= 0 && other.lowerBound.compareTo(upperBound) <= 0; } /** * Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code * connectedRange}, if such a range exists. * * <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The * resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)} * yields the empty range {@code [5..5)}. * * <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected * connected}. * * <p>The intersection operation is commutative, associative and idempotent, and its identity * element is {@link Range#all}). * * @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false} */ public Range<C> intersection(Range<C> connectedRange) { int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound); int upperCmp = upperBound.compareTo(connectedRange.upperBound); if (lowerCmp >= 0 && upperCmp <= 0) { return this; } else if (lowerCmp <= 0 && upperCmp >= 0) { return connectedRange; } else { Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound; Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound; return create(newLower, newUpper); } } /** * Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code * other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}. * * <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can * also be called their <i>union</i>. If they are not, note that the span might contain values * that are not contained in either input range. * * <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative * and idempotent. Unlike it, it is always well-defined for any two input ranges. */ public Range<C> span(Range<C> other) { int lowerCmp = lowerBound.compareTo(other.lowerBound); int upperCmp = upperBound.compareTo(other.upperBound); if (lowerCmp <= 0 && upperCmp >= 0) { return this; } else if (lowerCmp >= 0 && upperCmp <= 0) { return other; } else { Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound; Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound; return create(newLower, newUpper); } } /** * Returns the canonical form of this range in the given domain. The canonical form has the * following properties: * * <ul> * <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in other * words, {@code ContiguousSet.create(a.canonical(domain), domain).equals( * ContiguousSet.create(a, domain))} * <li>uniqueness: unless {@code a.isEmpty()}, * {@code ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))} implies * {@code a.canonical(domain).equals(b.canonical(domain))} * <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))} * </ul> * * <p>Furthermore, this method guarantees that the range returned will be one of the following * canonical forms: * * <ul> * <li>[start..end) * <li>[start..+∞) * <li>(-∞..end) (only if type {@code C} is unbounded below) * <li>(-∞..+∞) (only if type {@code C} is unbounded below) * </ul> */ public Range<C> canonical(DiscreteDomain<C> domain) { checkNotNull(domain); Cut<C> lower = lowerBound.canonical(domain); Cut<C> upper = upperBound.canonical(domain); return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper); } /** * Returns {@code true} if {@code object} is a range having the same endpoints and bound types as * this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b> * equal to one another, despite the fact that they each contain precisely the same set of values. * Similarly, empty ranges are not equal unless they have exactly the same representation, so * {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal. */ @Override public boolean equals(@Nullable Object object) { if (object instanceof Range) { Range<?> other = (Range<?>) object; return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound); } return false; } /** Returns a hash code for this range. */ @Override public int hashCode() { return lowerBound.hashCode() * 31 + upperBound.hashCode(); } /** * Returns a string representation of this range, such as {@code "[3..5)"} (other examples are * listed in the class documentation). */ @Override public String toString() { return toString(lowerBound, upperBound); } private static String toString(Cut<?> lowerBound, Cut<?> upperBound) { StringBuilder sb = new StringBuilder(16); lowerBound.describeAsLowerBound(sb); sb.append('\u2025'); upperBound.describeAsUpperBound(sb); return sb.toString(); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ private static <T> SortedSet<T> cast(Iterable<T> iterable) { return (SortedSet<T>) iterable; } Object readResolve() { if (this.equals(ALL)) { return all(); } else { return this; } } @SuppressWarnings("unchecked") // this method may throw CCE static int compareOrThrow(Comparable left, Comparable right) { return left.compareTo(right); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Range.java
Java
asf20
25,530
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; /** * An iterator that transforms a backing iterator; for internal use. This avoids * the object overhead of constructing a {@link Function} for internal methods. * * @author Louis Wasserman */ @GwtCompatible abstract class TransformedIterator<F, T> implements Iterator<T> { final Iterator<? extends F> backingIterator; TransformedIterator(Iterator<? extends F> backingIterator) { this.backingIterator = checkNotNull(backingIterator); } abstract T transform(F from); @Override public final boolean hasNext() { return backingIterator.hasNext(); } @Override public final T next() { return transform(backingIterator.next()); } @Override public final void remove() { backingIterator.remove(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/TransformedIterator.java
Java
asf20
1,530
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.Collection; import java.util.concurrent.BlockingDeque; import java.util.concurrent.TimeUnit; /** * A {@link BlockingDeque} which forwards all its method calls to another {@code BlockingDeque}. * Subclasses should override one or more methods to modify the behavior of the backing deque as * desired per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingBlockingDeque} forward * <b>indiscriminately</b> to the methods of the delegate. For example, overriding {@link #add} * alone <b>will not</b> change the behaviour of {@link #offer} which can lead to unexpected * behaviour. In this case, you should override {@code offer} as well, either providing your own * implementation, or delegating to the provided {@code standardOffer} method. * * <p> * The {@code standard} methods are not guaranteed to be thread-safe, even when all of the methods * that they depend on are thread-safe. * * @author Emily Soldal * @since 14.0 */ public abstract class ForwardingBlockingDeque<E> extends ForwardingDeque<E> implements BlockingDeque<E> { /** Constructor for use by subclasses. */ protected ForwardingBlockingDeque() {} @Override protected abstract BlockingDeque<E> delegate(); @Override public int remainingCapacity() { return delegate().remainingCapacity(); } @Override public void putFirst(E e) throws InterruptedException { delegate().putFirst(e); } @Override public void putLast(E e) throws InterruptedException { delegate().putLast(e); } @Override public boolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException { return delegate().offerFirst(e, timeout, unit); } @Override public boolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException { return delegate().offerLast(e, timeout, unit); } @Override public E takeFirst() throws InterruptedException { return delegate().takeFirst(); } @Override public E takeLast() throws InterruptedException { return delegate().takeLast(); } @Override public E pollFirst(long timeout, TimeUnit unit) throws InterruptedException { return delegate().pollFirst(timeout, unit); } @Override public E pollLast(long timeout, TimeUnit unit) throws InterruptedException { return delegate().pollLast(timeout, unit); } @Override public void put(E e) throws InterruptedException { delegate().put(e); } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { return delegate().offer(e, timeout, unit); } @Override public E take() throws InterruptedException { return delegate().take(); } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { return delegate().poll(timeout, unit); } @Override public int drainTo(Collection<? super E> c) { return delegate().drainTo(c); } @Override public int drainTo(Collection<? super E> c, int maxElements) { return delegate().drainTo(c, maxElements); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingBlockingDeque.java
Java
asf20
3,762
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import javax.annotation.Nullable; /** * A skeletal implementation of {@code RangeSet}. * * @author Louis Wasserman */ abstract class AbstractRangeSet<C extends Comparable> implements RangeSet<C> { AbstractRangeSet() {} @Override public boolean contains(C value) { return rangeContaining(value) != null; } @Override public abstract Range<C> rangeContaining(C value); @Override public boolean isEmpty() { return asRanges().isEmpty(); } @Override public void add(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void remove(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void clear() { remove(Range.<C>all()); } @Override public boolean enclosesAll(RangeSet<C> other) { for (Range<C> range : other.asRanges()) { if (!encloses(range)) { return false; } } return true; } @Override public void addAll(RangeSet<C> other) { for (Range<C> range : other.asRanges()) { add(range); } } @Override public void removeAll(RangeSet<C> other) { for (Range<C> range : other.asRanges()) { remove(range); } } @Override public abstract boolean encloses(Range<C> otherRange); @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } else if (obj instanceof RangeSet) { RangeSet<?> other = (RangeSet<?>) obj; return this.asRanges().equals(other.asRanges()); } return false; } @Override public final int hashCode() { return asRanges().hashCode(); } @Override public final String toString() { return asRanges().toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractRangeSet.java
Java
asf20
2,348
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An empty contiguous set. * * @author Gregory Kick */ @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> { EmptyContiguousSet(DiscreteDomain<C> domain) { super(domain); } @Override public C first() { throw new NoSuchElementException(); } @Override public C last() { throw new NoSuchElementException(); } @Override public int size() { return 0; } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { return this; } @Override public Range<C> range() { throw new NoSuchElementException(); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { throw new NoSuchElementException(); } @Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return this; } @Override ContiguousSet<C> subSetImpl( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { return this; } @Override ContiguousSet<C> tailSetImpl(C fromElement, boolean fromInclusive) { return this; } @GwtIncompatible("not used by GWT emulation") @Override int indexOf(Object target) { return -1; } @Override public UnmodifiableIterator<C> iterator() { return Iterators.emptyIterator(); } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<C> descendingIterator() { return Iterators.emptyIterator(); } @Override boolean isPartialView() { return false; } @Override public boolean isEmpty() { return true; } @Override public ImmutableList<C> asList() { return ImmutableList.of(); } @Override public String toString() { return "[]"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { Set<?> that = (Set<?>) object; return that.isEmpty(); } return false; } @Override public int hashCode() { return 0; } @GwtIncompatible("serialization") private static final class SerializedForm<C extends Comparable> implements Serializable { private final DiscreteDomain<C> domain; private SerializedForm(DiscreteDomain<C> domain) { this.domain = domain; } private Object readResolve() { return new EmptyContiguousSet<C>(domain); } private static final long serialVersionUID = 0; } @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm<C>(domain); } @GwtIncompatible("NavigableSet") ImmutableSortedSet<C> createDescendingSet() { return new EmptyImmutableSortedSet<C>(Ordering.natural().reverse()); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EmptyContiguousSet.java
Java
asf20
3,596
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Serialization.FieldSetter; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * A multiset that supports concurrent modifications and that provides atomic versions of most * {@code Multiset} operations (exceptions where noted). Null elements are not supported. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Cliff L. Biffle * @author mike nonemacher * @since 2.0 (imported from Google Collections Library) */ public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable { /* * The ConcurrentHashMultiset's atomic operations are implemented primarily in terms of * AtomicInteger's atomic operations, with some help from ConcurrentMap's atomic operations on * creation and removal (including automatic removal of zeroes). If the modification of an * AtomicInteger results in zero, we compareAndSet the value to zero; if that succeeds, we remove * the entry from the Map. If another operation sees a zero in the map, it knows that the entry is * about to be removed, so this operation may remove it (often by replacing it with a new * AtomicInteger). */ /** The number of occurrences of each element. */ private final transient ConcurrentMap<E, AtomicInteger> countMap; // This constant allows the deserialization code to set a final field. This holder class // makes sure it is not initialized unless an instance is deserialized. private static class FieldSettersHolder { static final FieldSetter<ConcurrentHashMultiset> COUNT_MAP_FIELD_SETTER = Serialization.getFieldSetter(ConcurrentHashMultiset.class, "countMap"); } /** * Creates a new, empty {@code ConcurrentHashMultiset} using the default * initial capacity, load factor, and concurrency settings. */ public static <E> ConcurrentHashMultiset<E> create() { // TODO(schmoe): provide a way to use this class with other (possibly arbitrary) // ConcurrentMap implementors. One possibility is to extract most of this class into // an AbstractConcurrentMapMultiset. return new ConcurrentHashMultiset<E>(new ConcurrentHashMap<E, AtomicInteger>()); } /** * Creates a new {@code ConcurrentHashMultiset} containing the specified elements, using * the default initial capacity, load factor, and concurrency settings. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> ConcurrentHashMultiset<E> create(Iterable<? extends E> elements) { ConcurrentHashMultiset<E> multiset = ConcurrentHashMultiset.create(); Iterables.addAll(multiset, elements); return multiset; } /** * Creates a new, empty {@code ConcurrentHashMultiset} using {@code mapMaker} * to construct the internal backing map. * * <p>If this {@link MapMaker} is configured to use entry eviction of any kind, this eviction * applies to all occurrences of a given element as a single unit. However, most updates to the * multiset do not count as map updates at all, since we're usually just mutating the value * stored in the map, so {@link MapMaker#expireAfterAccess} makes sense (evict the entry that * was queried or updated longest ago), but {@link MapMaker#expireAfterWrite} doesn't, because * the eviction time is measured from when we saw the first occurrence of the object. * * <p>The returned multiset is serializable but any serialization caveats * given in {@code MapMaker} apply. * * <p>Finally, soft/weak values can be used but are not very useful: the values are created * internally and not exposed externally, so no one else will have a strong reference to the * values. Weak keys on the other hand can be useful in some scenarios. * * @since 15.0 (source compatible (accepting the since removed {@code GenericMapMaker} class) * since 7.0) */ @Beta public static <E> ConcurrentHashMultiset<E> create(MapMaker mapMaker) { return new ConcurrentHashMultiset<E>(mapMaker.<E, AtomicInteger>makeMap()); } /** * Creates an instance using {@code countMap} to store elements and their counts. * * <p>This instance will assume ownership of {@code countMap}, and other code * should not maintain references to the map or modify it in any way. * * @param countMap backing map for storing the elements in the multiset and * their counts. It must be empty. * @throws IllegalArgumentException if {@code countMap} is not empty */ @VisibleForTesting ConcurrentHashMultiset(ConcurrentMap<E, AtomicInteger> countMap) { checkArgument(countMap.isEmpty()); this.countMap = countMap; } // Query Operations /** * Returns the number of occurrences of {@code element} in this multiset. * * @param element the element to look for * @return the nonnegative number of occurrences of the element */ @Override public int count(@Nullable Object element) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); return (existingCounter == null) ? 0 : existingCounter.get(); } /** * {@inheritDoc} * * <p>If the data in the multiset is modified by any other threads during this method, * it is undefined which (if any) of these modifications will be reflected in the result. */ @Override public int size() { long sum = 0L; for (AtomicInteger value : countMap.values()) { sum += value.get(); } return Ints.saturatedCast(sum); } /* * Note: the superclass toArray() methods assume that size() gives a correct * answer, which ours does not. */ @Override public Object[] toArray() { return snapshot().toArray(); } @Override public <T> T[] toArray(T[] array) { return snapshot().toArray(array); } /* * We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but * either of these would recurse back to us again! */ private List<E> snapshot() { List<E> list = Lists.newArrayListWithExpectedSize(size()); for (Multiset.Entry<E> entry : entrySet()) { E element = entry.getElement(); for (int i = entry.getCount(); i > 0; i--) { list.add(element); } } return list; } // Modification Operations /** * Adds a number of occurrences of the specified element to this multiset. * * @param element the element to add * @param occurrences the number of occurrences to add * @return the previous count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative, or if * the resulting amount would exceed {@link Integer#MAX_VALUE} */ @Override public int add(E element, int occurrences) { checkNotNull(element); if (occurrences == 0) { return count(element); } checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences); while (true) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through to operate against the existing AtomicInteger } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { try { int newValue = IntMath.checkedAdd(oldValue, occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { // newValue can't == 0, so no need to check & remove return oldValue; } } catch (ArithmeticException overflow) { throw new IllegalArgumentException("Overflow adding " + occurrences + " occurrences to a count of " + oldValue); } } else { // In the case of a concurrent remove, we might observe a zero value, which means another // thread is about to remove (element, existingCounter) from the map. Rather than wait, // we can just do that work here. AtomicInteger newCounter = new AtomicInteger(occurrences); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } break; } } // If we're still here, there was a race, so just try again. } } /** * Removes a number of occurrences of the specified element from this multiset. If the multiset * contains fewer than this number of occurrences to begin with, all occurrences will be removed. * * @param element the element whose occurrences should be removed * @param occurrences the number of occurrences of the element to remove * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative */ /* * TODO(cpovirk): remove and removeExactly currently accept null inputs only * if occurrences == 0. This satisfies both NullPointerTester and * CollectionRemoveTester.testRemove_nullAllowed, but it's not clear that it's * a good policy, especially because, in order for the test to pass, the * parameter must be misleadingly annotated as @Nullable. I suspect that * we'll want to remove @Nullable, add an eager checkNotNull, and loosen up * testRemove_nullAllowed. */ @Override public int remove(@Nullable Object element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences); AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { return 0; } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { int newValue = Math.max(0, oldValue - occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { if (newValue == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return oldValue; } } else { return 0; } } } /** * Removes exactly the specified number of occurrences of {@code element}, or makes no * change if this is not possible. * * <p>This method, in contrast to {@link #remove(Object, int)}, has no effect when the * element count is smaller than {@code occurrences}. * * @param element the element to remove * @param occurrences the number of occurrences of {@code element} to remove * @return {@code true} if the removal was possible (including if {@code occurrences} is zero) */ public boolean removeExactly(@Nullable Object element, int occurrences) { if (occurrences == 0) { return true; } checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences); AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { return false; } while (true) { int oldValue = existingCounter.get(); if (oldValue < occurrences) { return false; } int newValue = oldValue - occurrences; if (existingCounter.compareAndSet(oldValue, newValue)) { if (newValue == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return true; } } } /** * Adds or removes occurrences of {@code element} such that the {@link #count} of the * element becomes {@code count}. * * @return the count of {@code element} in the multiset before this call * @throws IllegalArgumentException if {@code count} is negative */ @Override public int setCount(E element, int count) { checkNotNull(element); checkNonnegative(count, "count"); while (true) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { if (count == 0) { return 0; } else { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through } } while (true) { int oldValue = existingCounter.get(); if (oldValue == 0) { if (count == 0) { return 0; } else { AtomicInteger newCounter = new AtomicInteger(count); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } } break; } else { if (existingCounter.compareAndSet(oldValue, count)) { if (count == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return oldValue; } } } } } /** * Sets the number of occurrences of {@code element} to {@code newCount}, but only if * the count is currently {@code expectedOldCount}. If {@code element} does not appear * in the multiset exactly {@code expectedOldCount} times, no changes will be made. * * @return {@code true} if the change was successful. This usually indicates * that the multiset has been modified, but not always: in the case that * {@code expectedOldCount == newCount}, the method will return {@code true} if * the condition was met. * @throws IllegalArgumentException if {@code expectedOldCount} or {@code newCount} is negative */ @Override public boolean setCount(E element, int expectedOldCount, int newCount) { checkNotNull(element); checkNonnegative(expectedOldCount, "oldCount"); checkNonnegative(newCount, "newCount"); AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { if (expectedOldCount != 0) { return false; } else if (newCount == 0) { return true; } else { // if our write lost the race, it must have lost to a nonzero value, so we can stop return countMap.putIfAbsent(element, new AtomicInteger(newCount)) == null; } } int oldValue = existingCounter.get(); if (oldValue == expectedOldCount) { if (oldValue == 0) { if (newCount == 0) { // Just observed a 0; try to remove the entry to clean up the map countMap.remove(element, existingCounter); return true; } else { AtomicInteger newCounter = new AtomicInteger(newCount); return (countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter); } } else { if (existingCounter.compareAndSet(oldValue, newCount)) { if (newCount == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return true; } } } return false; } // Views @Override Set<E> createElementSet() { final Set<E> delegate = countMap.keySet(); return new ForwardingSet<E>() { @Override protected Set<E> delegate() { return delegate; } @Override public boolean contains(@Nullable Object object) { return object != null && Collections2.safeContains(delegate, object); } @Override public boolean containsAll(Collection<?> collection) { return standardContainsAll(collection); } @Override public boolean remove(Object object) { return object != null && Collections2.safeRemove(delegate, object); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } }; } private transient EntrySet entrySet; @Override public Set<Multiset.Entry<E>> entrySet() { EntrySet result = entrySet; if (result == null) { entrySet = result = new EntrySet(); } return result; } @Override int distinctElements() { return countMap.size(); } @Override public boolean isEmpty() { return countMap.isEmpty(); } @Override Iterator<Entry<E>> entryIterator() { // AbstractIterator makes this fairly clean, but it doesn't support remove(). To support // remove(), we create an AbstractIterator, and then use ForwardingIterator to delegate to it. final Iterator<Entry<E>> readOnlyIterator = new AbstractIterator<Entry<E>>() { private Iterator<Map.Entry<E, AtomicInteger>> mapEntries = countMap.entrySet().iterator(); @Override protected Entry<E> computeNext() { while (true) { if (!mapEntries.hasNext()) { return endOfData(); } Map.Entry<E, AtomicInteger> mapEntry = mapEntries.next(); int count = mapEntry.getValue().get(); if (count != 0) { return Multisets.immutableEntry(mapEntry.getKey(), count); } } } }; return new ForwardingIterator<Entry<E>>() { private Entry<E> last; @Override protected Iterator<Entry<E>> delegate() { return readOnlyIterator; } @Override public Entry<E> next() { last = super.next(); return last; } @Override public void remove() { checkRemove(last != null); ConcurrentHashMultiset.this.setCount(last.getElement(), 0); last = null; } }; } @Override public void clear() { countMap.clear(); } private class EntrySet extends AbstractMultiset<E>.EntrySet { @Override ConcurrentHashMultiset<E> multiset() { return ConcurrentHashMultiset.this; } /* * Note: the superclass toArray() methods assume that size() gives a correct * answer, which ours does not. */ @Override public Object[] toArray() { return snapshot().toArray(); } @Override public <T> T[] toArray(T[] array) { return snapshot().toArray(array); } private List<Multiset.Entry<E>> snapshot() { List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size()); // Not Iterables.addAll(list, this), because that'll forward right back here. Iterators.addAll(list, iterator()); return list; } } /** * @serialData the ConcurrentMap of elements and their counts. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(countMap); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject ConcurrentMap<E, Integer> deserializedCountMap = (ConcurrentMap<E, Integer>) stream.readObject(); FieldSettersHolder.COUNT_MAP_FIELD_SETTER.set(this, deserializedCountMap); } private static final long serialVersionUID = 1; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ConcurrentHashMultiset.java
Java
asf20
21,393
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import 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) { checkNonnegative(occurrences, "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) { checkNonnegative(occurrences, "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) { checkNonnegative(count, "count"); 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) { checkNonnegative(newCount, "newCount"); checkNonnegative(oldCount, "oldCount"); 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() { checkRemove(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() { checkRemove(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. */ /** * @serialData the comparator, the number of distinct elements, the first element, its count, the * second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(elementSet().comparator()); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject Comparator<? super E> comparator = (Comparator<? super E>) stream.readObject(); Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator); Serialization.getFieldSetter(TreeMultiset.class, "range").set( this, GeneralRange.all(comparator)); Serialization.getFieldSetter(TreeMultiset.class, "rootReference").set( this, new Reference<AvlNode<E>>()); AvlNode<E> header = new AvlNode<E>(null, 1); Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header); successor(header, header); Serialization.populateMultiset(this, stream); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 1; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/TreeMultiset.java
Java
asf20
30,242
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * A {@code RegularImmutableTable} optimized for dense data. */ @GwtCompatible @Immutable final class DenseImmutableTable<R, C, V> extends RegularImmutableTable<R, C, V> { private final ImmutableMap<R, Integer> rowKeyToIndex; private final ImmutableMap<C, Integer> columnKeyToIndex; private final ImmutableMap<R, Map<C, V>> rowMap; private final ImmutableMap<C, Map<R, V>> columnMap; private final int[] rowCounts; private final int[] columnCounts; private final V[][] values; private final int[] iterationOrderRow; private final int[] iterationOrderColumn; private static <E> ImmutableMap<E, Integer> makeIndex(ImmutableSet<E> set) { ImmutableMap.Builder<E, Integer> indexBuilder = ImmutableMap.builder(); int i = 0; for (E key : set) { indexBuilder.put(key, i); i++; } return indexBuilder.build(); } DenseImmutableTable(ImmutableList<Cell<R, C, V>> cellList, ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) { @SuppressWarnings("unchecked") V[][] array = (V[][]) new Object[rowSpace.size()][columnSpace.size()]; this.values = array; this.rowKeyToIndex = makeIndex(rowSpace); this.columnKeyToIndex = makeIndex(columnSpace); rowCounts = new int[rowKeyToIndex.size()]; columnCounts = new int[columnKeyToIndex.size()]; int[] iterationOrderRow = new int[cellList.size()]; int[] iterationOrderColumn = new int[cellList.size()]; for (int i = 0; i < cellList.size(); i++) { Cell<R, C, V> cell = cellList.get(i); R rowKey = cell.getRowKey(); C columnKey = cell.getColumnKey(); int rowIndex = rowKeyToIndex.get(rowKey); int columnIndex = columnKeyToIndex.get(columnKey); V existingValue = values[rowIndex][columnIndex]; checkArgument(existingValue == null, "duplicate key: (%s, %s)", rowKey, columnKey); values[rowIndex][columnIndex] = cell.getValue(); rowCounts[rowIndex]++; columnCounts[columnIndex]++; iterationOrderRow[i] = rowIndex; iterationOrderColumn[i] = columnIndex; } this.iterationOrderRow = iterationOrderRow; this.iterationOrderColumn = iterationOrderColumn; this.rowMap = new RowMap(); this.columnMap = new ColumnMap(); } /** * An immutable map implementation backed by an indexed nullable array. */ private abstract static class ImmutableArrayMap<K, V> extends ImmutableMap<K, V> { private final int size; ImmutableArrayMap(int size) { this.size = size; } abstract ImmutableMap<K, Integer> keyToIndex(); // True if getValue never returns null. private boolean isFull() { return size == keyToIndex().size(); } K getKey(int index) { return keyToIndex().keySet().asList().get(index); } @Nullable abstract V getValue(int keyIndex); @Override ImmutableSet<K> createKeySet() { return isFull() ? keyToIndex().keySet() : super.createKeySet(); } @Override public int size() { return size; } @Override public V get(@Nullable Object key) { Integer keyIndex = keyToIndex().get(key); return (keyIndex == null) ? null : getValue(keyIndex); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new ImmutableMapEntrySet<K, V>() { @Override ImmutableMap<K, V> map() { return ImmutableArrayMap.this; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return new AbstractIterator<Entry<K, V>>() { private int index = -1; private final int maxIndex = keyToIndex().size(); @Override protected Entry<K, V> computeNext() { for (index++; index < maxIndex; index++) { V value = getValue(index); if (value != null) { return Maps.immutableEntry(getKey(index), value); } } return endOfData(); } }; } }; } } private final class Row extends ImmutableArrayMap<C, V> { private final int rowIndex; Row(int rowIndex) { super(rowCounts[rowIndex]); this.rowIndex = rowIndex; } @Override ImmutableMap<C, Integer> keyToIndex() { return columnKeyToIndex; } @Override V getValue(int keyIndex) { return values[rowIndex][keyIndex]; } @Override boolean isPartialView() { return true; } } private final class Column extends ImmutableArrayMap<R, V> { private final int columnIndex; Column(int columnIndex) { super(columnCounts[columnIndex]); this.columnIndex = columnIndex; } @Override ImmutableMap<R, Integer> keyToIndex() { return rowKeyToIndex; } @Override V getValue(int keyIndex) { return values[keyIndex][columnIndex]; } @Override boolean isPartialView() { return true; } } private final class RowMap extends ImmutableArrayMap<R, Map<C, V>> { private RowMap() { super(rowCounts.length); } @Override ImmutableMap<R, Integer> keyToIndex() { return rowKeyToIndex; } @Override Map<C, V> getValue(int keyIndex) { return new Row(keyIndex); } @Override boolean isPartialView() { return false; } } private final class ColumnMap extends ImmutableArrayMap<C, Map<R, V>> { private ColumnMap() { super(columnCounts.length); } @Override ImmutableMap<C, Integer> keyToIndex() { return columnKeyToIndex; } @Override Map<R, V> getValue(int keyIndex) { return new Column(keyIndex); } @Override boolean isPartialView() { return false; } } @Override public ImmutableMap<C, Map<R, V>> columnMap() { return columnMap; } @Override public ImmutableMap<R, Map<C, V>> rowMap() { return rowMap; } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return ((rowIndex == null) || (columnIndex == null)) ? null : values[rowIndex][columnIndex]; } @Override public int size() { return iterationOrderRow.length; } @Override Cell<R, C, V> getCell(int index) { int rowIndex = iterationOrderRow[index]; int columnIndex = iterationOrderColumn[index]; R rowKey = rowKeySet().asList().get(rowIndex); C columnKey = columnKeySet().asList().get(columnIndex); V value = values[rowIndex][columnIndex]; return cellOf(rowKey, columnKey, value); } @Override V getValue(int index) { return values[iterationOrderRow[index]][iterationOrderColumn[index]]; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/DenseImmutableTable.java
Java
asf20
7,654
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.annotation.Nullable; /** * An implementation of {@link ImmutableTable} holding an arbitrary number of * cells. * * @author Gregory Kick */ @GwtCompatible abstract class RegularImmutableTable<R, C, V> extends ImmutableTable<R, C, V> { RegularImmutableTable() {} abstract Cell<R, C, V> getCell(int iterationIndex); @Override final ImmutableSet<Cell<R, C, V>> createCellSet() { return isEmpty() ? ImmutableSet.<Cell<R, C, V>>of() : new CellSet(); } private final class CellSet extends ImmutableSet<Cell<R, C, V>> { @Override public int size() { return RegularImmutableTable.this.size(); } @Override public UnmodifiableIterator<Cell<R, C, V>> iterator() { return asList().iterator(); } @Override ImmutableList<Cell<R, C, V>> createAsList() { return new ImmutableAsList<Cell<R, C, V>>() { @Override public Cell<R, C, V> get(int index) { return getCell(index); } @Override ImmutableCollection<Cell<R, C, V>> delegateCollection() { return CellSet.this; } }; } @Override public boolean contains(@Nullable Object object) { if (object instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) object; Object value = get(cell.getRowKey(), cell.getColumnKey()); return value != null && value.equals(cell.getValue()); } return false; } @Override boolean isPartialView() { return false; } } abstract V getValue(int iterationIndex); @Override final ImmutableCollection<V> createValues() { return isEmpty() ? ImmutableList.<V>of() : new Values(); } private final class Values extends ImmutableList<V> { @Override public int size() { return RegularImmutableTable.this.size(); } @Override public V get(int index) { return getValue(index); } @Override boolean isPartialView() { return true; } } static <R, C, V> RegularImmutableTable<R, C, V> forCells( List<Cell<R, C, V>> cells, @Nullable final Comparator<? super R> rowComparator, @Nullable final Comparator<? super C> columnComparator) { checkNotNull(cells); if (rowComparator != null || columnComparator != null) { /* * This sorting logic leads to a cellSet() ordering that may not be expected and that isn't * documented in the Javadoc. If a row Comparator is provided, cellSet() iterates across the * columns in the first row, the columns in the second row, etc. If a column Comparator is * provided but a row Comparator isn't, cellSet() iterates across the rows in the first * column, the rows in the second column, etc. */ Comparator<Cell<R, C, V>> comparator = new Comparator<Cell<R, C, V>>() { @Override public int compare(Cell<R, C, V> cell1, Cell<R, C, V> cell2) { int rowCompare = (rowComparator == null) ? 0 : rowComparator.compare(cell1.getRowKey(), cell2.getRowKey()); if (rowCompare != 0) { return rowCompare; } return (columnComparator == null) ? 0 : columnComparator.compare(cell1.getColumnKey(), cell2.getColumnKey()); } }; Collections.sort(cells, comparator); } return forCellsInternal(cells, rowComparator, columnComparator); } static <R, C, V> RegularImmutableTable<R, C, V> forCells( Iterable<Cell<R, C, V>> cells) { return forCellsInternal(cells, null, null); } /** * A factory that chooses the most space-efficient representation of the * table. */ private static final <R, C, V> RegularImmutableTable<R, C, V> forCellsInternal(Iterable<Cell<R, C, V>> cells, @Nullable Comparator<? super R> rowComparator, @Nullable Comparator<? super C> columnComparator) { ImmutableSet.Builder<R> rowSpaceBuilder = ImmutableSet.builder(); ImmutableSet.Builder<C> columnSpaceBuilder = ImmutableSet.builder(); ImmutableList<Cell<R, C, V>> cellList = ImmutableList.copyOf(cells); for (Cell<R, C, V> cell : cellList) { rowSpaceBuilder.add(cell.getRowKey()); columnSpaceBuilder.add(cell.getColumnKey()); } ImmutableSet<R> rowSpace = rowSpaceBuilder.build(); if (rowComparator != null) { List<R> rowList = Lists.newArrayList(rowSpace); Collections.sort(rowList, rowComparator); rowSpace = ImmutableSet.copyOf(rowList); } ImmutableSet<C> columnSpace = columnSpaceBuilder.build(); if (columnComparator != null) { List<C> columnList = Lists.newArrayList(columnSpace); Collections.sort(columnList, columnComparator); columnSpace = ImmutableSet.copyOf(columnList); } // use a dense table if more than half of the cells have values // TODO(gak): tune this condition based on empirical evidence return (cellList.size() > (((long) rowSpace.size() * columnSpace.size()) / 2)) ? new DenseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace) : new SparseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularImmutableTable.java
Java
asf20
5,983
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Preconditions; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableList} with one or more elements. * * @author Kevin Bourrillion */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization class RegularImmutableList<E> extends ImmutableList<E> { private final transient int offset; private final transient int size; private final transient Object[] array; RegularImmutableList(Object[] array, int offset, int size) { this.offset = offset; this.size = size; this.array = array; } RegularImmutableList(Object[] array) { this(array, 0, array.length); } @Override public int size() { return size; } @Override boolean isPartialView() { return size != array.length; } @Override int copyIntoArray(Object[] dst, int dstOff) { System.arraycopy(array, offset, dst, dstOff, size); return dstOff + size; } // The fake cast to E is safe because the creation methods only allow E's @Override @SuppressWarnings("unchecked") public E get(int index) { Preconditions.checkElementIndex(index, size); return (E) array[index + offset]; } @Override public int indexOf(@Nullable Object object) { if (object == null) { return -1; } for (int i = 0; i < size; i++) { if (array[offset + i].equals(object)) { return i; } } return -1; } @Override public int lastIndexOf(@Nullable Object object) { if (object == null) { return -1; } for (int i = size - 1; i >= 0; i--) { if (array[offset + i].equals(object)) { return i; } } return -1; } @Override ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) { return new RegularImmutableList<E>( array, offset + fromIndex, toIndex - fromIndex); } @SuppressWarnings("unchecked") @Override public UnmodifiableListIterator<E> listIterator(int index) { // for performance // The fake cast to E is safe because the creation methods only allow E's return (UnmodifiableListIterator<E>) Iterators.forArray(array, offset, size, index); } // TODO(user): benchmark optimizations for equals() and see if they're worthwhile }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularImmutableList.java
Java
asf20
3,001
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Implementation of {@code Multimap} that uses an {@code ArrayList} to store * the values for a given key. A {@link HashMap} associates each key with an * {@link ArrayList} of values. * * <p>When iterating through the collections supplied by this class, the * ordering of values for a given key agrees with the order in which the values * were added. * * <p>This multimap allows duplicate key-value pairs. After adding a new * key-value pair equal to an existing key-value pair, the {@code * ArrayListMultimap} will contain entries for both the new value and the old * value. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link * #replaceValues} all implement {@link java.util.RandomAccess}. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedListMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> { // Default from ArrayList private static final int DEFAULT_VALUES_PER_KEY = 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)); checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); this.expectedValuesPerKey = expectedValuesPerKey; } private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size(), (multimap instanceof ArrayListMultimap) ? ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey : DEFAULT_VALUES_PER_KEY); putAll(multimap); } /** * Creates a new, empty {@code ArrayList} to hold the collection of values for * an arbitrary key. */ @Override List<V> createCollection() { return new ArrayList<V>(expectedValuesPerKey); } /** * Reduces the memory used by this {@code ArrayListMultimap}, if feasible. */ public void trimToSize() { for (Collection<V> collection : backingMap().values()) { ArrayList<V> arrayList = (ArrayList<V>) collection; arrayList.trimToSize(); } } /** * @serialData expectedValuesPerKey, number of distinct keys, and then for * each distinct key: the key, number of values for that key, and the * key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(expectedValuesPerKey); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectOutputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey = stream.readInt(); int distinctKeys = Serialization.readCount(stream); Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys); setMap(map); Serialization.populateMultimap(this, stream, distinctKeys); } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ArrayListMultimap.java
Java
asf20
6,123
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * Bimap with no mappings. * * @author Jared Levy */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization final class EmptyImmutableBiMap extends ImmutableBiMap<Object, Object> { static final EmptyImmutableBiMap INSTANCE = new EmptyImmutableBiMap(); private EmptyImmutableBiMap() {} @Override public ImmutableBiMap<Object, Object> inverse() { return this; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public Object get(@Nullable Object key) { return null; } @Override public ImmutableSet<Entry<Object, Object>> entrySet() { return ImmutableSet.of(); } @Override ImmutableSet<Entry<Object, Object>> createEntrySet() { throw new AssertionError("should never be called"); } @Override public ImmutableSetMultimap<Object, Object> asMultimap() { return ImmutableSetMultimap.of(); } @Override public ImmutableSet<Object> keySet() { return ImmutableSet.of(); } @Override boolean isPartialView() { return false; } Object readResolve() { return INSTANCE; // preserve singleton property } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EmptyImmutableBiMap.java
Java
asf20
1,948
/* * 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 com.google.common.annotations.GwtIncompatible; import java.util.Collections; import java.util.NoSuchElementException; import java.util.Set; /** * 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), DiscreteDomain.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); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ContiguousSet<C> headSet(C toElement, boolean inclusive) { return headSetImpl(checkNotNull(toElement), inclusive); } @Override public ContiguousSet<C> subSet(C fromElement, C toElement) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator().compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, true, toElement, false); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ContiguousSet<C> subSet(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator().compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); } @Override public ContiguousSet<C> tailSet(C fromElement) { return tailSetImpl(checkNotNull(fromElement), true); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) { return tailSetImpl(checkNotNull(fromElement), inclusive); } /* * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation. */ /*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive); /*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive); /*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive); /** * Returns the set of values that are contained in both this set and the other. * * <p>This method should always be used instead of * {@link Sets#intersection} for {@link ContiguousSet} instances. */ public abstract ContiguousSet<C> intersection(ContiguousSet<C> other); /** * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values * contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}. * * @throws NoSuchElementException if this set is empty */ public abstract Range<C> range(); /** * Returns the minimal range with the given boundary types for which all values in this set are * {@linkplain Range#contains(Comparable) contained} within the range. * * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN} * is requested for a domain minimum or maximum. For example, if {@code set} was created from the * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return * {@code [1..∞)}. * * @throws NoSuchElementException if this set is empty */ public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType); /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */ @Override public String toString() { return range().toString(); } /** * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code * ContiguousSet}. * * @throws UnsupportedOperationException always * @deprecated Use {@link #create}. */ @Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() { throw new UnsupportedOperationException(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ContiguousSet.java
Java
asf20
6,677
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.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. @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { synchronized (mutex) { stream.defaultWriteObject(); } } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; } private static <E> Collection<E> collection( Collection<E> collection, @Nullable Object mutex) { return new SynchronizedCollection<E>(collection, mutex); } @VisibleForTesting static class SynchronizedCollection<E> extends SynchronizedObject implements Collection<E> { private SynchronizedCollection( Collection<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Collection<E> delegate() { return (Collection<E>) super.delegate(); } @Override public boolean add(E e) { synchronized (mutex) { return delegate().add(e); } } @Override public boolean addAll(Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(c); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean contains(Object o) { synchronized (mutex) { return delegate().contains(o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return delegate().containsAll(c); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Iterator<E> iterator() { return delegate().iterator(); // manually synchronized } @Override public boolean remove(Object o) { synchronized (mutex) { return delegate().remove(o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return delegate().removeAll(c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return delegate().retainAll(c); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Object[] toArray() { synchronized (mutex) { return delegate().toArray(); } } @Override public <T> T[] toArray(T[] a) { synchronized (mutex) { return delegate().toArray(a); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) { return new SynchronizedSet<E>(set, mutex); } static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { SynchronizedSet(Set<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Set<E> delegate() { return (Set<E>) super.delegate(); } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static <E> SortedSet<E> sortedSet( SortedSet<E> set, @Nullable Object mutex) { return new SynchronizedSortedSet<E>(set, mutex); } static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSet<E> delegate() { return (SortedSet<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return sortedSet(delegate().subSet(fromElement, toElement), mutex); } } @Override public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return sortedSet(delegate().headSet(toElement), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return sortedSet(delegate().tailSet(fromElement), mutex); } } @Override public E first() { synchronized (mutex) { return delegate().first(); } } @Override public E last() { synchronized (mutex) { return delegate().last(); } } private static final long serialVersionUID = 0; } private static <E> List<E> list(List<E> list, @Nullable Object mutex) { return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList<E>(list, mutex) : new SynchronizedList<E>(list, mutex); } private static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { SynchronizedList(List<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override List<E> delegate() { return (List<E>) super.delegate(); } @Override public void add(int index, E element) { synchronized (mutex) { delegate().add(index, element); } } @Override public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(index, c); } } @Override public E get(int index) { synchronized (mutex) { return delegate().get(index); } } @Override public int indexOf(Object o) { synchronized (mutex) { return delegate().indexOf(o); } } @Override public int lastIndexOf(Object o) { synchronized (mutex) { return delegate().lastIndexOf(o); } } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); // manually synchronized } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); // manually synchronized } @Override public E remove(int index) { synchronized (mutex) { return delegate().remove(index); } } @Override public E set(int index, E element) { synchronized (mutex) { return delegate().set(index, element); } } @Override public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return list(delegate().subList(fromIndex, toIndex), mutex); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) { super(list, mutex); } private static final long serialVersionUID = 0; } static <E> Multiset<E> multiset( Multiset<E> multiset, @Nullable Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<E>(multiset, mutex); } private static class SynchronizedMultiset<E> extends SynchronizedCollection<E> implements Multiset<E> { transient Set<E> elementSet; transient Set<Entry<E>> entrySet; SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Multiset<E> delegate() { return (Multiset<E>) super.delegate(); } @Override public int count(Object o) { synchronized (mutex) { return delegate().count(o); } } @Override public int add(E e, int n) { synchronized (mutex) { return delegate().add(e, n); } } @Override public int remove(Object o, int n) { synchronized (mutex) { return delegate().remove(o, n); } } @Override public int setCount(E element, int count) { synchronized (mutex) { return delegate().setCount(element, count); } } @Override public boolean setCount(E element, int oldCount, int newCount) { synchronized (mutex) { return delegate().setCount(element, oldCount, newCount); } } @Override public Set<E> elementSet() { synchronized (mutex) { if (elementSet == null) { elementSet = typePreservingSet(delegate().elementSet(), mutex); } return elementSet; } } @Override public Set<Entry<E>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = typePreservingSet(delegate().entrySet(), mutex); } return entrySet; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> Multimap<K, V> multimap( Multimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedMultimap || multimap instanceof ImmutableMultimap) { return multimap; } return new SynchronizedMultimap<K, V>(multimap, mutex); } private static class SynchronizedMultimap<K, V> extends SynchronizedObject implements Multimap<K, V> { transient Set<K> keySet; transient Collection<V> valuesCollection; transient Collection<Map.Entry<K, V>> entries; transient Map<K, Collection<V>> asMap; transient Multiset<K> keys; @SuppressWarnings("unchecked") @Override Multimap<K, V> delegate() { return (Multimap<K, V>) super.delegate(); } SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public boolean containsEntry(Object key, Object value) { synchronized (mutex) { return delegate().containsEntry(key, value); } } @Override public Collection<V> get(K key) { synchronized (mutex) { return typePreservingCollection(delegate().get(key), mutex); } } @Override public boolean put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public boolean putAll(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().putAll(key, values); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { synchronized (mutex) { return delegate().putAll(multimap); } } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public boolean remove(Object key, Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public Collection<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = typePreservingSet(delegate().keySet(), mutex); } return keySet; } } @Override public Collection<V> values() { synchronized (mutex) { if (valuesCollection == null) { valuesCollection = collection(delegate().values(), mutex); } return valuesCollection; } } @Override public Collection<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entries == null) { entries = typePreservingCollection(delegate().entries(), mutex); } return entries; } } @Override public Map<K, Collection<V>> asMap() { synchronized (mutex) { if (asMap == null) { asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex); } return asMap; } } @Override public Multiset<K> keys() { synchronized (mutex) { if (keys == null) { keys = multiset(delegate().keys(), mutex); } return keys; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> ListMultimap<K, V> listMultimap( ListMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedListMultimap || multimap instanceof ImmutableListMultimap) { return multimap; } return new SynchronizedListMultimap<K, V>(multimap, mutex); } private static class SynchronizedListMultimap<K, V> extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> { SynchronizedListMultimap( ListMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { synchronized (mutex) { return list(delegate().get(key), mutex); } } @Override public List<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } private static final long serialVersionUID = 0; } static <K, V> SetMultimap<K, V> setMultimap( SetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSetMultimap || multimap instanceof ImmutableSetMultimap) { return multimap; } return new SynchronizedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSetMultimap<K, V> extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> { transient Set<Map.Entry<K, V>> entrySet; SynchronizedSetMultimap( SetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { synchronized (mutex) { return set(delegate().get(key), mutex); } } @Override public Set<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Set<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entries(), mutex); } return entrySet; } } private static final long serialVersionUID = 0; } static <K, V> SortedSetMultimap<K, V> sortedSetMultimap( SortedSetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSortedSetMultimap) { return multimap; } return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSortedSetMultimap<K, V> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap( SortedSetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } private static final long serialVersionUID = 0; } private static <E> Collection<E> typePreservingCollection( Collection<E> collection, @Nullable Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E> Set<E> typePreservingSet( Set<E> set, @Nullable Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } private static class SynchronizedAsMapEntries<K, V> extends SynchronizedSet<Map.Entry<K, Collection<V>>> { SynchronizedAsMapEntries( Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { // Must be manually synchronized. final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator(); return new ForwardingIterator<Map.Entry<K, Collection<V>>>() { @Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() { return iterator; } @Override public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = 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; } @GwtIncompatible("NavigableSet") @VisibleForTesting static class SynchronizedNavigableSet<E> extends SynchronizedSortedSet<E> implements NavigableSet<E> { SynchronizedNavigableSet(NavigableSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override NavigableSet<E> delegate() { return (NavigableSet<E>) super.delegate(); } @Override public E ceiling(E e) { synchronized (mutex) { return delegate().ceiling(e); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); // manually synchronized } transient NavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { synchronized (mutex) { if (descendingSet == null) { NavigableSet<E> dS = Synchronized.navigableSet(delegate().descendingSet(), mutex); descendingSet = dS; return dS; } return descendingSet; } } @Override public E floor(E e) { synchronized (mutex) { return delegate().floor(e); } } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().headSet(toElement, inclusive), mutex); } } @Override public E higher(E e) { synchronized (mutex) { return delegate().higher(e); } } @Override public E lower(E e) { synchronized (mutex) { return delegate().lower(e); } } @Override public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().subSet( fromElement, fromInclusive, toElement, toInclusive), mutex); } } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().tailSet(fromElement, inclusive), mutex); } } @Override public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } private static final long serialVersionUID = 0; } @GwtIncompatible("NavigableSet") static <E> NavigableSet<E> navigableSet( NavigableSet<E> navigableSet, @Nullable Object mutex) { return new SynchronizedNavigableSet<E>(navigableSet, mutex); } @GwtIncompatible("NavigableSet") static <E> NavigableSet<E> navigableSet(NavigableSet<E> navigableSet) { return navigableSet(navigableSet, null); } @GwtIncompatible("NavigableMap") static <K, V> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap) { return navigableMap(navigableMap, null); } @GwtIncompatible("NavigableMap") static <K, V> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap, @Nullable Object mutex) { return new SynchronizedNavigableMap<K, V>(navigableMap, mutex); } @GwtIncompatible("NavigableMap") @VisibleForTesting static class SynchronizedNavigableMap<K, V> extends SynchronizedSortedMap<K, V> implements NavigableMap<K, V> { SynchronizedNavigableMap( NavigableMap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override NavigableMap<K, V> delegate() { return (NavigableMap<K, V>) super.delegate(); } @Override public Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); } } @Override public K ceilingKey(K key) { synchronized (mutex) { return delegate().ceilingKey(key); } } transient NavigableSet<K> descendingKeySet; @Override public NavigableSet<K> descendingKeySet() { synchronized (mutex) { if (descendingKeySet == null) { return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); } return descendingKeySet; } } transient NavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { synchronized (mutex) { if (descendingMap == null) { return descendingMap = navigableMap(delegate().descendingMap(), mutex); } return descendingMap; } } @Override public Entry<K, V> firstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().firstEntry(), mutex); } } @Override public Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); } } @Override public K floorKey(K key) { synchronized (mutex) { return delegate().floorKey(key); } } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return navigableMap( delegate().headMap(toKey, inclusive), mutex); } } @Override public Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); } } @Override public K higherKey(K key) { synchronized (mutex) { return delegate().higherKey(key); } } @Override public Entry<K, V> lastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lastEntry(), mutex); } } @Override public Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); } } @Override public K lowerKey(K key) { synchronized (mutex) { return delegate().lowerKey(key); } } @Override public Set<K> keySet() { return navigableKeySet(); } transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { synchronized (mutex) { if (navigableKeySet == null) { return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); } return navigableKeySet; } } @Override public Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); } } @Override public Entry<K, V> pollLastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); } } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return navigableMap( delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return navigableMap( delegate().tailMap(fromKey, inclusive), mutex); } } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } private static final long serialVersionUID = 0; } @GwtIncompatible("works but is needed only for NavigableMap") private static <K, V> Entry<K, V> nullableSynchronizedEntry( @Nullable Entry<K, V> entry, @Nullable Object mutex) { if (entry == null) { return null; } return new SynchronizedEntry<K, V>(entry, mutex); } @GwtIncompatible("works but is needed only for NavigableMap") private static class SynchronizedEntry<K, V> extends SynchronizedObject implements Entry<K, V> { SynchronizedEntry(Entry<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") // guaranteed by the constructor @Override Entry<K, V> delegate() { return (Entry<K, V>) super.delegate(); } @Override public boolean equals(Object obj) { synchronized (mutex) { return delegate().equals(obj); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public K getKey() { synchronized (mutex) { return delegate().getKey(); } } @Override public V getValue() { synchronized (mutex) { return delegate().getValue(); } } @Override public V setValue(V value) { synchronized (mutex) { return delegate().setValue(value); } } 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; } @GwtIncompatible("Deque") static <E> Deque<E> deque(Deque<E> deque, @Nullable Object mutex) { return new SynchronizedDeque<E>(deque, mutex); } @GwtIncompatible("Deque") private static final class SynchronizedDeque<E> extends SynchronizedQueue<E> implements Deque<E> { SynchronizedDeque(Deque<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Deque<E> delegate() { return (Deque<E>) super.delegate(); } @Override public void addFirst(E e) { synchronized (mutex) { delegate().addFirst(e); } } @Override public void addLast(E e) { synchronized (mutex) { delegate().addLast(e); } } @Override public boolean offerFirst(E e) { synchronized (mutex) { return delegate().offerFirst(e); } } @Override public boolean offerLast(E e) { synchronized (mutex) { return delegate().offerLast(e); } } @Override public E removeFirst() { synchronized (mutex) { return delegate().removeFirst(); } } @Override public E removeLast() { synchronized (mutex) { return delegate().removeLast(); } } @Override public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public E getFirst() { synchronized (mutex) { return delegate().getFirst(); } } @Override public E getLast() { synchronized (mutex) { return delegate().getLast(); } } @Override public E peekFirst() { synchronized (mutex) { return delegate().peekFirst(); } } @Override public E peekLast() { synchronized (mutex) { return delegate().peekLast(); } } @Override public boolean removeFirstOccurrence(Object o) { synchronized (mutex) { return delegate().removeFirstOccurrence(o); } } @Override public boolean removeLastOccurrence(Object o) { synchronized (mutex) { return delegate().removeLastOccurrence(o); } } @Override public void push(E e) { synchronized (mutex) { delegate().push(e); } } @Override public E pop() { synchronized (mutex) { return delegate().pop(); } } @Override public Iterator<E> descendingIterator() { synchronized (mutex) { return delegate().descendingIterator(); } } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Synchronized.java
Java
asf20
45,249
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.EnumMap; import java.util.Iterator; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableMap} backed by a non-empty {@link * java.util.EnumMap}. * * @author Louis Wasserman */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization final class ImmutableEnumMap<K extends Enum<K>, V> extends ImmutableMap<K, V> { static <K extends Enum<K>, V> ImmutableMap<K, V> asImmutable(EnumMap<K, V> map) { switch (map.size()) { case 0: return ImmutableMap.of(); case 1: { Entry<K, V> entry = Iterables.getOnlyElement(map.entrySet()); return ImmutableMap.of(entry.getKey(), entry.getValue()); } default: return new ImmutableEnumMap<K, V>(map); } } private transient final EnumMap<K, V> delegate; private ImmutableEnumMap(EnumMap<K, V> delegate) { this.delegate = delegate; checkArgument(!delegate.isEmpty()); } @Override ImmutableSet<K> createKeySet() { return new ImmutableSet<K>() { @Override public boolean contains(Object object) { return delegate.containsKey(object); } @Override public int size() { return ImmutableEnumMap.this.size(); } @Override public UnmodifiableIterator<K> iterator() { return Iterators.unmodifiableIterator(delegate.keySet().iterator()); } @Override boolean isPartialView() { return true; } }; } @Override public int size() { return delegate.size(); } @Override public boolean containsKey(@Nullable Object key) { return delegate.containsKey(key); } @Override public V get(Object key) { return delegate.get(key); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new ImmutableMapEntrySet<K, V>() { @Override ImmutableMap<K, V> map() { return ImmutableEnumMap.this; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return new UnmodifiableIterator<Entry<K, V>>() { private final Iterator<Entry<K, V>> backingIterator = delegate.entrySet().iterator(); @Override public boolean hasNext() { return backingIterator.hasNext(); } @Override public Entry<K, V> next() { Entry<K, V> entry = backingIterator.next(); return Maps.immutableEntry(entry.getKey(), entry.getValue()); } }; } }; } @Override boolean isPartialView() { return false; } // All callers of the constructor are restricted to <K extends Enum<K>>. @Override Object writeReplace() { return new EnumSerializedForm<K, V>(delegate); } /* * This class is used to serialize ImmutableEnumSet instances. */ private static class EnumSerializedForm<K extends Enum<K>, V> implements Serializable { final EnumMap<K, V> delegate; EnumSerializedForm(EnumMap<K, V> delegate) { this.delegate = delegate; } Object readResolve() { return new ImmutableEnumMap<K, V>(delegate); } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableEnumMap.java
Java
asf20
4,013
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * A {@code SetMultimap} whose set of values for a given key are kept sorted; * that is, they comprise a {@link SortedSet}. It cannot hold duplicate * key-value pairs; adding a key-value pair that's already in the multimap has * no effect. This interface does not specify the ordering of the multimap's * keys. See the {@link Multimap} documentation for information common to all * multimaps. * * <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods * each return a {@link SortedSet} of values, while {@link Multimap#entries()} * returns a {@link Set} of map entries. Though the method signature doesn't say * so explicitly, the map returned by {@link #asMap} has {@code SortedSet} * values. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface SortedSetMultimap<K, V> extends SetMultimap<K, V> { // Following Javadoc copied from Multimap. /** * Returns a collection view of all values associated with a key. If no * mappings in the multimap have the provided key, an empty collection is * returned. * * <p>Changes to the returned collection will update the underlying multimap, * and vice versa. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link java.util.Collection} specified in the {@link Multimap} interface. */ @Override SortedSet<V> get(@Nullable K key); /** * Removes all values associated with a given key. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link java.util.Collection} specified in the {@link Multimap} interface. */ @Override SortedSet<V> removeAll(@Nullable Object key); /** * Stores a collection of values with the same key, replacing any existing * values for that key. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link java.util.Collection} specified in the {@link Multimap} interface. * * <p>Any duplicates in {@code values} will be stored in the multimap once. */ @Override SortedSet<V> replaceValues(K key, Iterable<? extends V> values); /** * Returns a map view that associates each key with the corresponding values * in the multimap. Changes to the returned map, such as element removal, will * update the underlying multimap. The map does not support {@code setValue()} * on its entries, {@code put}, or {@code putAll}. * * <p>When passed a key that is present in the map, {@code * asMap().get(Object)} has the same behavior as {@link #get}, returning a * live collection. When passed a key that is not present, however, {@code * asMap().get(Object)} returns {@code null} instead of an empty collection. * * <p><b>Note:</b> The returned map's values are guaranteed to be of type * {@link SortedSet}. To obtain this map with the more specific generic type * {@code Map<K, SortedSet<V>>}, call * {@link Multimaps#asMap(SortedSetMultimap)} instead. */ @Override Map<K, Collection<V>> asMap(); /** * Returns the comparator that orders the multimap values, with {@code null} * indicating that natural ordering is used. */ Comparator<? super V> valueComparator(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/SortedSetMultimap.java
Java
asf20
4,491
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * A skeleton {@code Multimap} implementation, not necessarily in terms of a {@code Map}. * * @author Louis Wasserman */ @GwtCompatible abstract class AbstractMultimap<K, V> implements Multimap<K, V> { @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsValue(@Nullable Object value) { for (Collection<V> collection : asMap().values()) { if (collection.contains(value)) { return true; } } return false; } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { Collection<V> collection = asMap().get(key); return collection != null && collection.contains(value); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { Collection<V> collection = asMap().get(key); return collection != null && collection.remove(value); } @Override public boolean put(@Nullable K key, @Nullable V value) { return get(key).add(value); } @Override public boolean putAll(@Nullable K key, Iterable<? extends V> values) { checkNotNull(values); // make sure we only call values.iterator() once // and we only call get(key) if values is nonempty if (values instanceof Collection) { Collection<? extends V> valueCollection = (Collection<? extends V>) values; return !valueCollection.isEmpty() && get(key).addAll(valueCollection); } else { Iterator<? extends V> valueItr = values.iterator(); return valueItr.hasNext() && Iterators.addAll(get(key), valueItr); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { boolean changed = false; for (Map.Entry<? extends K, ? extends V> entry : multimap.entries()) { changed |= put(entry.getKey(), entry.getValue()); } return changed; } @Override public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { checkNotNull(values); Collection<V> result = removeAll(key); putAll(key, values); return result; } private transient Collection<Entry<K, V>> entries; @Override public Collection<Entry<K, V>> entries() { Collection<Entry<K, V>> result = entries; return (result == null) ? entries = createEntries() : result; } Collection<Entry<K, V>> createEntries() { if (this instanceof SetMultimap) { return new EntrySet(); } else { return new Entries(); } } private class Entries extends Multimaps.Entries<K, V> { @Override Multimap<K, V> multimap() { return AbstractMultimap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } } private class EntrySet extends Entries implements Set<Entry<K, V>> { @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean equals(@Nullable Object obj) { return Sets.equalsImpl(this, obj); } } abstract Iterator<Entry<K, V>> entryIterator(); private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } Set<K> createKeySet() { return new Maps.KeySet<K, Collection<V>>(asMap()); } private transient Multiset<K> keys; @Override public Multiset<K> keys() { Multiset<K> result = keys; return (result == null) ? keys = createKeys() : result; } Multiset<K> createKeys() { return new Multimaps.Keys<K, V>(this); } private transient Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = createValues() : result; } Collection<V> createValues() { return new Values(); } class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return valueIterator(); } @Override public int size() { return AbstractMultimap.this.size(); } @Override public boolean contains(@Nullable Object o) { return AbstractMultimap.this.containsValue(o); } @Override public void clear() { AbstractMultimap.this.clear(); } } Iterator<V> valueIterator() { return Maps.valueIterator(entries().iterator()); } private transient Map<K, Collection<V>> asMap; @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = asMap; return (result == null) ? asMap = createAsMap() : result; } abstract Map<K, Collection<V>> createAsMap(); // Comparison and hashing @Override public boolean equals(@Nullable Object object) { return Multimaps.equalsImpl(this, object); } /** * 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}. * * @see Map#hashCode */ @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(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractMultimap.java
Java
asf20
6,296
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Skeletal, implementation-agnostic implementation of the {@link Table} interface. * * @author Louis Wasserman */ @GwtCompatible abstract class AbstractTable<R, C, V> implements Table<R, C, V> { @Override public boolean containsRow(@Nullable Object rowKey) { return Maps.safeContainsKey(rowMap(), rowKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { return Maps.safeContainsKey(columnMap(), columnKey); } @Override public Set<R> rowKeySet() { return rowMap().keySet(); } @Override public Set<C> columnKeySet() { return columnMap().keySet(); } @Override public boolean containsValue(@Nullable Object value) { for (Map<C, V> row : rowMap().values()) { if (row.containsValue(value)) { return true; } } return false; } @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return row != null && Maps.safeContainsKey(row, columnKey); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return (row == null) ? null : Maps.safeGet(row, columnKey); } @Override public boolean isEmpty() { return size() == 0; } @Override public void clear() { Iterators.clear(cellSet().iterator()); } @Override public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return (row == null) ? null : Maps.safeRemove(row, columnKey); } @Override public V put(R rowKey, C columnKey, V value) { return row(rowKey).put(columnKey, value); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { for (Table.Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) { put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } } private transient Set<Cell<R, C, V>> cellSet; @Override public Set<Cell<R, C, V>> cellSet() { Set<Cell<R, C, V>> result = cellSet; return (result == null) ? cellSet = createCellSet() : result; } Set<Cell<R, C, V>> createCellSet() { return new CellSet(); } abstract Iterator<Table.Cell<R, C, V>> cellIterator(); class CellSet extends AbstractSet<Cell<R, C, V>> { @Override public boolean contains(Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeContains( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; } @Override public boolean remove(@Nullable Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeRemove( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; } @Override public void clear() { AbstractTable.this.clear(); } @Override public Iterator<Table.Cell<R, C, V>> iterator() { return cellIterator(); } @Override public int size() { return AbstractTable.this.size(); } } private transient Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = createValues() : result; } Collection<V> createValues() { return new Values(); } Iterator<V> valuesIterator() { return new TransformedIterator<Cell<R, C, V>, V>(cellSet().iterator()) { @Override V transform(Cell<R, C, V> cell) { return cell.getValue(); } }; } class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return valuesIterator(); } @Override public boolean contains(Object o) { return containsValue(o); } @Override public void clear() { AbstractTable.this.clear(); } @Override public int size() { return AbstractTable.this.size(); } } @Override public boolean equals(@Nullable Object obj) { return Tables.equalsImpl(this, obj); } @Override public int hashCode() { return cellSet().hashCode(); } /** * Returns the string representation {@code rowMap().toString()}. */ @Override public String toString() { return rowMap().toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractTable.java
Java
asf20
5,508
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; /** * 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)); } /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap( Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); Serialization.populateMultiset(this, stream, distinctElements); } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/HashMultiset.java
Java
asf20
3,312
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Ints; import javax.annotation.Nullable; /** * Static methods for implementing hash-based collections. * * @author Kevin Bourrillion * @author Jesse Wilson * @author Austin Appleby */ @GwtCompatible final class Hashing { private Hashing() {} private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; /* * This method was rewritten in Java from an intermediate step of the Murmur hash function in * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the * following header: * * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author * hereby disclaims copyright to this source code. */ static int smear(int hashCode) { return C2 * Integer.rotateLeft(hashCode * C1, 15); } static int smearedHash(@Nullable Object o) { return smear((o == null) ? 0 : o.hashCode()); } private static int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; static int closedTableSize(int expectedEntries, double loadFactor) { // Get the recommended table size. // Round down to the nearest power of 2. expectedEntries = Math.max(expectedEntries, 2); int tableSize = Integer.highestOneBit(expectedEntries); // Check to make sure that we will not exceed the maximum load factor. if (expectedEntries > (int) (loadFactor * tableSize)) { tableSize <<= 1; return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE; } return tableSize; } static boolean needsResizing(int size, int tableSize, double loadFactor) { return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Hashing.java
Java
asf20
2,385
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multisets.UnmodifiableMultiset; import java.util.Comparator; import java.util.NavigableSet; /** * Implementation of {@link Multisets#unmodifiableSortedMultiset(SortedMultiset)}, * split out into its own file so it can be GWT emulated (to deal with the differing * elementSet() types in GWT and non-GWT). * * @author Louis Wasserman */ @GwtCompatible(emulated = true) final class UnmodifiableSortedMultiset<E> extends UnmodifiableMultiset<E> implements SortedMultiset<E> { UnmodifiableSortedMultiset(SortedMultiset<E> delegate) { super(delegate); } @Override protected SortedMultiset<E> delegate() { return (SortedMultiset<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override NavigableSet<E> createElementSet() { return Sets.unmodifiableNavigableSet(delegate().elementSet()); } @Override public NavigableSet<E> elementSet() { return (NavigableSet<E>) super.elementSet(); } private transient UnmodifiableSortedMultiset<E> descendingMultiset; @Override public SortedMultiset<E> descendingMultiset() { UnmodifiableSortedMultiset<E> result = descendingMultiset; if (result == null) { result = new UnmodifiableSortedMultiset<E>( delegate().descendingMultiset()); result.descendingMultiset = this; return descendingMultiset = result; } return result; } @Override public Entry<E> firstEntry() { return delegate().firstEntry(); } @Override public Entry<E> lastEntry() { return delegate().lastEntry(); } @Override public Entry<E> pollFirstEntry() { throw new UnsupportedOperationException(); } @Override public Entry<E> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset( delegate().headMultiset(upperBound, boundType)); } @Override public SortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return Multisets.unmodifiableSortedMultiset(delegate().subMultiset( lowerBound, lowerBoundType, upperBound, upperBoundType)); } @Override public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset( delegate().tailMultiset(lowerBound, boundType)); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
Java
asf20
3,269
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMapEntry.TerminalEntry; import java.io.Serializable; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.annotation.Nullable; /** * An immutable, hash-based {@link Map} with reliable user-specified iteration * order. Does not permit null keys or values. * * <p>Unlike {@link Collections#unmodifiableMap}, which is a <i>view</i> of a * separate map which can still change, an instance of {@code ImmutableMap} * contains its own data and will <i>never</i> change. {@code ImmutableMap} is * convenient for {@code public static final} maps ("constant maps") and also * lets you easily make a "defensive copy" of a map provided to your class by a * caller. * * <p><i>Performance notes:</i> unlike {@link HashMap}, {@code ImmutableMap} is * not optimized for element types that have slow {@link Object#equals} or * {@link Object#hashCode} implementations. You can get better performance by * having your element type cache its own hash codes, and by making use of the * cached values to short-circuit a slow {@code equals} algorithm. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable { /** * Returns the empty map. This map behaves and performs comparably to * {@link Collections#emptyMap}, and is preferable mainly for consistency * and maintainability of your code. */ public static <K, V> ImmutableMap<K, V> of() { return ImmutableBiMap.of(); } /** * Returns an immutable map containing a single entry. This map behaves and * performs comparably to {@link Collections#singletonMap} but will not accept * a null key or value. It is preferable mainly for consistency and * maintainability of your code. */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { return ImmutableBiMap.of(k1, v1); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } // looking for of() with > 5 entries? Use the builder instead. /** * Verifies that {@code key} and {@code value} are non-null, and returns a new * immutable entry with those values. * * <p>A call to {@link Map.Entry#setValue} on the returned entry will always * throw {@link UnsupportedOperationException}. */ static <K, V> TerminalEntry<K, V> entryOf(K key, V value) { checkEntryNotNull(key, value); return new TerminalEntry<K, V>(key, value); } /** * 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>(); } static void checkNoConflict(boolean safe, String conflictDescription, Entry<?, ?> entry1, Entry<?, ?> entry2) { if (!safe) { throw new IllegalArgumentException( "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2); } } /** * A builder for creating immutable map instances, especially {@code public * static final} maps ("constant maps"). Example: <pre> {@code * * static final ImmutableMap<String, Integer> WORD_TO_INT = * new ImmutableMap.Builder<String, Integer>() * .put("one", 1) * .put("two", 2) * .put("three", 3) * .build();}</pre> * * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are * even more convenient. * * <p>Builder instances can be reused - it is safe to call {@link #build} * multiple times to build multiple maps in series. Each map is a superset of * the maps created before it. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<K, V> { TerminalEntry<K, V>[] entries; int size; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMap#builder}. */ public Builder() { this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); } @SuppressWarnings("unchecked") Builder(int initialCapacity) { this.entries = new TerminalEntry[initialCapacity]; this.size = 0; } private void ensureCapacity(int minCapacity) { if (minCapacity > entries.length) { entries = ObjectArrays.arraysCopyOf( entries, ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity)); } } /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys are not allowed, and will cause {@link #build} to fail. */ public Builder<K, V> put(K key, V value) { ensureCapacity(size + 1); TerminalEntry<K, V> entry = entryOf(key, value); // don't inline this: we want to fail atomically if key or value is null entries[size++] = entry; return this; } /** * Adds the given {@code entry} to the map, making it immutable if * necessary. Duplicate keys are not allowed, and will cause {@link #build} * to fail. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { return put(entry.getKey(), entry.getValue()); } /** * Associates all of the given map's keys and values in the built map. * Duplicate keys are not allowed, and will cause {@link #build} to fail. * * @throws NullPointerException if any key or value in {@code map} is null */ public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { ensureCapacity(size + map.size()); for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry); } return this; } /* * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap * versions throw an IllegalStateException instead? */ /** * Returns a newly-created immutable map. * * @throws IllegalArgumentException if duplicate keys were added */ public ImmutableMap<K, V> build() { switch (size) { case 0: return of(); case 1: return of(entries[0].getKey(), entries[0].getValue()); default: return new RegularImmutableMap<K, V>(size, entries); } } } /** * Returns an immutable map containing the same entries as {@code map}. If * {@code map} somehow contains entries with duplicate keys (for example, if * it is a {@code SortedMap} whose comparator is not <i>consistent with * equals</i>), the results of this method are undefined. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws NullPointerException if any key or value in {@code map} is null */ public static <K, V> ImmutableMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) { // TODO(user): Make ImmutableMap.copyOf(immutableBiMap) call copyOf() // on the ImmutableMap delegate(), rather than the bimap itself @SuppressWarnings("unchecked") // safe since map is not writable ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map; if (!kvMap.isPartialView()) { return kvMap; } } else if (map instanceof EnumMap) { return copyOfEnumMapUnsafe(map); } Entry<?, ?>[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); switch (entries.length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // all entries will be Entry<K, V>'s Entry<K, V> onlyEntry = (Entry<K, V>) entries[0]; return of(onlyEntry.getKey(), onlyEntry.getValue()); default: return new RegularImmutableMap<K, V>(entries); } } // If the map is an EnumMap, it must have key type K for some <K extends Enum<K>>. @SuppressWarnings({"unchecked", "rawtypes"}) private static <K, V> ImmutableMap<K, V> copyOfEnumMapUnsafe(Map<? extends K, ? extends V> map) { return copyOfEnumMap((EnumMap) map); } private static <K extends Enum<K>, V> ImmutableMap<K, V> copyOfEnumMap( Map<K, ? extends V> original) { EnumMap<K, V> copy = new EnumMap<K, V>(original); for (Map.Entry<?, ?> entry : copy.entrySet()) { checkEntryNotNull(entry.getKey(), entry.getValue()); } return ImmutableEnumMap.asImmutable(copy); } private static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0]; ImmutableMap() {} /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final V put(K k, V v) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final V remove(Object o) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void clear() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } // Overriding to mark it Nullable @Override public abstract V get(@Nullable Object key); private transient ImmutableSet<Entry<K, V>> entrySet; /** * Returns an immutable set of the mappings in this map. The entries are in * the same order as the parameters used to build this map. */ @Override public ImmutableSet<Entry<K, V>> entrySet() { ImmutableSet<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } abstract ImmutableSet<Entry<K, V>> createEntrySet(); private transient ImmutableSet<K> keySet; /** * Returns an immutable set of the keys in this map. These keys are in * the same order as the parameters used to build this map. */ @Override public ImmutableSet<K> keySet() { ImmutableSet<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } ImmutableSet<K> createKeySet() { return new ImmutableMapKeySet<K, V>(this); } private transient ImmutableCollection<V> values; /** * Returns an immutable collection of the values in this map. The values are * in the same order as the parameters used to build this map. */ @Override public ImmutableCollection<V> values() { ImmutableCollection<V> result = values; return (result == null) ? values = new ImmutableMapValues<K, V>(this) : result; } // cached so that this.multimapView().inverse() only computes inverse once private transient ImmutableSetMultimap<K, V> multimapView; /** * Returns a multimap view of the map. * * @since 14.0 */ @Beta public ImmutableSetMultimap<K, V> asMultimap() { ImmutableSetMultimap<K, V> result = multimapView; return (result == null) ? (multimapView = createMultimapView()) : result; } private ImmutableSetMultimap<K, V> createMultimapView() { ImmutableMap<K, ImmutableSet<V>> map = viewMapValuesAsSingletonSets(); return new ImmutableSetMultimap<K, V>(map, map.size(), null); } private ImmutableMap<K, ImmutableSet<V>> viewMapValuesAsSingletonSets() { return new MapViewOfValuesAsSingletonSets<K, V>(this); } private static final class MapViewOfValuesAsSingletonSets<K, V> extends ImmutableMap<K, ImmutableSet<V>> { private final ImmutableMap<K, V> delegate; MapViewOfValuesAsSingletonSets(ImmutableMap<K, V> delegate) { this.delegate = checkNotNull(delegate); } @Override public int size() { return delegate.size(); } @Override public boolean containsKey(@Nullable Object key) { return delegate.containsKey(key); } @Override public ImmutableSet<V> get(@Nullable Object key) { V outerValue = delegate.get(key); return (outerValue == null) ? null : ImmutableSet.of(outerValue); } @Override boolean isPartialView() { return false; } @Override ImmutableSet<Entry<K, ImmutableSet<V>>> createEntrySet() { return new ImmutableMapEntrySet<K, ImmutableSet<V>>() { @Override ImmutableMap<K, ImmutableSet<V>> map() { return MapViewOfValuesAsSingletonSets.this; } @Override public UnmodifiableIterator<Entry<K, ImmutableSet<V>>> iterator() { final Iterator<Entry<K, V>> backingIterator = delegate.entrySet().iterator(); return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() { @Override public boolean hasNext() { return backingIterator.hasNext(); } @Override public Entry<K, ImmutableSet<V>> next() { final Entry<K, V> backingEntry = backingIterator.next(); return new AbstractMapEntry<K, ImmutableSet<V>>() { @Override public K getKey() { return backingEntry.getKey(); } @Override public ImmutableSet<V> getValue() { return ImmutableSet.of(backingEntry.getValue()); } }; } }; } }; } } @Override public boolean equals(@Nullable Object object) { return Maps.equalsImpl(this, object); } abstract boolean isPartialView(); @Override public int hashCode() { // not caching hash code since it could change if map values are mutable // in a way that modifies their hash codes return entrySet().hashCode(); } @Override public String toString() { return Maps.toStringImpl(this); } /** * Serialized type for all ImmutableMap instances. It captures the logical * contents and they are reconstructed using public factory methods. This * ensures that the implementation types remain as implementation details. */ static class SerializedForm implements Serializable { private final Object[] keys; private final Object[] values; SerializedForm(ImmutableMap<?, ?> map) { keys = new Object[map.size()]; values = new Object[map.size()]; int i = 0; for (Entry<?, ?> entry : map.entrySet()) { keys[i] = entry.getKey(); values[i] = entry.getValue(); i++; } } Object readResolve() { Builder<Object, Object> builder = new Builder<Object, Object>(); return createMap(builder); } Object createMap(Builder<Object, Object> builder) { for (int i = 0; i < keys.length; i++) { builder.put(keys[i], values[i]); } return builder.build(); } private static final long serialVersionUID = 0; } Object writeReplace() { return new SerializedForm(this); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableMap.java
Java
asf20
18,353
/* * 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 javax.annotation.Nullable; /** * Wraps an exception that occurred during a computation. * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public class ComputationException extends RuntimeException { /** * Creates a new instance with the given cause. */ public ComputationException(@Nullable Throwable cause) { super(cause); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ComputationException.java
Java
asf20
1,142
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; /** * An iterator that does not support {@link #remove}. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class UnmodifiableIterator<E> implements Iterator<E> { /** Constructor for use by subclasses. */ protected UnmodifiableIterator() {} /** * Guaranteed to throw an exception and leave the underlying data unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void remove() { throw new UnsupportedOperationException(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/UnmodifiableIterator.java
Java
asf20
1,329
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER; import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.SortedLists.KeyAbsentBehavior; import com.google.common.collect.SortedLists.KeyPresentBehavior; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An efficient immutable implementation of a {@link RangeSet}. * * @author Louis Wasserman * @since 14.0 */ @Beta public final class ImmutableRangeSet<C extends Comparable> extends AbstractRangeSet<C> implements Serializable { private static final ImmutableRangeSet<Comparable<?>> EMPTY = new ImmutableRangeSet<Comparable<?>>(ImmutableList.<Range<Comparable<?>>>of()); private static final ImmutableRangeSet<Comparable<?>> ALL = new ImmutableRangeSet<Comparable<?>>(ImmutableList.of(Range.<Comparable<?>>all())); /** * Returns an empty immutable range set. */ @SuppressWarnings("unchecked") public static <C extends Comparable> ImmutableRangeSet<C> of() { return (ImmutableRangeSet<C>) EMPTY; } /** * Returns an immutable range set containing the single range {@link Range#all()}. */ @SuppressWarnings("unchecked") static <C extends Comparable> ImmutableRangeSet<C> all() { return (ImmutableRangeSet<C>) ALL; } /** * Returns an immutable range set containing the specified single range. If {@link Range#isEmpty() * range.isEmpty()}, this is equivalent to {@link ImmutableRangeSet#of()}. */ public static <C extends Comparable> ImmutableRangeSet<C> of(Range<C> range) { checkNotNull(range); if (range.isEmpty()) { return of(); } else if (range.equals(Range.all())) { return all(); } else { return new ImmutableRangeSet<C>(ImmutableList.of(range)); } } /** * Returns an immutable copy of the specified {@code RangeSet}. */ public static <C extends Comparable> ImmutableRangeSet<C> copyOf(RangeSet<C> rangeSet) { checkNotNull(rangeSet); if (rangeSet.isEmpty()) { return of(); } else if (rangeSet.encloses(Range.<C>all())) { return all(); } if (rangeSet instanceof ImmutableRangeSet) { ImmutableRangeSet<C> immutableRangeSet = (ImmutableRangeSet<C>) rangeSet; if (!immutableRangeSet.isPartialView()) { return immutableRangeSet; } } return new ImmutableRangeSet<C>(ImmutableList.copyOf(rangeSet.asRanges())); } ImmutableRangeSet(ImmutableList<Range<C>> ranges) { this.ranges = ranges; } private ImmutableRangeSet(ImmutableList<Range<C>> ranges, ImmutableRangeSet<C> complement) { this.ranges = ranges; this.complement = complement; } private transient final ImmutableList<Range<C>> ranges; @Override public boolean encloses(Range<C> otherRange) { int index = SortedLists.binarySearch(ranges, Range.<C>lowerBoundFn(), otherRange.lowerBound, Ordering.natural(), ANY_PRESENT, NEXT_LOWER); return index != -1 && ranges.get(index).encloses(otherRange); } @Override public Range<C> rangeContaining(C value) { int index = SortedLists.binarySearch(ranges, Range.<C>lowerBoundFn(), Cut.belowValue(value), Ordering.natural(), ANY_PRESENT, NEXT_LOWER); if (index != -1) { Range<C> range = ranges.get(index); return range.contains(value) ? range : null; } return null; } @Override public Range<C> span() { if (ranges.isEmpty()) { throw new NoSuchElementException(); } return Range.create( ranges.get(0).lowerBound, ranges.get(ranges.size() - 1).upperBound); } @Override public boolean isEmpty() { return ranges.isEmpty(); } @Override public void add(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void addAll(RangeSet<C> other) { throw new UnsupportedOperationException(); } @Override public void remove(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void removeAll(RangeSet<C> other) { throw new UnsupportedOperationException(); } @Override public ImmutableSet<Range<C>> asRanges() { if (ranges.isEmpty()) { return ImmutableSet.of(); } return new RegularImmutableSortedSet<Range<C>>(ranges, Range.RANGE_LEX_ORDERING); } private transient ImmutableRangeSet<C> complement; private final class ComplementRanges extends ImmutableList<Range<C>> { // True if the "positive" range set is empty or bounded below. private final boolean positiveBoundedBelow; // True if the "positive" range set is empty or bounded above. private final boolean positiveBoundedAbove; private final int size; ComplementRanges() { this.positiveBoundedBelow = ranges.get(0).hasLowerBound(); this.positiveBoundedAbove = Iterables.getLast(ranges).hasUpperBound(); int size = ranges.size() - 1; if (positiveBoundedBelow) { size++; } if (positiveBoundedAbove) { size++; } this.size = size; } @Override public int size() { return size; } @Override public Range<C> get(int index) { checkElementIndex(index, size); Cut<C> lowerBound; if (positiveBoundedBelow) { lowerBound = (index == 0) ? Cut.<C>belowAll() : ranges.get(index - 1).upperBound; } else { lowerBound = ranges.get(index).upperBound; } Cut<C> upperBound; if (positiveBoundedAbove && index == size - 1) { upperBound = Cut.<C>aboveAll(); } else { upperBound = ranges.get(index + (positiveBoundedBelow ? 0 : 1)).lowerBound; } return Range.create(lowerBound, upperBound); } @Override boolean isPartialView() { return true; } } @Override public ImmutableRangeSet<C> complement() { ImmutableRangeSet<C> result = complement; if (result != null) { return result; } else if (ranges.isEmpty()) { return complement = all(); } else if (ranges.size() == 1 && ranges.get(0).equals(Range.all())) { return complement = of(); } else { ImmutableList<Range<C>> complementRanges = new ComplementRanges(); result = complement = new ImmutableRangeSet<C>(complementRanges, this); } return result; } /** * Returns a list containing the nonempty intersections of {@code range} * with the ranges in this range set. */ private ImmutableList<Range<C>> intersectRanges(final Range<C> range) { if (ranges.isEmpty() || range.isEmpty()) { return ImmutableList.of(); } else if (range.encloses(span())) { return ranges; } final int fromIndex; if (range.hasLowerBound()) { fromIndex = SortedLists.binarySearch( ranges, Range.<C>upperBoundFn(), range.lowerBound, KeyPresentBehavior.FIRST_AFTER, KeyAbsentBehavior.NEXT_HIGHER); } else { fromIndex = 0; } int toIndex; if (range.hasUpperBound()) { toIndex = SortedLists.binarySearch( ranges, Range.<C>lowerBoundFn(), range.upperBound, KeyPresentBehavior.FIRST_PRESENT, KeyAbsentBehavior.NEXT_HIGHER); } else { toIndex = ranges.size(); } final int length = toIndex - fromIndex; if (length == 0) { return ImmutableList.of(); } else { return new ImmutableList<Range<C>>() { @Override public int size() { return length; } @Override public Range<C> get(int index) { checkElementIndex(index, length); if (index == 0 || index == length - 1) { return ranges.get(index + fromIndex).intersection(range); } else { return ranges.get(index + fromIndex); } } @Override boolean isPartialView() { return true; } }; } } /** * Returns a view of the intersection of this range set with the given range. */ @Override public ImmutableRangeSet<C> subRangeSet(Range<C> range) { if (!isEmpty()) { Range<C> span = span(); if (range.encloses(span)) { return this; } else if (range.isConnected(span)) { return new ImmutableRangeSet<C>(intersectRanges(range)); } } return of(); } /** * Returns an {@link ImmutableSortedSet} containing the same values in the given domain * {@linkplain RangeSet#contains contained} by this range set. * * <p><b>Note:</b> {@code a.asSet(d).equals(b.asSet(d))} does not imply {@code a.equals(b)}! For * example, {@code a} and {@code b} could be {@code [2..4]} and {@code (1..5)}, or the empty * ranges {@code [3..3)} and {@code [4..4)}. * * <p><b>Warning:</b> Be extremely careful what you do with the {@code asSet} view of a large * range set (such as {@code ImmutableRangeSet.of(Range.greaterThan(0))}). Certain operations on * such a set can be performed efficiently, but others (such as {@link Set#hashCode} or * {@link Collections#frequency}) can cause major performance problems. * * <p>The returned set's {@link Object#toString} method returns a short-hand form of the set's * contents, such as {@code "[1..100]}"}. * * @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if * neither has an upper bound */ public ImmutableSortedSet<C> asSet(DiscreteDomain<C> domain) { checkNotNull(domain); if (isEmpty()) { return ImmutableSortedSet.of(); } Range<C> span = span().canonical(domain); if (!span.hasLowerBound()) { // according to the spec of canonical, neither this ImmutableRangeSet nor // the range have a lower bound throw new IllegalArgumentException( "Neither the DiscreteDomain nor this range set are bounded below"); } else if (!span.hasUpperBound()) { try { domain.maxValue(); } catch (NoSuchElementException e) { throw new IllegalArgumentException( "Neither the DiscreteDomain nor this range set are bounded above"); } } return new AsSet(domain); } private final class AsSet extends ImmutableSortedSet<C> { private final DiscreteDomain<C> domain; AsSet(DiscreteDomain<C> domain) { super(Ordering.natural()); this.domain = domain; } private transient Integer size; @Override public int size() { // racy single-check idiom Integer result = size; if (result == null) { long total = 0; for (Range<C> range : ranges) { total += ContiguousSet.create(range, domain).size(); if (total >= Integer.MAX_VALUE) { break; } } result = size = Ints.saturatedCast(total); } return result.intValue(); } @Override public UnmodifiableIterator<C> iterator() { return new AbstractIterator<C>() { final Iterator<Range<C>> rangeItr = ranges.iterator(); Iterator<C> elemItr = Iterators.emptyIterator(); @Override protected C computeNext() { while (!elemItr.hasNext()) { if (rangeItr.hasNext()) { elemItr = ContiguousSet.create(rangeItr.next(), domain).iterator(); } else { return endOfData(); } } return elemItr.next(); } }; } @Override @GwtIncompatible("NavigableSet") public UnmodifiableIterator<C> descendingIterator() { return new AbstractIterator<C>() { final Iterator<Range<C>> rangeItr = ranges.reverse().iterator(); Iterator<C> elemItr = Iterators.emptyIterator(); @Override protected C computeNext() { while (!elemItr.hasNext()) { if (rangeItr.hasNext()) { elemItr = ContiguousSet.create(rangeItr.next(), domain).descendingIterator(); } else { return endOfData(); } } return elemItr.next(); } }; } ImmutableSortedSet<C> subSet(Range<C> range) { return subRangeSet(range).asSet(domain); } @Override ImmutableSortedSet<C> headSetImpl(C toElement, boolean inclusive) { return subSet(Range.upTo(toElement, BoundType.forBoolean(inclusive))); } @Override ImmutableSortedSet<C> subSetImpl( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { if (!fromInclusive && !toInclusive && Range.compareOrThrow(fromElement, toElement) == 0) { return ImmutableSortedSet.of(); } return subSet(Range.range( fromElement, BoundType.forBoolean(fromInclusive), toElement, BoundType.forBoolean(toInclusive))); } @Override ImmutableSortedSet<C> tailSetImpl(C fromElement, boolean inclusive) { return subSet(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); } @Override public boolean contains(@Nullable Object o) { if (o == null) { return false; } try { @SuppressWarnings("unchecked") // we catch CCE's C c = (C) o; return ImmutableRangeSet.this.contains(c); } catch (ClassCastException e) { return false; } } @Override int indexOf(Object target) { if (contains(target)) { @SuppressWarnings("unchecked") // if it's contained, it's definitely a C C c = (C) target; long total = 0; for (Range<C> range : ranges) { if (range.contains(c)) { return Ints.saturatedCast(total + ContiguousSet.create(range, domain).indexOf(c)); } else { total += ContiguousSet.create(range, domain).size(); } } throw new AssertionError("impossible"); } return -1; } @Override boolean isPartialView() { return ranges.isPartialView(); } @Override public String toString() { return ranges.toString(); } @Override Object writeReplace() { return new AsSetSerializedForm<C>(ranges, domain); } } private static class AsSetSerializedForm<C extends Comparable> implements Serializable { private final ImmutableList<Range<C>> ranges; private final DiscreteDomain<C> domain; AsSetSerializedForm(ImmutableList<Range<C>> ranges, DiscreteDomain<C> domain) { this.ranges = ranges; this.domain = domain; } Object readResolve() { return new ImmutableRangeSet<C>(ranges).asSet(domain); } } /** * Returns {@code true} if this immutable range set's implementation contains references to * user-created objects that aren't accessible via this range set's methods. This is generally * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid * memory leaks. */ boolean isPartialView() { return ranges.isPartialView(); } /** * Returns a new builder for an immutable range set. */ public static <C extends Comparable<?>> Builder<C> builder() { return new Builder<C>(); } /** * A builder for immutable range sets. */ public static class Builder<C extends Comparable<?>> { private final RangeSet<C> rangeSet; public Builder() { this.rangeSet = TreeRangeSet.create(); } /** * Add the specified range to this builder. Adjacent/abutting ranges are permitted, but * empty ranges, or ranges with nonempty overlap, are forbidden. * * @throws IllegalArgumentException if {@code range} is empty or has nonempty intersection with * any ranges already added to the builder */ public Builder<C> add(Range<C> range) { if (range.isEmpty()) { throw new IllegalArgumentException("range must not be empty, but was " + range); } else if (!rangeSet.complement().encloses(range)) { for (Range<C> currentRange : rangeSet.asRanges()) { checkArgument( !currentRange.isConnected(range) || currentRange.intersection(range).isEmpty(), "Ranges may not overlap, but received %s and %s", currentRange, range); } throw new AssertionError("should have thrown an IAE above"); } rangeSet.add(range); return this; } /** * Add all ranges from the specified range set to this builder. Duplicate or connected ranges * are permitted, and will be merged in the resulting immutable range set. */ public Builder<C> addAll(RangeSet<C> ranges) { for (Range<C> range : ranges.asRanges()) { add(range); } return this; } /** * Returns an {@code ImmutableRangeSet} containing the ranges added to this builder. */ public ImmutableRangeSet<C> build() { return copyOf(rangeSet); } } private static final class SerializedForm<C extends Comparable> implements Serializable { private final ImmutableList<Range<C>> ranges; SerializedForm(ImmutableList<Range<C>> ranges) { this.ranges = ranges; } Object readResolve() { if (ranges.isEmpty()) { return of(); } else if (ranges.equals(ImmutableList.of(Range.all()))) { return all(); } else { return new ImmutableRangeSet<C>(ranges); } } } Object writeReplace() { return new SerializedForm<C>(ranges); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableRangeSet.java
Java
asf20
18,565
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.NoSuchElementException; /** * An iterator that supports a one-element lookahead while iterating. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionHelpersExplained#PeekingIterator"> * {@code PeekingIterator}</a>. * * @author Mick Killianey * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface PeekingIterator<E> extends Iterator<E> { /** * Returns the next element in the iteration, without advancing the iteration. * * <p>Calls to {@code peek()} should not change the state of the iteration, * except that it <i>may</i> prevent removal of the most recent element via * {@link #remove()}. * * @throws NoSuchElementException if the iteration has no more elements * according to {@link #hasNext()} */ E peek(); /** * {@inheritDoc} * * <p>The objects returned by consecutive calls to {@link #peek()} then {@link * #next()} are guaranteed to be equal to each other. */ @Override E next(); /** * {@inheritDoc} * * <p>Implementations may or may not support removal when a call to {@link * #peek()} has occurred since the most recent call to {@link #next()}. * * @throws IllegalStateException if there has been a call to {@link #peek()} * since the most recent call to {@link #next()} and this implementation * does not support this sequence of calls (optional) */ @Override void remove(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/PeekingIterator.java
Java
asf20
2,229
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collection; import java.util.Comparator; import javax.annotation.Nullable; /** * An empty immutable sorted multiset. * * @author Louis Wasserman */ @SuppressWarnings("serial") // Uses writeReplace, not default serialization final class EmptyImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private final ImmutableSortedSet<E> elementSet; EmptyImmutableSortedMultiset(Comparator<? super E> comparator) { this.elementSet = ImmutableSortedSet.emptySet(comparator); } @Override public Entry<E> firstEntry() { return null; } @Override public Entry<E> lastEntry() { return null; } @Override public int count(@Nullable Object element) { return 0; } @Override public boolean containsAll(Collection<?> targets) { return targets.isEmpty(); } @Override public int size() { return 0; } @Override public ImmutableSortedSet<E> elementSet() { return elementSet; } @Override Entry<E> getEntry(int index) { throw new AssertionError("should never be called"); } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { checkNotNull(upperBound); checkNotNull(boundType); return this; } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { checkNotNull(lowerBound); checkNotNull(boundType); return this; } @Override public UnmodifiableIterator<E> iterator() { return Iterators.emptyIterator(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof Multiset) { Multiset<?> other = (Multiset<?>) object; return other.isEmpty(); } return false; } @Override boolean isPartialView() { return false; } @Override int copyIntoArray(Object[] dst, int offset) { return offset; } @Override public ImmutableList<E> asList() { return ImmutableList.of(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EmptyImmutableSortedMultiset.java
Java
asf20
2,669
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.Collection; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An empty immutable sorted set. * * @author Jared Levy */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> { EmptyImmutableSortedSet(Comparator<? super E> comparator) { super(comparator); } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(@Nullable Object target) { return false; } @Override public boolean containsAll(Collection<?> targets) { return targets.isEmpty(); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.emptyIterator(); } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<E> descendingIterator() { return Iterators.emptyIterator(); } @Override boolean isPartialView() { return false; } @Override public ImmutableList<E> asList() { return ImmutableList.of(); } @Override int copyIntoArray(Object[] dst, int offset) { return offset; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { Set<?> that = (Set<?>) object; return that.isEmpty(); } return false; } @Override public int hashCode() { return 0; } @Override public String toString() { return "[]"; } @Override public E first() { throw new NoSuchElementException(); } @Override public E last() { throw new NoSuchElementException(); } @Override ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) { return this; } @Override ImmutableSortedSet<E> subSetImpl( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return this; } @Override ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) { return this; } @Override int indexOf(@Nullable Object target) { return -1; } @Override ImmutableSortedSet<E> createDescendingSet() { return new EmptyImmutableSortedSet<E>(Ordering.from(comparator).reverse()); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EmptyImmutableSortedSet.java
Java
asf20
3,062
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Booleans; import java.io.Serializable; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * Implementation detail for the internal structure of {@link Range} instances. Represents * a unique way of "cutting" a "number line" (actually of instances of type {@code C}, not * necessarily "numbers") into two sections; this can be done below a certain value, above * a certain value, below all values or above all values. With this object defined in this * way, an interval can always be represented by a pair of {@code Cut} instances. * * @author Kevin Bourrillion */ @GwtCompatible abstract class Cut<C extends Comparable> implements Comparable<Cut<C>>, Serializable { final C endpoint; Cut(@Nullable C endpoint) { this.endpoint = endpoint; } abstract boolean isLessThan(C value); abstract BoundType typeAsLowerBound(); abstract BoundType typeAsUpperBound(); abstract Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain); abstract Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain); abstract void describeAsLowerBound(StringBuilder sb); abstract void describeAsUpperBound(StringBuilder sb); abstract C leastValueAbove(DiscreteDomain<C> domain); abstract C greatestValueBelow(DiscreteDomain<C> domain); /* * The canonical form is a BelowValue cut whenever possible, otherwise ABOVE_ALL, or * (only in the case of types that are unbounded below) BELOW_ALL. */ Cut<C> canonical(DiscreteDomain<C> domain) { return this; } // note: overriden by {BELOW,ABOVE}_ALL @Override public int compareTo(Cut<C> that) { if (that == belowAll()) { return 1; } if (that == aboveAll()) { return -1; } int result = Range.compareOrThrow(endpoint, that.endpoint); if (result != 0) { return result; } // same value. below comes before above return Booleans.compare( this instanceof AboveValue, that instanceof AboveValue); } C endpoint() { return endpoint; } @SuppressWarnings("unchecked") // catching CCE @Override public boolean equals(Object obj) { if (obj instanceof Cut) { // It might not really be a Cut<C>, but we'll catch a CCE if it's not Cut<C> that = (Cut<C>) obj; try { int compareResult = compareTo(that); return compareResult == 0; } catch (ClassCastException ignored) { } } return false; } /* * The implementation neither produces nor consumes any non-null instance of type C, so * casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> belowAll() { return (Cut<C>) BelowAll.INSTANCE; } private static final long serialVersionUID = 0; private static final class BelowAll extends Cut<Comparable<?>> { private static final BelowAll INSTANCE = new BelowAll(); private BelowAll() { super(null); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return true; } @Override BoundType typeAsLowerBound() { throw new IllegalStateException(); } @Override BoundType typeAsUpperBound() { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withLowerBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withUpperBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override void describeAsLowerBound(StringBuilder sb) { sb.append("(-\u221e"); } @Override void describeAsUpperBound(StringBuilder sb) { throw new AssertionError(); } @Override Comparable<?> leastValueAbove( DiscreteDomain<Comparable<?>> domain) { return domain.minValue(); } @Override Comparable<?> greatestValueBelow( DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Cut<Comparable<?>> canonical( DiscreteDomain<Comparable<?>> domain) { try { return Cut.<Comparable<?>>belowValue(domain.minValue()); } catch (NoSuchElementException e) { return this; } } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : -1; } @Override public String toString() { return "-\u221e"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } /* * The implementation neither produces nor consumes any non-null instance of * type C, so casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> aboveAll() { return (Cut<C>) AboveAll.INSTANCE; } private static final class AboveAll extends Cut<Comparable<?>> { private static final AboveAll INSTANCE = new AboveAll(); private AboveAll() { super(null); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return false; } @Override BoundType typeAsLowerBound() { throw new AssertionError("this statement should be unreachable"); } @Override BoundType typeAsUpperBound() { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withLowerBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withUpperBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override void describeAsLowerBound(StringBuilder sb) { throw new AssertionError(); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append("+\u221e)"); } @Override Comparable<?> leastValueAbove( DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Comparable<?> greatestValueBelow( DiscreteDomain<Comparable<?>> domain) { return domain.maxValue(); } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : 1; } @Override public String toString() { return "+\u221e"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } static <C extends Comparable> Cut<C> belowValue(C endpoint) { return new BelowValue<C>(endpoint); } private static final class BelowValue<C extends Comparable> extends Cut<C> { BelowValue(C endpoint) { super(checkNotNull(endpoint)); } @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) <= 0; } @Override BoundType typeAsLowerBound() { return BoundType.CLOSED; } @Override BoundType typeAsUpperBound() { return BoundType.OPEN; } @Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case CLOSED: return this; case OPEN: @Nullable C previous = domain.previous(endpoint); return (previous == null) ? Cut.<C>belowAll() : new AboveValue<C>(previous); default: throw new AssertionError(); } } @Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case CLOSED: @Nullable C previous = domain.previous(endpoint); return (previous == null) ? Cut.<C>aboveAll() : new AboveValue<C>(previous); case OPEN: return this; default: throw new AssertionError(); } } @Override void describeAsLowerBound(StringBuilder sb) { sb.append('[').append(endpoint); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append(endpoint).append(')'); } @Override C leastValueAbove(DiscreteDomain<C> domain) { return endpoint; } @Override C greatestValueBelow(DiscreteDomain<C> domain) { return domain.previous(endpoint); } @Override public int hashCode() { return endpoint.hashCode(); } @Override public String toString() { return "\\" + endpoint + "/"; } private static final long serialVersionUID = 0; } static <C extends Comparable> Cut<C> aboveValue(C endpoint) { return new AboveValue<C>(endpoint); } private static final class AboveValue<C extends Comparable> extends Cut<C> { AboveValue(C endpoint) { super(checkNotNull(endpoint)); } @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) < 0; } @Override BoundType typeAsLowerBound() { return BoundType.OPEN; } @Override BoundType typeAsUpperBound() { return BoundType.CLOSED; } @Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case OPEN: return this; case CLOSED: @Nullable C next = domain.next(endpoint); return (next == null) ? Cut.<C>belowAll() : belowValue(next); default: throw new AssertionError(); } } @Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case OPEN: @Nullable C next = domain.next(endpoint); return (next == null) ? Cut.<C>aboveAll() : belowValue(next); case CLOSED: return this; default: throw new AssertionError(); } } @Override void describeAsLowerBound(StringBuilder sb) { sb.append('(').append(endpoint); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append(endpoint).append(']'); } @Override C leastValueAbove(DiscreteDomain<C> domain) { return domain.next(endpoint); } @Override C greatestValueBelow(DiscreteDomain<C> domain) { return endpoint; } @Override Cut<C> canonical(DiscreteDomain<C> domain) { C next = leastValueAbove(domain); return (next != null) ? belowValue(next) : Cut.<C>aboveAll(); } @Override public int hashCode() { return ~endpoint.hashCode(); } @Override public String toString() { return "/" + endpoint + "\\"; } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Cut.java
Java
asf20
11,529
/* * 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.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Fixed-size {@link Table} implementation backed by a two-dimensional array. * * <p>The allowed row and column keys must be supplied when the table is * created. The table always contains a mapping for every row key / column pair. * The value corresponding to a given row and column is null unless another * value is provided. * * <p>The table's size is constant: the product of the number of supplied row * keys and the number of supplied column keys. The {@code remove} and {@code * clear} methods are not supported by the table or its views. The {@link * #erase} and {@link #eraseAll} methods may be used instead. * * <p>The ordering of the row and column keys provided when the table is * constructed determines the iteration ordering across rows and columns in the * table's views. None of the view iterators support {@link Iterator#remove}. * If the table is modified after an iterator is created, the iterator remains * valid. * * <p>This class requires less memory than the {@link HashBasedTable} and {@link * TreeBasedTable} implementations, except when the table is sparse. * * <p>Null row keys or column keys are not permitted. * * <p>This class provides methods involving the underlying array structure, * where the array indices correspond to the position of a row or column in the * lists of allowed keys and values. See the {@link #at}, {@link #set}, {@link * #toArray}, {@link #rowKeyList}, and {@link #columnKeyList} methods for more * details. * * <p>Note that this implementation is not synchronized. If multiple threads * access the same cell of an {@code ArrayTable} concurrently and one of the * threads modifies its value, there is no guarantee that the new value will be * fully visible to the other threads. To guarantee that modifications are * visible, synchronize access to the table. Unlike other {@code Table} * implementations, synchronization is unnecessary between a thread that writes * to one cell and a thread that reads from another. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @since 10.0 */ @Beta @GwtCompatible(emulated = true) public final class ArrayTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable { /** * Creates an empty {@code ArrayTable}. * * @param rowKeys row keys that may be stored in the generated table * @param columnKeys column keys that may be stored in the generated table * @throws NullPointerException if any of the provided keys is null * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} * contains duplicates or is empty */ public static <R, C, V> ArrayTable<R, C, V> create( Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { return new ArrayTable<R, C, V>(rowKeys, columnKeys); } /* * TODO(jlevy): Add factory methods taking an Enum class, instead of an * iterable, to specify the allowed row keys and/or column keys. Note that * custom serialization logic is needed to support different enum sizes during * serialization and deserialization. */ /** * Creates an {@code ArrayTable} with the mappings in the provided table. * * <p>If {@code table} includes a mapping with row key {@code r} and a * separate mapping with column key {@code c}, the returned table contains a * mapping with row key {@code r} and column key {@code c}. If that row key / * column key pair in not in {@code table}, the pair maps to {@code null} in * the generated table. * * <p>The returned table allows subsequent {@code put} calls with the row keys * in {@code table.rowKeySet()} and the column keys in {@code * table.columnKeySet()}. Calling {@link #put} with other keys leads to an * {@code IllegalArgumentException}. * * <p>The ordering of {@code table.rowKeySet()} and {@code * table.columnKeySet()} determines the row and column iteration ordering of * the returned table. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if the provided table is empty */ public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, V> table) { return (table instanceof ArrayTable<?, ?, ?>) ? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table) : new ArrayTable<R, C, V>(table); } private final ImmutableList<R> rowList; private final ImmutableList<C> columnList; // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex? private final ImmutableMap<R, Integer> rowKeyToIndex; private final ImmutableMap<C, Integer> columnKeyToIndex; private final V[][] array; private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { this.rowList = ImmutableList.copyOf(rowKeys); this.columnList = ImmutableList.copyOf(columnKeys); checkArgument(!rowList.isEmpty()); checkArgument(!columnList.isEmpty()); /* * TODO(jlevy): Support empty rowKeys or columnKeys? If we do, when * columnKeys is empty but rowKeys isn't, the table is empty but * containsRow() can return true and rowKeySet() isn't empty. */ rowKeyToIndex = index(rowList); columnKeyToIndex = index(columnList); @SuppressWarnings("unchecked") V[][] tmpArray = (V[][]) new Object[rowList.size()][columnList.size()]; array = tmpArray; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); } private static <E> ImmutableMap<E, Integer> index(List<E> list) { ImmutableMap.Builder<E, Integer> columnBuilder = ImmutableMap.builder(); for (int i = 0; i < list.size(); i++) { columnBuilder.put(list.get(i), i); } return columnBuilder.build(); } private ArrayTable(Table<R, C, V> table) { this(table.rowKeySet(), table.columnKeySet()); putAll(table); } private ArrayTable(ArrayTable<R, C, V> table) { rowList = table.rowList; columnList = table.columnList; rowKeyToIndex = table.rowKeyToIndex; columnKeyToIndex = table.columnKeyToIndex; @SuppressWarnings("unchecked") V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()]; array = copy; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length); } } private abstract static class ArrayMap<K, V> extends Maps.ImprovedAbstractMap<K, V> { private final ImmutableMap<K, Integer> keyIndex; private ArrayMap(ImmutableMap<K, Integer> keyIndex) { this.keyIndex = keyIndex; } @Override public Set<K> keySet() { return keyIndex.keySet(); } K getKey(int index) { return keyIndex.keySet().asList().get(index); } abstract String getKeyRole(); @Nullable abstract V getValue(int index); @Nullable abstract V setValue(int index, V newValue); @Override public int size() { return keyIndex.size(); } @Override public boolean isEmpty() { return keyIndex.isEmpty(); } @Override protected Set<Entry<K, V>> createEntrySet() { return new Maps.EntrySet<K, V>() { @Override Map<K, V> map() { return ArrayMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new AbstractIndexedListIterator<Entry<K, V>>(size()) { @Override protected Entry<K, V> get(final int index) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return ArrayMap.this.getKey(index); } @Override public V getValue() { return ArrayMap.this.getValue(index); } @Override public V setValue(V value) { return ArrayMap.this.setValue(index, value); } }; } }; } }; } // TODO(user): consider an optimized values() implementation @Override public boolean containsKey(@Nullable Object key) { return keyIndex.containsKey(key); } @Override public V get(@Nullable Object key) { Integer index = keyIndex.get(key); if (index == null) { return null; } else { return getValue(index); } } @Override public V put(K key, V value) { Integer index = keyIndex.get(key); if (index == null) { throw new IllegalArgumentException( getKeyRole() + " " + key + " not in " + keyIndex.keySet()); } return setValue(index, value); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } } /** * Returns, as an immutable list, the row keys provided when the table was * constructed, including those that are mapped to null values only. */ public ImmutableList<R> rowKeyList() { return rowList; } /** * Returns, as an immutable list, the column keys provided when the table was * constructed, including those that are mapped to null values only. */ public ImmutableList<C> columnKeyList() { return columnList; } /** * Returns the value corresponding to the specified row and column indices. * The same value is returned by {@code * get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but * this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @return the value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code * rowIndex} is greater then or equal to the number of allowed row keys, * or {@code columnIndex} is greater then or equal to the number of * allowed column keys */ public V at(int rowIndex, int columnIndex) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); return array[rowIndex][columnIndex]; } /** * Associates {@code value} with the specified row and column indices. The * logic {@code * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} * has the same behavior, but this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @param value value to store in the table * @return the previous value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code * rowIndex} is greater then or equal to the number of allowed row keys, * or {@code columnIndex} is greater then or equal to the number of * allowed column keys */ public V set(int rowIndex, int columnIndex, @Nullable V value) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); V oldValue = array[rowIndex][columnIndex]; array[rowIndex][columnIndex] = value; return oldValue; } /** * Returns a two-dimensional array with the table contents. The row and column * indices correspond to the positions of the row and column in the iterables * provided during table construction. If the table lacks a mapping for a * given row and column, the corresponding array element is null. * * <p>Subsequent table changes will not modify the array, and vice versa. * * @param valueClass class of values stored in the returned array */ @GwtIncompatible("reflection") public V[][] toArray(Class<V> valueClass) { // Can change to use varargs in JDK 1.6 if we want @SuppressWarnings("unchecked") // TODO: safe? V[][] copy = (V[][]) Array.newInstance( valueClass, new int[] { rowList.size(), columnList.size() }); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(array[i], 0, copy[i], 0, array[i].length); } return copy; } /** * Not supported. Use {@link #eraseAll} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #eraseAll} */ @Override @Deprecated public void clear() { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with every pair of allowed row and column * keys. */ public void eraseAll() { for (V[] row : array) { Arrays.fill(row, null); } } /** * Returns {@code true} if the provided keys are among the keys provided when * the table was constructed. */ @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { return containsRow(rowKey) && containsColumn(columnKey); } /** * Returns {@code true} if the provided column key is among the column keys * provided when the table was constructed. */ @Override public boolean containsColumn(@Nullable Object columnKey) { return columnKeyToIndex.containsKey(columnKey); } /** * Returns {@code true} if the provided row key is among the row keys * provided when the table was constructed. */ @Override public boolean containsRow(@Nullable Object rowKey) { return rowKeyToIndex.containsKey(rowKey); } @Override public boolean containsValue(@Nullable Object value) { for (V[] row : array) { for (V element : row) { if (Objects.equal(value, element)) { return true; } } } return false; } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex); } /** * Always returns {@code false}. */ @Override public boolean isEmpty() { return false; } /** * {@inheritDoc} * * @throws IllegalArgumentException if {@code rowKey} is not in {@link * #rowKeySet()} or {@code columnKey} is not in {@link #columnKeySet()}. */ @Override public V put(R rowKey, C columnKey, @Nullable V value) { checkNotNull(rowKey); checkNotNull(columnKey); Integer rowIndex = rowKeyToIndex.get(rowKey); checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList); Integer columnIndex = columnKeyToIndex.get(columnKey); checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList); return set(rowIndex, columnIndex, value); } /* * TODO(jlevy): Consider creating a merge() method, similar to putAll() but * copying non-null values only. */ /** * {@inheritDoc} * * <p>If {@code table} is an {@code ArrayTable}, its null values will be * stored in this table, possibly replacing values that were previously * non-null. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if any of the provided table's row keys or * column keys is not in {@link #rowKeySet()} or {@link #columnKeySet()} */ @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { super.putAll(table); } /** * Not supported. Use {@link #erase} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #erase} */ @Override @Deprecated public V remove(Object rowKey, Object columnKey) { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with the specified keys, assuming both * keys are valid. If either key is null or isn't among the keys provided * during construction, this method has no effect. * * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when * both provided keys are valid. * * @param rowKey row key of mapping to be erased * @param columnKey column key of mapping to be erased * @return the value previously associated with the keys, or {@code null} if * no mapping existed for the keys */ public V erase(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); if (rowIndex == null || columnIndex == null) { return null; } return set(rowIndex, columnIndex, null); } // TODO(jlevy): Add eraseRow and eraseColumn methods? @Override public int size() { return rowList.size() * columnList.size(); } /** * Returns an unmodifiable set of all row key / column key / value * triplets. Changes to the table will update the returned set. * * <p>The returned set's iterator traverses the mappings with the first row * key, the mappings with the second row key, and so on. * * <p>The value in the returned cells may change if the table subsequently * changes. * * @return set of table cells consisting of row key / column key / value * triplets */ @Override public Set<Cell<R, C, V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, V>> cellIterator() { return new AbstractIndexedListIterator<Cell<R, C, V>>(size()) { @Override protected Cell<R, C, V> get(final int index) { return new Tables.AbstractCell<R, C, V>() { final int rowIndex = index / columnList.size(); final int columnIndex = index % columnList.size(); @Override public R getRowKey() { return rowList.get(rowIndex); } @Override public C getColumnKey() { return columnList.get(columnIndex); } @Override public V getValue() { return at(rowIndex, columnIndex); } }; } }; } /** * Returns a view of all mappings that have the given column key. If the * column key isn't in {@link #columnKeySet()}, an empty immutable map is * returned. * * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map * associates the row key with the corresponding value in the table. Changes * to the returned map will update the underlying table, and vice versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ @Override public Map<R, V> column(C columnKey) { checkNotNull(columnKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (columnIndex == null) ? ImmutableMap.<R, V>of() : new Column(columnIndex); } private class Column extends ArrayMap<R, V> { final int columnIndex; Column(int columnIndex) { super(rowKeyToIndex); this.columnIndex = columnIndex; } @Override String getKeyRole() { return "Row"; } @Override V getValue(int index) { return at(index, columnIndex); } @Override V setValue(int index, V newValue) { return set(index, columnIndex, newValue); } } /** * Returns an immutable set of the valid column keys, including those that * are associated with null values only. * * @return immutable set of column keys */ @Override public ImmutableSet<C> columnKeySet() { return columnKeyToIndex.keySet(); } private transient ColumnMap columnMap; @Override public Map<C, Map<R, V>> columnMap() { ColumnMap map = columnMap; return (map == null) ? columnMap = new ColumnMap() : map; } private class ColumnMap extends ArrayMap<C, Map<R, V>> { private ColumnMap() { super(columnKeyToIndex); } @Override String getKeyRole() { return "Column"; } @Override Map<R, V> getValue(int index) { return new Column(index); } @Override Map<R, V> setValue(int index, Map<R, V> newValue) { throw new UnsupportedOperationException(); } @Override public Map<R, V> put(C key, Map<R, V> value) { throw new UnsupportedOperationException(); } } /** * Returns a view of all mappings that have the given row key. If the * row key isn't in {@link #rowKeySet()}, an empty immutable map is * returned. * * <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned * map associates the column key with the corresponding value in the * table. Changes to the returned map will update the underlying table, and * vice versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ @Override public Map<C, V> row(R rowKey) { checkNotNull(rowKey); Integer rowIndex = rowKeyToIndex.get(rowKey); return (rowIndex == null) ? ImmutableMap.<C, V>of() : new Row(rowIndex); } private class Row extends ArrayMap<C, V> { final int rowIndex; Row(int rowIndex) { super(columnKeyToIndex); this.rowIndex = rowIndex; } @Override String getKeyRole() { return "Column"; } @Override V getValue(int index) { return at(rowIndex, index); } @Override V setValue(int index, V newValue) { return set(rowIndex, index, newValue); } } /** * Returns an immutable set of the valid row keys, including those that are * associated with null values only. * * @return immutable set of row keys */ @Override public ImmutableSet<R> rowKeySet() { return rowKeyToIndex.keySet(); } private transient RowMap rowMap; @Override public Map<R, Map<C, V>> rowMap() { RowMap map = rowMap; return (map == null) ? rowMap = new RowMap() : map; } private class RowMap extends ArrayMap<R, Map<C, V>> { private RowMap() { super(rowKeyToIndex); } @Override String getKeyRole() { return "Row"; } @Override Map<C, V> getValue(int index) { return new Row(index); } @Override Map<C, V> setValue(int index, Map<C, V> newValue) { throw new UnsupportedOperationException(); } @Override public Map<C, V> put(R key, Map<C, V> value) { throw new UnsupportedOperationException(); } } /** * Returns an unmodifiable collection of all values, which may contain * duplicates. Changes to the table will update the returned collection. * * <p>The returned collection's iterator traverses the values of the first row * key, the values of the second row key, and so on. * * @return collection of values */ @Override public Collection<V> values() { return super.values(); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ArrayTable.java
Java
asf20
24,495
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkPositionIndex; import com.google.common.annotations.GwtCompatible; import java.util.ListIterator; import java.util.NoSuchElementException; /** * This class provides a skeletal implementation of the {@link ListIterator} * interface across a fixed number of elements that may be retrieved by * position. It does not support {@link #remove}, {@link #set}, or {@link #add}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractIndexedListIterator<E> extends UnmodifiableListIterator<E> { private final int size; private int position; /** * Returns the element with the specified index. This method is called by * {@link #next()}. */ protected abstract E get(int index); /** * Constructs an iterator across a sequence of the given size whose initial * position is 0. That is, the first call to {@link #next()} will return the * first element (or throw {@link NoSuchElementException} if {@code size} is * zero). * * @throws IllegalArgumentException if {@code size} is negative */ protected AbstractIndexedListIterator(int size) { this(size, 0); } /** * Constructs an iterator across a sequence of the given size with the given * initial position. That is, the first call to {@link #nextIndex()} will * return {@code position}, and the first call to {@link #next()} will return * the element at that index, if available. Calls to {@link #previous()} can * retrieve the preceding {@code position} elements. * * @throws IndexOutOfBoundsException if {@code position} is negative or is * greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ protected AbstractIndexedListIterator(int size, int position) { checkPositionIndex(position, size); this.size = size; this.position = position; } @Override public final boolean hasNext() { return position < size; } @Override public final E next() { if (!hasNext()) { throw new NoSuchElementException(); } return get(position++); } @Override public final int nextIndex() { return position; } @Override public final boolean hasPrevious() { return position > 0; } @Override public final E previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } return get(--position); } @Override public final int previousIndex() { return position - 1; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractIndexedListIterator.java
Java
asf20
3,143
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import javax.annotation.Nullable; /** * A descending wrapper around an {@code ImmutableSortedMultiset} * * @author Louis Wasserman */ @SuppressWarnings("serial") // uses writeReplace, not default serialization final class DescendingImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private final transient ImmutableSortedMultiset<E> forward; DescendingImmutableSortedMultiset(ImmutableSortedMultiset<E> forward) { this.forward = forward; } @Override public int count(@Nullable Object element) { return forward.count(element); } @Override public Entry<E> firstEntry() { return forward.lastEntry(); } @Override public Entry<E> lastEntry() { return forward.firstEntry(); } @Override public int size() { return forward.size(); } @Override public ImmutableSortedSet<E> elementSet() { return forward.elementSet().descendingSet(); } @Override Entry<E> getEntry(int index) { return forward.entrySet().asList().reverse().get(index); } @Override public ImmutableSortedMultiset<E> descendingMultiset() { return forward; } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return forward.tailMultiset(upperBound, boundType).descendingMultiset(); } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return forward.headMultiset(lowerBound, boundType).descendingMultiset(); } @Override boolean isPartialView() { return forward.isPartialView(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/DescendingImmutableSortedMultiset.java
Java
asf20
2,193
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; /** * Implementation of {@code Table} whose iteration ordering across row keys is * sorted by their natural ordering or by a supplied comparator. Note that * iterations across the columns keys for a single row key may or may not be * ordered, depending on the implementation. When rows and columns are both * sorted, it's easier to use the {@link TreeBasedTable} subclass. * * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and * {@link Map} specified by the {@link Table} interface. * * <p>Null keys and values are not supported. * * <p>See the {@link StandardTable} superclass for more information about the * behavior of this class. * * @author Jared Levy */ @GwtCompatible class StandardRowSortedTable<R, C, V> extends StandardTable<R, C, V> implements RowSortedTable<R, C, V> { /* * TODO(jlevy): Consider adding headTable, tailTable, and subTable methods, * which return a Table view with rows keys in a given range. Create a * RowSortedTable subinterface with the revised methods? */ StandardRowSortedTable(SortedMap<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { super(backingMap, factory); } private SortedMap<R, Map<C, V>> sortedBackingMap() { return (SortedMap<R, Map<C, V>>) backingMap; } /** * {@inheritDoc} * * <p>This method returns a {@link SortedSet}, instead of the {@code Set} * specified in the {@link Table} interface. */ @Override public SortedSet<R> rowKeySet() { return (SortedSet<R>) rowMap().keySet(); } /** * {@inheritDoc} * * <p>This method returns a {@link SortedMap}, instead of the {@code Map} * specified in the {@link Table} interface. */ @Override public SortedMap<R, Map<C, V>> rowMap() { return (SortedMap<R, Map<C, V>>) super.rowMap(); } @Override SortedMap<R, Map<C, V>> createRowMap() { return new RowSortedMap(); } private class RowSortedMap extends RowMap implements SortedMap<R, Map<C, V>> { @Override public SortedSet<R> keySet() { return (SortedSet<R>) super.keySet(); } @Override SortedSet<R> createKeySet() { return new Maps.SortedKeySet<R, Map<C, V>>(this); } @Override public Comparator<? super R> comparator() { return sortedBackingMap().comparator(); } @Override public R firstKey() { return sortedBackingMap().firstKey(); } @Override public R lastKey() { return sortedBackingMap().lastKey(); } @Override public SortedMap<R, Map<C, V>> headMap(R toKey) { checkNotNull(toKey); return new StandardRowSortedTable<R, C, V>( sortedBackingMap().headMap(toKey), factory).rowMap(); } @Override public SortedMap<R, Map<C, V>> subMap(R fromKey, R toKey) { checkNotNull(fromKey); checkNotNull(toKey); return new StandardRowSortedTable<R, C, V>( sortedBackingMap().subMap(fromKey, toKey), factory).rowMap(); } @Override public SortedMap<R, Map<C, V>> tailMap(R fromKey) { checkNotNull(fromKey); return new StandardRowSortedTable<R, C, V>( sortedBackingMap().tailMap(fromKey), factory).rowMap(); } } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/StandardRowSortedTable.java
Java
asf20
4,271
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; /** * An {@code Iterable} whose elements are sorted relative to a {@code Comparator}, typically * provided at creation time. * * @author Louis Wasserman */ @GwtCompatible interface SortedIterable<T> extends Iterable<T> { /** * Returns the {@code Comparator} by which the elements of this iterable are ordered, or {@code * Ordering.natural()} if the elements are ordered by their natural ordering. */ Comparator<? super T> comparator(); /** * Returns an iterator over elements of type {@code T}. The elements are returned in * nondecreasing order according to the associated {@link #comparator}. */ @Override Iterator<T> iterator(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/SortedIterable.java
Java
asf20
1,410
/* * 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.CollectPreconditions.checkRemove; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Equivalence; import com.google.common.base.Ticker; import com.google.common.collect.GenericMapMaker.NullListener; import com.google.common.collect.MapMaker.RemovalCause; import com.google.common.collect.MapMaker.RemovalListener; import com.google.common.collect.MapMaker.RemovalNotification; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractQueue; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** * The concurrent hash map implementation built by {@link MapMaker}. * * <p>This implementation is heavily derived from revision 1.96 of <a * href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>. * * @author Bob Lee * @author Charles Fry * @author Doug Lea ({@code ConcurrentHashMap}) */ class MapMakerInternalMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable { /* * The basic strategy is to subdivide the table among Segments, each of which itself is a * concurrently readable hash table. The map supports non-blocking reads and concurrent writes * across different segments. * * If a maximum size is specified, a best-effort bounding is performed per segment, using a * page-replacement algorithm to determine which entries to evict when the capacity has been * exceeded. * * The page replacement algorithm's data structures are kept casually consistent with the map. The * ordering of writes to a segment is sequentially consistent. An update to the map and recording * of reads may not be immediately reflected on the algorithm's data structures. These structures * are guarded by a lock and operations are applied in batches to avoid lock contention. The * penalty of applying the batches is spread across threads so that the amortized cost is slightly * higher than performing just the operation without enforcing the capacity constraint. * * This implementation uses a per-segment queue to record a memento of the additions, removals, * and accesses that were performed on the map. The queue is drained on writes and when it exceeds * its capacity threshold. * * The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit * rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation * operates per-segment rather than globally for increased implementation simplicity. We expect * the cache hit rate to be similar to that of a global LRU algorithm. */ // Constants /** * The maximum capacity, used if a higher value is implicitly specified by either of the * constructors with arguments. MUST be a power of two <= 1<<30 to ensure that entries are * indexable using ints. */ static final int MAXIMUM_CAPACITY = Ints.MAX_POWER_OF_TWO; /** The maximum number of segments to allow; used to bound constructor arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** Number of (unsynchronized) retries in the containsValue method. */ static final int CONTAINS_VALUE_RETRIES = 3; /** * Number of cache access operations that can be buffered per segment before the cache's recency * ordering information is updated. This is used to avoid lock contention by recording a memento * of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs. * * <p>This must be a (2^n)-1 as it is used as a mask. */ static final int DRAIN_THRESHOLD = 0x3F; /** * Maximum number of entries to be drained in a single cleanup run. This applies independently to * the cleanup queue and both reference queues. */ // TODO(fry): empirically optimize this static final int DRAIN_MAX = 16; static final long CLEANUP_EXECUTOR_DELAY_SECS = 60; // Fields private static final Logger logger = Logger.getLogger(MapMakerInternalMap.class.getName()); /** * Mask value for indexing into segments. The upper bits of a key's hash code are used to choose * the segment. */ final transient int segmentMask; /** * Shift value for indexing within segments. Helps prevent entries that end up in the same segment * from also ending up in the same bucket. */ final transient int segmentShift; /** The segments, each of which is a specialized hash table. */ final transient Segment<K, V>[] segments; /** The concurrency level. */ final int concurrencyLevel; /** Strategy for comparing keys. */ final Equivalence<Object> keyEquivalence; /** Strategy for comparing values. */ final Equivalence<Object> valueEquivalence; /** Strategy for referencing keys. */ final Strength keyStrength; /** Strategy for referencing values. */ final Strength valueStrength; /** The maximum size of this map. MapMaker.UNSET_INT if there is no maximum. */ final int maximumSize; /** How long after the last access to an entry the map will retain that entry. */ final long expireAfterAccessNanos; /** How long after the last write to an entry the map will retain that entry. */ final long expireAfterWriteNanos; /** Entries waiting to be consumed by the removal listener. */ // TODO(fry): define a new type which creates event objects and automates the clear logic final Queue<RemovalNotification<K, V>> removalNotificationQueue; /** * A listener that is invoked when an entry is removed due to expiration or garbage collection of * soft/weak entries. */ final RemovalListener<K, V> removalListener; /** Factory used to create new entries. */ final transient EntryFactory entryFactory; /** Measures time in a testable way. */ final Ticker ticker; /** * Creates a new, empty map with the specified strategy, initial capacity and concurrency level. */ MapMakerInternalMap(MapMaker builder) { concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS); keyStrength = builder.getKeyStrength(); valueStrength = builder.getValueStrength(); keyEquivalence = builder.getKeyEquivalence(); valueEquivalence = valueStrength.defaultEquivalence(); maximumSize = builder.maximumSize; expireAfterAccessNanos = builder.getExpireAfterAccessNanos(); expireAfterWriteNanos = builder.getExpireAfterWriteNanos(); entryFactory = EntryFactory.getFactory(keyStrength, expires(), evictsBySize()); ticker = builder.getTicker(); removalListener = builder.getRemovalListener(); removalNotificationQueue = (removalListener == NullListener.INSTANCE) ? MapMakerInternalMap.<RemovalNotification<K, V>>discardingQueue() : new ConcurrentLinkedQueue<RemovalNotification<K, V>>(); int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY); if (evictsBySize()) { initialCapacity = Math.min(initialCapacity, maximumSize); } // Find power-of-two sizes best matching arguments. Constraints: // (segmentCount <= maximumSize) // && (concurrencyLevel > maximumSize || segmentCount > concurrencyLevel) int segmentShift = 0; int segmentCount = 1; while (segmentCount < concurrencyLevel && (!evictsBySize() || segmentCount * 2 <= maximumSize)) { ++segmentShift; segmentCount <<= 1; } this.segmentShift = 32 - segmentShift; segmentMask = segmentCount - 1; this.segments = newSegmentArray(segmentCount); int segmentCapacity = initialCapacity / segmentCount; if (segmentCapacity * segmentCount < initialCapacity) { ++segmentCapacity; } int segmentSize = 1; while (segmentSize < segmentCapacity) { segmentSize <<= 1; } if (evictsBySize()) { // Ensure sum of segment max sizes = overall max size int maximumSegmentSize = maximumSize / segmentCount + 1; int remainder = maximumSize % segmentCount; for (int i = 0; i < this.segments.length; ++i) { if (i == remainder) { maximumSegmentSize--; } this.segments[i] = createSegment(segmentSize, maximumSegmentSize); } } else { for (int i = 0; i < this.segments.length; ++i) { this.segments[i] = createSegment(segmentSize, MapMaker.UNSET_INT); } } } boolean evictsBySize() { return maximumSize != MapMaker.UNSET_INT; } boolean expires() { return expiresAfterWrite() || expiresAfterAccess(); } boolean expiresAfterWrite() { return expireAfterWriteNanos > 0; } boolean expiresAfterAccess() { return expireAfterAccessNanos > 0; } boolean usesKeyReferences() { return keyStrength != Strength.STRONG; } boolean usesValueReferences() { return valueStrength != Strength.STRONG; } enum Strength { /* * TODO(kevinb): If we strongly reference the value and aren't computing, we needn't wrap the * value. This could save ~8 bytes per entry. */ STRONG { @Override <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) { return new StrongValueReference<K, V>(value); } @Override Equivalence<Object> defaultEquivalence() { return Equivalence.equals(); } }, SOFT { @Override <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) { return new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry); } @Override Equivalence<Object> defaultEquivalence() { return Equivalence.identity(); } }, WEAK { @Override <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) { return new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry); } @Override Equivalence<Object> defaultEquivalence() { return Equivalence.identity(); } }; /** * Creates a reference for the given value according to this value strength. */ abstract <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value); /** * Returns the default equivalence strategy used to compare and hash keys or values referenced * at this strength. This strategy will be used unless the user explicitly specifies an * alternate strategy. */ abstract Equivalence<Object> defaultEquivalence(); } /** * Creates new entries. */ enum EntryFactory { STRONG { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new StrongEntry<K, V>(key, hash, next); } }, STRONG_EXPIRABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new StrongExpirableEntry<K, V>(key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext); copyExpirableEntry(original, newEntry); return newEntry; } }, STRONG_EVICTABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new StrongEvictableEntry<K, V>(key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext); copyEvictableEntry(original, newEntry); return newEntry; } }, STRONG_EXPIRABLE_EVICTABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new StrongExpirableEvictableEntry<K, V>(key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext); copyExpirableEntry(original, newEntry); copyEvictableEntry(original, newEntry); return newEntry; } }, WEAK { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new WeakEntry<K, V>(segment.keyReferenceQueue, key, hash, next); } }, WEAK_EXPIRABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new WeakExpirableEntry<K, V>(segment.keyReferenceQueue, key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext); copyExpirableEntry(original, newEntry); return newEntry; } }, WEAK_EVICTABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new WeakEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext); copyEvictableEntry(original, newEntry); return newEntry; } }, WEAK_EXPIRABLE_EVICTABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new WeakExpirableEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext); copyExpirableEntry(original, newEntry); copyEvictableEntry(original, newEntry); return newEntry; } }; /** * Masks used to compute indices in the following table. */ static final int EXPIRABLE_MASK = 1; static final int EVICTABLE_MASK = 2; /** * Look-up table for factories. First dimension is the reference type. The second dimension is * the result of OR-ing the feature masks. */ static final EntryFactory[][] factories = { { STRONG, STRONG_EXPIRABLE, STRONG_EVICTABLE, STRONG_EXPIRABLE_EVICTABLE }, {}, // no support for SOFT keys { WEAK, WEAK_EXPIRABLE, WEAK_EVICTABLE, WEAK_EXPIRABLE_EVICTABLE } }; static EntryFactory getFactory(Strength keyStrength, boolean expireAfterWrite, boolean evictsBySize) { int flags = (expireAfterWrite ? EXPIRABLE_MASK : 0) | (evictsBySize ? EVICTABLE_MASK : 0); return factories[keyStrength.ordinal()][flags]; } /** * Creates a new entry. * * @param segment to create the entry for * @param key of the entry * @param hash of the key * @param next entry in the same bucket */ abstract <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next); /** * Copies an entry, assigning it a new {@code next} entry. * * @param original the entry to copy * @param newNext entry in the same bucket */ @GuardedBy("Segment.this") <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { return newEntry(segment, original.getKey(), original.getHash(), newNext); } @GuardedBy("Segment.this") <K, V> void copyExpirableEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) { // TODO(fry): when we link values instead of entries this method can go // away, as can connectExpirables, nullifyExpirable. newEntry.setExpirationTime(original.getExpirationTime()); connectExpirables(original.getPreviousExpirable(), newEntry); connectExpirables(newEntry, original.getNextExpirable()); nullifyExpirable(original); } @GuardedBy("Segment.this") <K, V> void copyEvictableEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) { // TODO(fry): when we link values instead of entries this method can go // away, as can connectEvictables, nullifyEvictable. connectEvictables(original.getPreviousEvictable(), newEntry); connectEvictables(newEntry, original.getNextEvictable()); nullifyEvictable(original); } } /** * A reference to a value. */ interface ValueReference<K, V> { /** * Gets the value. Does not block or throw exceptions. */ V get(); /** * Waits for a value that may still be computing. Unlike get(), this method can block (in the * case of FutureValueReference). * * @throws ExecutionException if the computing thread throws an exception */ V waitForValue() throws ExecutionException; /** * Returns the entry associated with this value reference, or {@code null} if this value * reference is independent of any entry. */ ReferenceEntry<K, V> getEntry(); /** * Creates a copy of this reference for the given entry. * * <p>{@code value} may be null only for a loading reference. */ ValueReference<K, V> copyFor( ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry); /** * Clears this reference object. * * @param newValue the new value reference which will replace this one; this is only used during * computation to immediately notify blocked threads of the new value */ void clear(@Nullable ValueReference<K, V> newValue); /** * Returns {@code true} if the value type is a computing reference (regardless of whether or not * computation has completed). This is necessary to distiguish between partially-collected * entries and computing entries, which need to be cleaned up differently. */ boolean isComputingReference(); } /** * Placeholder. Indicates that the value hasn't been set yet. */ static final ValueReference<Object, Object> UNSET = new ValueReference<Object, Object>() { @Override public Object get() { return null; } @Override public ReferenceEntry<Object, Object> getEntry() { return null; } @Override public ValueReference<Object, Object> copyFor(ReferenceQueue<Object> queue, @Nullable Object value, ReferenceEntry<Object, Object> entry) { return this; } @Override public boolean isComputingReference() { return false; } @Override public Object waitForValue() { return null; } @Override public void clear(ValueReference<Object, Object> newValue) {} }; /** * Singleton placeholder that indicates a value is being computed. */ @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static <K, V> ValueReference<K, V> unset() { return (ValueReference<K, V>) UNSET; } /** * An entry in a reference map. * * Entries in the map can be in the following states: * * Valid: * - Live: valid key/value are set * - Computing: computation is pending * * Invalid: * - Expired: time expired (key/value may still be set) * - Collected: key/value was partially collected, but not yet cleaned up */ interface ReferenceEntry<K, V> { /** * Gets the value reference from this entry. */ ValueReference<K, V> getValueReference(); /** * Sets the value reference for this entry. */ void setValueReference(ValueReference<K, V> valueReference); /** * Gets the next entry in the chain. */ ReferenceEntry<K, V> getNext(); /** * Gets the entry's hash. */ int getHash(); /** * Gets the key for this entry. */ K getKey(); /* * Used by entries that are expirable. Expirable entries are maintained in a doubly-linked list. * New entries are added at the tail of the list at write time; stale entries are expired from * the head of the list. */ /** * Gets the entry expiration time in ns. */ long getExpirationTime(); /** * Sets the entry expiration time in ns. */ void setExpirationTime(long time); /** * Gets the next entry in the recency list. */ ReferenceEntry<K, V> getNextExpirable(); /** * Sets the next entry in the recency list. */ void setNextExpirable(ReferenceEntry<K, V> next); /** * Gets the previous entry in the recency list. */ ReferenceEntry<K, V> getPreviousExpirable(); /** * Sets the previous entry in the recency list. */ void setPreviousExpirable(ReferenceEntry<K, V> previous); /* * Implemented by entries that are evictable. Evictable entries are maintained in a * doubly-linked list. New entries are added at the tail of the list at write time and stale * entries are expired from the head of the list. */ /** * Gets the next entry in the recency list. */ ReferenceEntry<K, V> getNextEvictable(); /** * Sets the next entry in the recency list. */ void setNextEvictable(ReferenceEntry<K, V> next); /** * Gets the previous entry in the recency list. */ ReferenceEntry<K, V> getPreviousEvictable(); /** * Sets the previous entry in the recency list. */ void setPreviousEvictable(ReferenceEntry<K, V> previous); } private enum NullEntry implements ReferenceEntry<Object, Object> { INSTANCE; @Override public ValueReference<Object, Object> getValueReference() { return null; } @Override public void setValueReference(ValueReference<Object, Object> valueReference) {} @Override public ReferenceEntry<Object, Object> getNext() { return null; } @Override public int getHash() { return 0; } @Override public Object getKey() { return null; } @Override public long getExpirationTime() { return 0; } @Override public void setExpirationTime(long time) {} @Override public ReferenceEntry<Object, Object> getNextExpirable() { return this; } @Override public void setNextExpirable(ReferenceEntry<Object, Object> next) {} @Override public ReferenceEntry<Object, Object> getPreviousExpirable() { return this; } @Override public void setPreviousExpirable(ReferenceEntry<Object, Object> previous) {} @Override public ReferenceEntry<Object, Object> getNextEvictable() { return this; } @Override public void setNextEvictable(ReferenceEntry<Object, Object> next) {} @Override public ReferenceEntry<Object, Object> getPreviousEvictable() { return this; } @Override public void setPreviousEvictable(ReferenceEntry<Object, Object> previous) {} } abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> { @Override public ValueReference<K, V> getValueReference() { throw new UnsupportedOperationException(); } @Override public void setValueReference(ValueReference<K, V> valueReference) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNext() { throw new UnsupportedOperationException(); } @Override public int getHash() { throw new UnsupportedOperationException(); } @Override public K getKey() { throw new UnsupportedOperationException(); } @Override public long getExpirationTime() { throw new UnsupportedOperationException(); } @Override public void setExpirationTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextExpirable() { throw new UnsupportedOperationException(); } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousExpirable() { throw new UnsupportedOperationException(); } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextEvictable() { throw new UnsupportedOperationException(); } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousEvictable() { throw new UnsupportedOperationException(); } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } } @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static <K, V> ReferenceEntry<K, V> nullEntry() { return (ReferenceEntry<K, V>) NullEntry.INSTANCE; } static final Queue<? extends Object> DISCARDING_QUEUE = new AbstractQueue<Object>() { @Override public boolean offer(Object o) { return true; } @Override public Object peek() { return null; } @Override public Object poll() { return null; } @Override public int size() { return 0; } @Override public Iterator<Object> iterator() { return Iterators.emptyIterator(); } }; /** * Queue that discards all elements. */ @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static <E> Queue<E> discardingQueue() { return (Queue) DISCARDING_QUEUE; } /* * Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins! * To maintain this code, make a change for the strong reference type. Then, cut and paste, and * replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that * strong entries store the key reference directly while soft and weak entries delegate to their * respective superclasses. */ /** * Used for strongly-referenced keys. */ static class StrongEntry<K, V> implements ReferenceEntry<K, V> { final K key; StrongEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) { this.key = key; this.hash = hash; this.next = next; } @Override public K getKey() { return this.key; } // null expiration @Override public long getExpirationTime() { throw new UnsupportedOperationException(); } @Override public void setExpirationTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextExpirable() { throw new UnsupportedOperationException(); } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousExpirable() { throw new UnsupportedOperationException(); } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // null eviction @Override public ReferenceEntry<K, V> getNextEvictable() { throw new UnsupportedOperationException(); } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousEvictable() { throw new UnsupportedOperationException(); } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // The code below is exactly the same for each entry type. final int hash; final ReferenceEntry<K, V> next; volatile ValueReference<K, V> valueReference = unset(); @Override public ValueReference<K, V> getValueReference() { return valueReference; } @Override public void setValueReference(ValueReference<K, V> valueReference) { ValueReference<K, V> previous = this.valueReference; this.valueReference = valueReference; previous.clear(valueReference); } @Override public int getHash() { return hash; } @Override public ReferenceEntry<K, V> getNext() { return next; } } static final class StrongExpirableEntry<K, V> extends StrongEntry<K, V> implements ReferenceEntry<K, V> { StrongExpirableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(key, hash, next); } // The code below is exactly the same for each expirable entry type. volatile long time = Long.MAX_VALUE; @Override public long getExpirationTime() { return time; } @Override public void setExpirationTime(long time) { this.time = time; } @GuardedBy("Segment.this") ReferenceEntry<K, V> nextExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } } static final class StrongEvictableEntry<K, V> extends StrongEntry<K, V> implements ReferenceEntry<K, V> { StrongEvictableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(key, hash, next); } // The code below is exactly the same for each evictable entry type. @GuardedBy("Segment.this") ReferenceEntry<K, V> nextEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } } static final class StrongExpirableEvictableEntry<K, V> extends StrongEntry<K, V> implements ReferenceEntry<K, V> { StrongExpirableEvictableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(key, hash, next); } // The code below is exactly the same for each expirable entry type. volatile long time = Long.MAX_VALUE; @Override public long getExpirationTime() { return time; } @Override public void setExpirationTime(long time) { this.time = time; } @GuardedBy("Segment.this") ReferenceEntry<K, V> nextExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } // The code below is exactly the same for each evictable entry type. @GuardedBy("Segment.this") ReferenceEntry<K, V> nextEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } } /** * Used for softly-referenced keys. */ static class SoftEntry<K, V> extends SoftReference<K> implements ReferenceEntry<K, V> { SoftEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(key, queue); this.hash = hash; this.next = next; } @Override public K getKey() { return get(); } // null expiration @Override public long getExpirationTime() { throw new UnsupportedOperationException(); } @Override public void setExpirationTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextExpirable() { throw new UnsupportedOperationException(); } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousExpirable() { throw new UnsupportedOperationException(); } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // null eviction @Override public ReferenceEntry<K, V> getNextEvictable() { throw new UnsupportedOperationException(); } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousEvictable() { throw new UnsupportedOperationException(); } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // The code below is exactly the same for each entry type. final int hash; final ReferenceEntry<K, V> next; volatile ValueReference<K, V> valueReference = unset(); @Override public ValueReference<K, V> getValueReference() { return valueReference; } @Override public void setValueReference(ValueReference<K, V> valueReference) { ValueReference<K, V> previous = this.valueReference; this.valueReference = valueReference; previous.clear(valueReference); } @Override public int getHash() { return hash; } @Override public ReferenceEntry<K, V> getNext() { return next; } } static final class SoftExpirableEntry<K, V> extends SoftEntry<K, V> implements ReferenceEntry<K, V> { SoftExpirableEntry( ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each expirable entry type. volatile long time = Long.MAX_VALUE; @Override public long getExpirationTime() { return time; } @Override public void setExpirationTime(long time) { this.time = time; } @GuardedBy("Segment.this") ReferenceEntry<K, V> nextExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } } static final class SoftEvictableEntry<K, V> extends SoftEntry<K, V> implements ReferenceEntry<K, V> { SoftEvictableEntry( ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each evictable entry type. @GuardedBy("Segment.this") ReferenceEntry<K, V> nextEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } } static final class SoftExpirableEvictableEntry<K, V> extends SoftEntry<K, V> implements ReferenceEntry<K, V> { SoftExpirableEvictableEntry( ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each expirable entry type. volatile long time = Long.MAX_VALUE; @Override public long getExpirationTime() { return time; } @Override public void setExpirationTime(long time) { this.time = time; } @GuardedBy("Segment.this") ReferenceEntry<K, V> nextExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } // The code below is exactly the same for each evictable entry type. @GuardedBy("Segment.this") ReferenceEntry<K, V> nextEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } } /** * Used for weakly-referenced keys. */ static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> { WeakEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(key, queue); this.hash = hash; this.next = next; } @Override public K getKey() { return get(); } // null expiration @Override public long getExpirationTime() { throw new UnsupportedOperationException(); } @Override public void setExpirationTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextExpirable() { throw new UnsupportedOperationException(); } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousExpirable() { throw new UnsupportedOperationException(); } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // null eviction @Override public ReferenceEntry<K, V> getNextEvictable() { throw new UnsupportedOperationException(); } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousEvictable() { throw new UnsupportedOperationException(); } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // The code below is exactly the same for each entry type. final int hash; final ReferenceEntry<K, V> next; volatile ValueReference<K, V> valueReference = unset(); @Override public ValueReference<K, V> getValueReference() { return valueReference; } @Override public void setValueReference(ValueReference<K, V> valueReference) { ValueReference<K, V> previous = this.valueReference; this.valueReference = valueReference; previous.clear(valueReference); } @Override public int getHash() { return hash; } @Override public ReferenceEntry<K, V> getNext() { return next; } } static final class WeakExpirableEntry<K, V> extends WeakEntry<K, V> implements ReferenceEntry<K, V> { WeakExpirableEntry( ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each expirable entry type. volatile long time = Long.MAX_VALUE; @Override public long getExpirationTime() { return time; } @Override public void setExpirationTime(long time) { this.time = time; } @GuardedBy("Segment.this") ReferenceEntry<K, V> nextExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } } static final class WeakEvictableEntry<K, V> extends WeakEntry<K, V> implements ReferenceEntry<K, V> { WeakEvictableEntry( ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each evictable entry type. @GuardedBy("Segment.this") ReferenceEntry<K, V> nextEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } } static final class WeakExpirableEvictableEntry<K, V> extends WeakEntry<K, V> implements ReferenceEntry<K, V> { WeakExpirableEvictableEntry( ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each expirable entry type. volatile long time = Long.MAX_VALUE; @Override public long getExpirationTime() { return time; } @Override public void setExpirationTime(long time) { this.time = time; } @GuardedBy("Segment.this") ReferenceEntry<K, V> nextExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousExpirable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } // The code below is exactly the same for each evictable entry type. @GuardedBy("Segment.this") ReferenceEntry<K, V> nextEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } @GuardedBy("Segment.this") ReferenceEntry<K, V> previousEvictable = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } } /** * References a weak value. */ static final class WeakValueReference<K, V> extends WeakReference<V> implements ValueReference<K, V> { final ReferenceEntry<K, V> entry; WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) { super(referent, queue); this.entry = entry; } @Override public ReferenceEntry<K, V> getEntry() { return entry; } @Override public void clear(ValueReference<K, V> newValue) { clear(); } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return new WeakValueReference<K, V>(queue, value, entry); } @Override public boolean isComputingReference() { return false; } @Override public V waitForValue() { return get(); } } /** * References a soft value. */ static final class SoftValueReference<K, V> extends SoftReference<V> implements ValueReference<K, V> { final ReferenceEntry<K, V> entry; SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) { super(referent, queue); this.entry = entry; } @Override public ReferenceEntry<K, V> getEntry() { return entry; } @Override public void clear(ValueReference<K, V> newValue) { clear(); } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return new SoftValueReference<K, V>(queue, value, entry); } @Override public boolean isComputingReference() { return false; } @Override public V waitForValue() { return get(); } } /** * References a strong value. */ static final class StrongValueReference<K, V> implements ValueReference<K, V> { final V referent; StrongValueReference(V referent) { this.referent = referent; } @Override public V get() { return referent; } @Override public ReferenceEntry<K, V> getEntry() { return null; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return this; } @Override public boolean isComputingReference() { return false; } @Override public V waitForValue() { return get(); } @Override public void clear(ValueReference<K, V> newValue) {} } /** * Applies a supplemental hash function to a given hash code, which defends against poor quality * hash functions. This is critical when the concurrent hash map uses power-of-two length hash * tables, that otherwise encounter collisions for hash codes that do not differ in lower or * upper bits. * * @param h hash code */ static int rehash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. // TODO(kevinb): use Hashing/move this to Hashing? h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); } /** * This method is a convenience for testing. Code should call {@link Segment#newEntry} directly. */ @GuardedBy("Segment.this") @VisibleForTesting ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) { return segmentFor(hash).newEntry(key, hash, next); } /** * This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly. */ @GuardedBy("Segment.this") @VisibleForTesting ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { int hash = original.getHash(); return segmentFor(hash).copyEntry(original, newNext); } /** * This method is a convenience for testing. Code should call {@link Segment#setValue} instead. */ @GuardedBy("Segment.this") @VisibleForTesting ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value) { int hash = entry.getHash(); return valueStrength.referenceValue(segmentFor(hash), entry, value); } int hash(Object key) { int h = keyEquivalence.hash(key); return rehash(h); } void reclaimValue(ValueReference<K, V> valueReference) { ReferenceEntry<K, V> entry = valueReference.getEntry(); int hash = entry.getHash(); segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference); } void reclaimKey(ReferenceEntry<K, V> entry) { int hash = entry.getHash(); segmentFor(hash).reclaimKey(entry, hash); } /** * This method is a convenience for testing. Code should call {@link Segment#getLiveValue} * instead. */ @VisibleForTesting boolean isLive(ReferenceEntry<K, V> entry) { return segmentFor(entry.getHash()).getLiveValue(entry) != null; } /** * Returns the segment that should be used for a key with the given hash. * * @param hash the hash code for the key * @return the segment */ Segment<K, V> segmentFor(int hash) { // TODO(fry): Lazily create segments? return segments[(hash >>> segmentShift) & segmentMask]; } Segment<K, V> createSegment(int initialCapacity, int maxSegmentSize) { return new Segment<K, V>(this, initialCapacity, maxSegmentSize); } /** * Gets the value from an entry. Returns {@code null} if the entry is invalid, * partially-collected, computing, or expired. Unlike {@link Segment#getLiveValue} this method * does not attempt to clean up stale entries. */ V getLiveValue(ReferenceEntry<K, V> entry) { if (entry.getKey() == null) { return null; } V value = entry.getValueReference().get(); if (value == null) { return null; } if (expires() && isExpired(entry)) { return null; } return value; } // expiration /** * Returns {@code true} if the entry has expired. */ boolean isExpired(ReferenceEntry<K, V> entry) { return isExpired(entry, ticker.read()); } /** * Returns {@code true} if the entry has expired. */ boolean isExpired(ReferenceEntry<K, V> entry, long now) { // if the expiration time had overflowed, this "undoes" the overflow return now - entry.getExpirationTime() > 0; } @GuardedBy("Segment.this") static <K, V> void connectExpirables(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) { previous.setNextExpirable(next); next.setPreviousExpirable(previous); } @GuardedBy("Segment.this") static <K, V> void nullifyExpirable(ReferenceEntry<K, V> nulled) { ReferenceEntry<K, V> nullEntry = nullEntry(); nulled.setNextExpirable(nullEntry); nulled.setPreviousExpirable(nullEntry); } // eviction /** * Notifies listeners that an entry has been automatically removed due to expiration, eviction, * or eligibility for garbage collection. This should be called every time expireEntries or * evictEntry is called (once the lock is released). */ void processPendingNotifications() { RemovalNotification<K, V> notification; while ((notification = removalNotificationQueue.poll()) != null) { try { removalListener.onRemoval(notification); } catch (Exception e) { logger.log(Level.WARNING, "Exception thrown by removal listener", e); } } } /** Links the evitables together. */ @GuardedBy("Segment.this") static <K, V> void connectEvictables(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) { previous.setNextEvictable(next); next.setPreviousEvictable(previous); } @GuardedBy("Segment.this") static <K, V> void nullifyEvictable(ReferenceEntry<K, V> nulled) { ReferenceEntry<K, V> nullEntry = nullEntry(); nulled.setNextEvictable(nullEntry); nulled.setPreviousEvictable(nullEntry); } @SuppressWarnings("unchecked") final Segment<K, V>[] newSegmentArray(int ssize) { return new Segment[ssize]; } // Inner Classes /** * Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock * opportunistically, just to simplify some locking and avoid separate construction. */ @SuppressWarnings("serial") // This class is never serialized. static class Segment<K, V> extends ReentrantLock { /* * TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class. * It will require more memory but will reduce indirection. */ /* * Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can * be read without locking. Next fields of nodes are immutable (final). All list additions are * performed at the front of each bin. This makes it easy to check changes, and also fast to * traverse. When nodes would otherwise be changed, new nodes are created to replace them. This * works well for hash tables since the bin lists tend to be short. (The average length is less * than two.) * * Read operations can thus proceed without locking, but rely on selected uses of volatiles to * ensure that completed write operations performed by other threads are noticed. For most * purposes, the "count" field, tracking the number of elements, serves as that volatile * variable ensuring visibility. This is convenient because this field needs to be read in many * read operations anyway: * * - All (unsynchronized) read operations must first read the "count" field, and should not * look at table entries if it is 0. * * - All (synchronized) write operations should write to the "count" field after structurally * changing any bin. The operations must not take any action that could even momentarily * cause a concurrent read operation to see inconsistent data. This is made easier by the * nature of the read operations in Map. For example, no operation can reveal that the table * has grown but the threshold has not yet been updated, so there are no atomicity requirements * for this with respect to reads. * * As a guide, all critical volatile reads and writes to the count field are marked in code * comments. */ final MapMakerInternalMap<K, V> map; /** * The number of live elements in this segment's region. This does not include unset elements * which are awaiting cleanup. */ volatile int count; /** * Number of updates that alter the size of the table. This is used during bulk-read methods to * make sure they see a consistent snapshot: If modCounts change during a traversal of segments * computing size or checking containsValue, then we might have an inconsistent view of state * so (usually) must retry. */ int modCount; /** * The table is expanded when its size exceeds this threshold. (The value of this field is * always {@code (int) (capacity * 0.75)}.) */ int threshold; /** * The per-segment table. */ volatile AtomicReferenceArray<ReferenceEntry<K, V>> table; /** * The maximum size of this map. MapMaker.UNSET_INT if there is no maximum. */ final int maxSegmentSize; /** * The key reference queue contains entries whose keys have been garbage collected, and which * need to be cleaned up internally. */ final ReferenceQueue<K> keyReferenceQueue; /** * The value reference queue contains value references whose values have been garbage collected, * and which need to be cleaned up internally. */ final ReferenceQueue<V> valueReferenceQueue; /** * The recency queue is used to record which entries were accessed for updating the eviction * list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is * crossed or a write occurs on the segment. */ final Queue<ReferenceEntry<K, V>> recencyQueue; /** * A counter of the number of reads since the last write, used to drain queues on a small * fraction of read operations. */ final AtomicInteger readCount = new AtomicInteger(); /** * A queue of elements currently in the map, ordered by access time. Elements are added to the * tail of the queue on access/write. */ @GuardedBy("Segment.this") final Queue<ReferenceEntry<K, V>> evictionQueue; /** * A queue of elements currently in the map, ordered by expiration time (either access or write * time). Elements are added to the tail of the queue on access/write. */ @GuardedBy("Segment.this") final Queue<ReferenceEntry<K, V>> expirationQueue; Segment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) { this.map = map; this.maxSegmentSize = maxSegmentSize; initTable(newEntryArray(initialCapacity)); keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<K>() : null; valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<V>() : null; recencyQueue = (map.evictsBySize() || map.expiresAfterAccess()) ? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>() : MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue(); evictionQueue = map.evictsBySize() ? new EvictionQueue<K, V>() : MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue(); expirationQueue = map.expires() ? new ExpirationQueue<K, V>() : MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue(); } AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) { return new AtomicReferenceArray<ReferenceEntry<K, V>>(size); } void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) { this.threshold = newTable.length() * 3 / 4; // 0.75 if (this.threshold == maxSegmentSize) { // prevent spurious expansion before eviction this.threshold++; } this.table = newTable; } @GuardedBy("Segment.this") ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) { return map.entryFactory.newEntry(this, key, hash, next); } /** * Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry, * or {@code null} if {@code original} was already garbage collected. */ @GuardedBy("Segment.this") ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { if (original.getKey() == null) { // key collected return null; } ValueReference<K, V> valueReference = original.getValueReference(); V value = valueReference.get(); if ((value == null) && !valueReference.isComputingReference()) { // value collected return null; } ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext); newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry)); return newEntry; } /** * Sets a new value of an entry. Adds newly created entries at the end of the expiration queue. */ @GuardedBy("Segment.this") void setValue(ReferenceEntry<K, V> entry, V value) { ValueReference<K, V> valueReference = map.valueStrength.referenceValue(this, entry, value); entry.setValueReference(valueReference); recordWrite(entry); } // reference queues, for garbage collection cleanup /** * Cleanup collected entries when the lock is available. */ void tryDrainReferenceQueues() { if (tryLock()) { try { drainReferenceQueues(); } finally { unlock(); } } } /** * Drain the key and value reference queues, cleaning up internal entries containing garbage * collected keys or values. */ @GuardedBy("Segment.this") void drainReferenceQueues() { if (map.usesKeyReferences()) { drainKeyReferenceQueue(); } if (map.usesValueReferences()) { drainValueReferenceQueue(); } } @GuardedBy("Segment.this") void drainKeyReferenceQueue() { Reference<? extends K> ref; int i = 0; while ((ref = keyReferenceQueue.poll()) != null) { @SuppressWarnings("unchecked") ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref; map.reclaimKey(entry); if (++i == DRAIN_MAX) { break; } } } @GuardedBy("Segment.this") void drainValueReferenceQueue() { Reference<? extends V> ref; int i = 0; while ((ref = valueReferenceQueue.poll()) != null) { @SuppressWarnings("unchecked") ValueReference<K, V> valueReference = (ValueReference<K, V>) ref; map.reclaimValue(valueReference); if (++i == DRAIN_MAX) { break; } } } /** * Clears all entries from the key and value reference queues. */ void clearReferenceQueues() { if (map.usesKeyReferences()) { clearKeyReferenceQueue(); } if (map.usesValueReferences()) { clearValueReferenceQueue(); } } void clearKeyReferenceQueue() { while (keyReferenceQueue.poll() != null) {} } void clearValueReferenceQueue() { while (valueReferenceQueue.poll() != null) {} } // recency queue, shared by expiration and eviction /** * Records the relative order in which this read was performed by adding {@code entry} to the * recency queue. At write-time, or when the queue is full past the threshold, the queue will * be drained and the entries therein processed. * * <p>Note: locked reads should use {@link #recordLockedRead}. */ void recordRead(ReferenceEntry<K, V> entry) { if (map.expiresAfterAccess()) { recordExpirationTime(entry, map.expireAfterAccessNanos); } recencyQueue.add(entry); } /** * Updates the eviction metadata that {@code entry} was just read. This currently amounts to * adding {@code entry} to relevant eviction lists. * * <p>Note: this method should only be called under lock, as it directly manipulates the * eviction queues. Unlocked reads should use {@link #recordRead}. */ @GuardedBy("Segment.this") void recordLockedRead(ReferenceEntry<K, V> entry) { evictionQueue.add(entry); if (map.expiresAfterAccess()) { recordExpirationTime(entry, map.expireAfterAccessNanos); expirationQueue.add(entry); } } /** * Updates eviction metadata that {@code entry} was just written. This currently amounts to * adding {@code entry} to relevant eviction lists. */ @GuardedBy("Segment.this") void recordWrite(ReferenceEntry<K, V> entry) { // we are already under lock, so drain the recency queue immediately drainRecencyQueue(); evictionQueue.add(entry); if (map.expires()) { // currently MapMaker ensures that expireAfterWrite and // expireAfterAccess are mutually exclusive long expiration = map.expiresAfterAccess() ? map.expireAfterAccessNanos : map.expireAfterWriteNanos; recordExpirationTime(entry, expiration); expirationQueue.add(entry); } } /** * Drains the recency queue, updating eviction metadata that the entries therein were read in * the specified relative order. This currently amounts to adding them to relevant eviction * lists (accounting for the fact that they could have been removed from the map since being * added to the recency queue). */ @GuardedBy("Segment.this") void drainRecencyQueue() { ReferenceEntry<K, V> e; while ((e = recencyQueue.poll()) != null) { // An entry may be in the recency queue despite it being removed from // the map . This can occur when the entry was concurrently read while a // writer is removing it from the segment or after a clear has removed // all of the segment's entries. if (evictionQueue.contains(e)) { evictionQueue.add(e); } if (map.expiresAfterAccess() && expirationQueue.contains(e)) { expirationQueue.add(e); } } } // expiration void recordExpirationTime(ReferenceEntry<K, V> entry, long expirationNanos) { // might overflow, but that's okay (see isExpired()) entry.setExpirationTime(map.ticker.read() + expirationNanos); } /** * Cleanup expired entries when the lock is available. */ void tryExpireEntries() { if (tryLock()) { try { expireEntries(); } finally { unlock(); // don't call postWriteCleanup as we're in a read } } } @GuardedBy("Segment.this") void expireEntries() { drainRecencyQueue(); if (expirationQueue.isEmpty()) { // There's no point in calling nanoTime() if we have no entries to // expire. return; } long now = map.ticker.read(); ReferenceEntry<K, V> e; while ((e = expirationQueue.peek()) != null && map.isExpired(e, now)) { if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) { throw new AssertionError(); } } } // eviction void enqueueNotification(ReferenceEntry<K, V> entry, RemovalCause cause) { enqueueNotification(entry.getKey(), entry.getHash(), entry.getValueReference().get(), cause); } void enqueueNotification(@Nullable K key, int hash, @Nullable V value, RemovalCause cause) { if (map.removalNotificationQueue != DISCARDING_QUEUE) { RemovalNotification<K, V> notification = new RemovalNotification<K, V>(key, value, cause); map.removalNotificationQueue.offer(notification); } } /** * Performs eviction if the segment is full. This should only be called prior to adding a new * entry and increasing {@code count}. * * @return {@code true} if eviction occurred */ @GuardedBy("Segment.this") boolean evictEntries() { if (map.evictsBySize() && count >= maxSegmentSize) { drainRecencyQueue(); ReferenceEntry<K, V> e = evictionQueue.remove(); if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) { throw new AssertionError(); } return true; } return false; } /** * Returns first entry of bin for given hash. */ ReferenceEntry<K, V> getFirst(int hash) { // read this volatile field only once AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; return table.get(hash & (table.length() - 1)); } // Specialized implementations of map methods ReferenceEntry<K, V> getEntry(Object key, int hash) { if (count != 0) { // read-volatile for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) { if (e.getHash() != hash) { continue; } K entryKey = e.getKey(); if (entryKey == null) { tryDrainReferenceQueues(); continue; } if (map.keyEquivalence.equivalent(key, entryKey)) { return e; } } } return null; } ReferenceEntry<K, V> getLiveEntry(Object key, int hash) { ReferenceEntry<K, V> e = getEntry(key, hash); if (e == null) { return null; } else if (map.expires() && map.isExpired(e)) { tryExpireEntries(); return null; } return e; } V get(Object key, int hash) { try { ReferenceEntry<K, V> e = getLiveEntry(key, hash); if (e == null) { return null; } V value = e.getValueReference().get(); if (value != null) { recordRead(e); } else { tryDrainReferenceQueues(); } return value; } finally { postReadCleanup(); } } boolean containsKey(Object key, int hash) { try { if (count != 0) { // read-volatile ReferenceEntry<K, V> e = getLiveEntry(key, hash); if (e == null) { return false; } return e.getValueReference().get() != null; } return false; } finally { postReadCleanup(); } } /** * This method is a convenience for testing. Code should call {@link * MapMakerInternalMap#containsValue} directly. */ @VisibleForTesting boolean containsValue(Object value) { try { if (count != 0) { // read-volatile AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int length = table.length(); for (int i = 0; i < length; ++i) { for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) { V entryValue = getLiveValue(e); if (entryValue == null) { continue; } if (map.valueEquivalence.equivalent(value, entryValue)) { return true; } } } } return false; } finally { postReadCleanup(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { preWriteCleanup(); int newCount = this.count + 1; if (newCount > this.threshold) { // ensure capacity expand(); newCount = this.count + 1; } AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); // Look for an existing entry. for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { // We found an existing entry. ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); if (entryValue == null) { ++modCount; setValue(e, value); if (!valueReference.isComputingReference()) { enqueueNotification(key, hash, entryValue, RemovalCause.COLLECTED); newCount = this.count; // count remains unchanged } else if (evictEntries()) { // evictEntries after setting new value newCount = this.count + 1; } this.count = newCount; // write-volatile return null; } else if (onlyIfAbsent) { // Mimic // "if (!map.containsKey(key)) ... // else return map.get(key); recordLockedRead(e); return entryValue; } else { // clobber existing entry, count remains unchanged ++modCount; enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED); setValue(e, value); return entryValue; } } } // Create a new entry. ++modCount; ReferenceEntry<K, V> newEntry = newEntry(key, hash, first); setValue(newEntry, value); table.set(index, newEntry); if (evictEntries()) { // evictEntries after setting new value newCount = this.count + 1; } this.count = newCount; // write-volatile return null; } finally { unlock(); postWriteCleanup(); } } /** * Expands the table if possible. */ @GuardedBy("Segment.this") void expand() { AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table; int oldCapacity = oldTable.length(); if (oldCapacity >= MAXIMUM_CAPACITY) { return; } /* * Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move with a power of two offset. * We eliminate unnecessary node creation by catching cases where old nodes can be reused * because their next fields won't change. Statistically, at the default threshold, only * about one-sixth of them need cloning when a table doubles. The nodes they replace will be * garbage collectable as soon as they are no longer referenced by any reader thread that may * be in the midst of traversing table right now. */ int newCount = count; AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1); threshold = newTable.length() * 3 / 4; int newMask = newTable.length() - 1; for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. ReferenceEntry<K, V> head = oldTable.get(oldIndex); if (head != null) { ReferenceEntry<K, V> next = head.getNext(); int headIndex = head.getHash() & newMask; // Single node on list if (next == null) { newTable.set(headIndex, head); } else { // Reuse the consecutive sequence of nodes with the same target // index from the end of the list. tail points to the first // entry in the reusable list. ReferenceEntry<K, V> tail = head; int tailIndex = headIndex; for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) { int newIndex = e.getHash() & newMask; if (newIndex != tailIndex) { // The index changed. We'll need to copy the previous entry. tailIndex = newIndex; tail = e; } } newTable.set(tailIndex, tail); // Clone nodes leading up to the tail. for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) { int newIndex = e.getHash() & newMask; ReferenceEntry<K, V> newNext = newTable.get(newIndex); ReferenceEntry<K, V> newFirst = copyEntry(e, newNext); if (newFirst != null) { newTable.set(newIndex, newFirst); } else { removeCollectedEntry(e); newCount--; } } } } } table = newTable; this.count = newCount; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { preWriteCleanup(); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { // If the value disappeared, this entry is partially collected, // and we should pretend like it doesn't exist. ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); if (entryValue == null) { if (isCollected(valueReference)) { int newCount = this.count - 1; ++modCount; enqueueNotification(entryKey, hash, entryValue, RemovalCause.COLLECTED); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile } return false; } if (map.valueEquivalence.equivalent(oldValue, entryValue)) { ++modCount; enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED); setValue(e, newValue); return true; } else { // Mimic // "if (map.containsKey(key) && map.get(key).equals(oldValue))..." recordLockedRead(e); return false; } } } return false; } finally { unlock(); postWriteCleanup(); } } V replace(K key, int hash, V newValue) { lock(); try { preWriteCleanup(); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { // If the value disappeared, this entry is partially collected, // and we should pretend like it doesn't exist. ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); if (entryValue == null) { if (isCollected(valueReference)) { int newCount = this.count - 1; ++modCount; enqueueNotification(entryKey, hash, entryValue, RemovalCause.COLLECTED); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile } return null; } ++modCount; enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED); setValue(e, newValue); return entryValue; } } return null; } finally { unlock(); postWriteCleanup(); } } V remove(Object key, int hash) { lock(); try { preWriteCleanup(); int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); RemovalCause cause; if (entryValue != null) { cause = RemovalCause.EXPLICIT; } else if (isCollected(valueReference)) { cause = RemovalCause.COLLECTED; } else { return null; } ++modCount; enqueueNotification(entryKey, hash, entryValue, cause); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return entryValue; } } return null; } finally { unlock(); postWriteCleanup(); } } boolean remove(Object key, int hash, Object value) { lock(); try { preWriteCleanup(); int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); RemovalCause cause; if (map.valueEquivalence.equivalent(value, entryValue)) { cause = RemovalCause.EXPLICIT; } else if (isCollected(valueReference)) { cause = RemovalCause.COLLECTED; } else { return false; } ++modCount; enqueueNotification(entryKey, hash, entryValue, cause); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return (cause == RemovalCause.EXPLICIT); } } return false; } finally { unlock(); postWriteCleanup(); } } void clear() { if (count != 0) { lock(); try { AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; if (map.removalNotificationQueue != DISCARDING_QUEUE) { for (int i = 0; i < table.length(); ++i) { for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) { // Computing references aren't actually in the map yet. if (!e.getValueReference().isComputingReference()) { enqueueNotification(e, RemovalCause.EXPLICIT); } } } } for (int i = 0; i < table.length(); ++i) { table.set(i, null); } clearReferenceQueues(); evictionQueue.clear(); expirationQueue.clear(); readCount.set(0); ++modCount; count = 0; // write-volatile } finally { unlock(); postWriteCleanup(); } } } /** * Removes an entry from within a table. All entries following the removed node can stay, but * all preceding ones need to be cloned. * * <p>This method does not decrement count for the removed entry, but does decrement count for * all partially collected entries which are skipped. As such callers which are modifying count * must re-read it after calling removeFromChain. * * @param first the first entry of the table * @param entry the entry being removed from the table * @return the new first entry for the table */ @GuardedBy("Segment.this") ReferenceEntry<K, V> removeFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) { evictionQueue.remove(entry); expirationQueue.remove(entry); int newCount = count; ReferenceEntry<K, V> newFirst = entry.getNext(); for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) { ReferenceEntry<K, V> next = copyEntry(e, newFirst); if (next != null) { newFirst = next; } else { removeCollectedEntry(e); newCount--; } } this.count = newCount; return newFirst; } void removeCollectedEntry(ReferenceEntry<K, V> entry) { enqueueNotification(entry, RemovalCause.COLLECTED); evictionQueue.remove(entry); expirationQueue.remove(entry); } /** * Removes an entry whose key has been garbage collected. */ boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) { lock(); try { int newCount = count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { if (e == entry) { ++modCount; enqueueNotification( e.getKey(), hash, e.getValueReference().get(), RemovalCause.COLLECTED); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return true; } } return false; } finally { unlock(); postWriteCleanup(); } } /** * Removes an entry whose value has been garbage collected. */ boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) { lock(); try { int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> v = e.getValueReference(); if (v == valueReference) { ++modCount; enqueueNotification(key, hash, valueReference.get(), RemovalCause.COLLECTED); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return true; } return false; } } return false; } finally { unlock(); if (!isHeldByCurrentThread()) { // don't cleanup inside of put postWriteCleanup(); } } } /** * Clears a value that has not yet been set, and thus does not require count to be modified. */ boolean clearValue(K key, int hash, ValueReference<K, V> valueReference) { lock(); try { AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> v = e.getValueReference(); if (v == valueReference) { ReferenceEntry<K, V> newFirst = removeFromChain(first, e); table.set(index, newFirst); return true; } return false; } } return false; } finally { unlock(); postWriteCleanup(); } } @GuardedBy("Segment.this") boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) { int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { if (e == entry) { ++modCount; enqueueNotification(e.getKey(), hash, e.getValueReference().get(), cause); ReferenceEntry<K, V> newFirst = removeFromChain(first, e); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return true; } } return false; } /** * Returns {@code true} if the value has been partially collected, meaning that the value is * null and it is not computing. */ boolean isCollected(ValueReference<K, V> valueReference) { if (valueReference.isComputingReference()) { return false; } return (valueReference.get() == null); } /** * Gets the value from an entry. Returns {@code null} if the entry is invalid, * partially-collected, computing, or expired. */ V getLiveValue(ReferenceEntry<K, V> entry) { if (entry.getKey() == null) { tryDrainReferenceQueues(); return null; } V value = entry.getValueReference().get(); if (value == null) { tryDrainReferenceQueues(); return null; } if (map.expires() && map.isExpired(entry)) { tryExpireEntries(); return null; } return value; } /** * Performs routine cleanup following a read. Normally cleanup happens during writes, or from * the cleanupExecutor. If cleanup is not observed after a sufficient number of reads, try * cleaning up from the read thread. */ void postReadCleanup() { if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) { runCleanup(); } } /** * Performs routine cleanup prior to executing a write. This should be called every time a * write thread acquires the segment lock, immediately after acquiring the lock. * * <p>Post-condition: expireEntries has been run. */ @GuardedBy("Segment.this") void preWriteCleanup() { runLockedCleanup(); } /** * Performs routine cleanup following a write. */ void postWriteCleanup() { runUnlockedCleanup(); } void runCleanup() { runLockedCleanup(); runUnlockedCleanup(); } void runLockedCleanup() { if (tryLock()) { try { drainReferenceQueues(); expireEntries(); // calls drainRecencyQueue readCount.set(0); } finally { unlock(); } } } void runUnlockedCleanup() { // locked cleanup may generate notifications we can send unlocked if (!isHeldByCurrentThread()) { map.processPendingNotifications(); } } } // Queues /** * A custom queue for managing eviction order. Note that this is tightly integrated with {@code * ReferenceEntry}, upon which it relies to perform its linking. * * <p>Note that this entire implementation makes the assumption that all elements which are in * the map are also in this queue, and that all elements not in the queue are not in the map. * * <p>The benefits of creating our own queue are that (1) we can replace elements in the middle * of the queue as part of copyEvictableEntry, and (2) the contains method is highly optimized * for the current model. */ static final class EvictionQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> { final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() { ReferenceEntry<K, V> nextEvictable = this; @Override public ReferenceEntry<K, V> getNextEvictable() { return nextEvictable; } @Override public void setNextEvictable(ReferenceEntry<K, V> next) { this.nextEvictable = next; } ReferenceEntry<K, V> previousEvictable = this; @Override public ReferenceEntry<K, V> getPreviousEvictable() { return previousEvictable; } @Override public void setPreviousEvictable(ReferenceEntry<K, V> previous) { this.previousEvictable = previous; } }; // implements Queue @Override public boolean offer(ReferenceEntry<K, V> entry) { // unlink connectEvictables(entry.getPreviousEvictable(), entry.getNextEvictable()); // add to tail connectEvictables(head.getPreviousEvictable(), entry); connectEvictables(entry, head); return true; } @Override public ReferenceEntry<K, V> peek() { ReferenceEntry<K, V> next = head.getNextEvictable(); return (next == head) ? null : next; } @Override public ReferenceEntry<K, V> poll() { ReferenceEntry<K, V> next = head.getNextEvictable(); if (next == head) { return null; } remove(next); return next; } @Override @SuppressWarnings("unchecked") public boolean remove(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry) o; ReferenceEntry<K, V> previous = e.getPreviousEvictable(); ReferenceEntry<K, V> next = e.getNextEvictable(); connectEvictables(previous, next); nullifyEvictable(e); return next != NullEntry.INSTANCE; } @Override @SuppressWarnings("unchecked") public boolean contains(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry) o; return e.getNextEvictable() != NullEntry.INSTANCE; } @Override public boolean isEmpty() { return head.getNextEvictable() == head; } @Override public int size() { int size = 0; for (ReferenceEntry<K, V> e = head.getNextEvictable(); e != head; e = e.getNextEvictable()) { size++; } return size; } @Override public void clear() { ReferenceEntry<K, V> e = head.getNextEvictable(); while (e != head) { ReferenceEntry<K, V> next = e.getNextEvictable(); nullifyEvictable(e); e = next; } head.setNextEvictable(head); head.setPreviousEvictable(head); } @Override public Iterator<ReferenceEntry<K, V>> iterator() { return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) { @Override protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) { ReferenceEntry<K, V> next = previous.getNextEvictable(); return (next == head) ? null : next; } }; } } /** * A custom queue for managing expiration order. Note that this is tightly integrated with * {@code ReferenceEntry}, upon which it reliese to perform its linking. * * <p>Note that this entire implementation makes the assumption that all elements which are in * the map are also in this queue, and that all elements not in the queue are not in the map. * * <p>The benefits of creating our own queue are that (1) we can replace elements in the middle * of the queue as part of copyEvictableEntry, and (2) the contains method is highly optimized * for the current model. */ static final class ExpirationQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> { final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() { @Override public long getExpirationTime() { return Long.MAX_VALUE; } @Override public void setExpirationTime(long time) {} ReferenceEntry<K, V> nextExpirable = this; @Override public ReferenceEntry<K, V> getNextExpirable() { return nextExpirable; } @Override public void setNextExpirable(ReferenceEntry<K, V> next) { this.nextExpirable = next; } ReferenceEntry<K, V> previousExpirable = this; @Override public ReferenceEntry<K, V> getPreviousExpirable() { return previousExpirable; } @Override public void setPreviousExpirable(ReferenceEntry<K, V> previous) { this.previousExpirable = previous; } }; // implements Queue @Override public boolean offer(ReferenceEntry<K, V> entry) { // unlink connectExpirables(entry.getPreviousExpirable(), entry.getNextExpirable()); // add to tail connectExpirables(head.getPreviousExpirable(), entry); connectExpirables(entry, head); return true; } @Override public ReferenceEntry<K, V> peek() { ReferenceEntry<K, V> next = head.getNextExpirable(); return (next == head) ? null : next; } @Override public ReferenceEntry<K, V> poll() { ReferenceEntry<K, V> next = head.getNextExpirable(); if (next == head) { return null; } remove(next); return next; } @Override @SuppressWarnings("unchecked") public boolean remove(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry) o; ReferenceEntry<K, V> previous = e.getPreviousExpirable(); ReferenceEntry<K, V> next = e.getNextExpirable(); connectExpirables(previous, next); nullifyExpirable(e); return next != NullEntry.INSTANCE; } @Override @SuppressWarnings("unchecked") public boolean contains(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry) o; return e.getNextExpirable() != NullEntry.INSTANCE; } @Override public boolean isEmpty() { return head.getNextExpirable() == head; } @Override public int size() { int size = 0; for (ReferenceEntry<K, V> e = head.getNextExpirable(); e != head; e = e.getNextExpirable()) { size++; } return size; } @Override public void clear() { ReferenceEntry<K, V> e = head.getNextExpirable(); while (e != head) { ReferenceEntry<K, V> next = e.getNextExpirable(); nullifyExpirable(e); e = next; } head.setNextExpirable(head); head.setPreviousExpirable(head); } @Override public Iterator<ReferenceEntry<K, V>> iterator() { return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) { @Override protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) { ReferenceEntry<K, V> next = previous.getNextExpirable(); return (next == head) ? null : next; } }; } } static final class CleanupMapTask implements Runnable { final WeakReference<MapMakerInternalMap<?, ?>> mapReference; public CleanupMapTask(MapMakerInternalMap<?, ?> map) { this.mapReference = new WeakReference<MapMakerInternalMap<?, ?>>(map); } @Override public void run() { MapMakerInternalMap<?, ?> map = mapReference.get(); if (map == null) { throw new CancellationException(); } for (Segment<?, ?> segment : map.segments) { segment.runCleanup(); } } } // ConcurrentMap methods @Override public boolean isEmpty() { /* * Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and * removed in one segment while checking another, in which case the table was never actually * empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment * modifications before recheck.) Method containsValue() uses similar constructions for * stability checks. */ long sum = 0L; Segment<K, V>[] segments = this.segments; for (int i = 0; i < segments.length; ++i) { if (segments[i].count != 0) { return false; } sum += segments[i].modCount; } if (sum != 0L) { // recheck unless no modifications for (int i = 0; i < segments.length; ++i) { if (segments[i].count != 0) { return false; } sum -= segments[i].modCount; } if (sum != 0L) { return false; } } return true; } @Override public int size() { Segment<K, V>[] segments = this.segments; long sum = 0; for (int i = 0; i < segments.length; ++i) { sum += segments[i].count; } return Ints.saturatedCast(sum); } @Override public V get(@Nullable Object key) { if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).get(key, hash); } /** * Returns the internal entry for the specified key. The entry may be computing, expired, or * partially collected. Does not impact recency ordering. */ ReferenceEntry<K, V> getEntry(@Nullable Object key) { if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).getEntry(key, hash); } @Override public boolean containsKey(@Nullable Object key) { if (key == null) { return false; } int hash = hash(key); return segmentFor(hash).containsKey(key, hash); } @Override public boolean containsValue(@Nullable Object value) { if (value == null) { return false; } // This implementation is patterned after ConcurrentHashMap, but without the locking. The only // way for it to return a false negative would be for the target value to jump around in the map // such that none of the subsequent iterations observed it, despite the fact that at every point // in time it was present somewhere int the map. This becomes increasingly unlikely as // CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible. final Segment<K, V>[] segments = this.segments; long last = -1L; for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) { long sum = 0L; for (Segment<K, V> segment : segments) { // ensure visibility of most recent completed write @SuppressWarnings({"UnusedDeclaration", "unused"}) int c = segment.count; // read-volatile AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table; for (int j = 0; j < table.length(); j++) { for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) { V v = segment.getLiveValue(e); if (v != null && valueEquivalence.equivalent(value, v)) { return true; } } } sum += segment.modCount; } if (sum == last) { break; } last = sum; } return false; } @Override public V put(K key, V value) { checkNotNull(key); checkNotNull(value); int hash = hash(key); return segmentFor(hash).put(key, hash, value, false); } @Override public V putIfAbsent(K key, V value) { checkNotNull(key); checkNotNull(value); int hash = hash(key); return segmentFor(hash).put(key, hash, value, true); } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Entry<? extends K, ? extends V> e : m.entrySet()) { put(e.getKey(), e.getValue()); } } @Override public V remove(@Nullable Object key) { if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).remove(key, hash); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { if (key == null || value == null) { return false; } int hash = hash(key); return segmentFor(hash).remove(key, hash, value); } @Override public boolean replace(K key, @Nullable V oldValue, V newValue) { checkNotNull(key); checkNotNull(newValue); if (oldValue == null) { return false; } int hash = hash(key); return segmentFor(hash).replace(key, hash, oldValue, newValue); } @Override public V replace(K key, V value) { checkNotNull(key); checkNotNull(value); int hash = hash(key); return segmentFor(hash).replace(key, hash, value); } @Override public void clear() { for (Segment<K, V> segment : segments) { segment.clear(); } } transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> ks = keySet; return (ks != null) ? ks : (keySet = new KeySet()); } transient Collection<V> values; @Override public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } // Iterator Support abstract class HashIterator<E> implements Iterator<E> { int nextSegmentIndex; int nextTableIndex; Segment<K, V> currentSegment; AtomicReferenceArray<ReferenceEntry<K, V>> currentTable; ReferenceEntry<K, V> nextEntry; WriteThroughEntry nextExternal; WriteThroughEntry lastReturned; HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } @Override public abstract E next(); final void advance() { nextExternal = null; if (nextInChain()) { return; } if (nextInTable()) { return; } while (nextSegmentIndex >= 0) { currentSegment = segments[nextSegmentIndex--]; if (currentSegment.count != 0) { currentTable = currentSegment.table; nextTableIndex = currentTable.length() - 1; if (nextInTable()) { return; } } } } /** * Finds the next entry in the current chain. Returns {@code true} if an entry was found. */ boolean nextInChain() { if (nextEntry != null) { for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) { if (advanceTo(nextEntry)) { return true; } } } return false; } /** * Finds the next entry in the current table. Returns {@code true} if an entry was found. */ boolean nextInTable() { while (nextTableIndex >= 0) { if ((nextEntry = currentTable.get(nextTableIndex--)) != null) { if (advanceTo(nextEntry) || nextInChain()) { return true; } } } return false; } /** * Advances to the given entry. Returns {@code true} if the entry was valid, {@code false} if it * should be skipped. */ boolean advanceTo(ReferenceEntry<K, V> entry) { try { K key = entry.getKey(); V value = getLiveValue(entry); if (value != null) { nextExternal = new WriteThroughEntry(key, value); return true; } else { // Skip stale entry. return false; } } finally { currentSegment.postReadCleanup(); } } @Override public boolean hasNext() { return nextExternal != null; } WriteThroughEntry nextEntry() { if (nextExternal == null) { throw new NoSuchElementException(); } lastReturned = nextExternal; advance(); return lastReturned; } @Override public void remove() { checkRemove(lastReturned != null); MapMakerInternalMap.this.remove(lastReturned.getKey()); lastReturned = null; } } final class KeyIterator extends HashIterator<K> { @Override public K next() { return nextEntry().getKey(); } } final class ValueIterator extends HashIterator<V> { @Override public V next() { return nextEntry().getValue(); } } /** * Custom Entry class used by EntryIterator.next(), that relays setValue changes to the * underlying map. */ final class WriteThroughEntry extends AbstractMapEntry<K, V> { final K key; // non-null V value; // non-null WriteThroughEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public boolean equals(@Nullable Object object) { // Cannot use key and value equivalence if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return key.equals(that.getKey()) && value.equals(that.getValue()); } return false; } @Override public int hashCode() { // Cannot use key and value equivalence return key.hashCode() ^ value.hashCode(); } @Override public V setValue(V newValue) { V oldValue = put(key, newValue); value = newValue; // only if put succeeds return oldValue; } } final class EntryIterator extends HashIterator<Entry<K, V>> { @Override public Entry<K, V> next() { return nextEntry(); } } final class KeySet extends AbstractSet<K> { @Override public Iterator<K> iterator() { return new KeyIterator(); } @Override public int size() { return MapMakerInternalMap.this.size(); } @Override public boolean isEmpty() { return MapMakerInternalMap.this.isEmpty(); } @Override public boolean contains(Object o) { return MapMakerInternalMap.this.containsKey(o); } @Override public boolean remove(Object o) { return MapMakerInternalMap.this.remove(o) != null; } @Override public void clear() { MapMakerInternalMap.this.clear(); } } final class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return new ValueIterator(); } @Override public int size() { return MapMakerInternalMap.this.size(); } @Override public boolean isEmpty() { return MapMakerInternalMap.this.isEmpty(); } @Override public boolean contains(Object o) { return MapMakerInternalMap.this.containsValue(o); } @Override public void clear() { MapMakerInternalMap.this.clear(); } } final class EntrySet extends AbstractSet<Entry<K, V>> { @Override public Iterator<Entry<K, V>> iterator() { return new EntryIterator(); } @Override public boolean contains(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; Object key = e.getKey(); if (key == null) { return false; } V v = MapMakerInternalMap.this.get(key); return v != null && valueEquivalence.equivalent(e.getValue(), v); } @Override public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; Object key = e.getKey(); return key != null && MapMakerInternalMap.this.remove(key, e.getValue()); } @Override public int size() { return MapMakerInternalMap.this.size(); } @Override public boolean isEmpty() { return MapMakerInternalMap.this.isEmpty(); } @Override public void clear() { MapMakerInternalMap.this.clear(); } } // Serialization Support private static final long serialVersionUID = 5; Object writeReplace() { return new SerializationProxy<K, V>(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, this); } /** * The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a * circular dependency is present, so the proxy must be able to behave as the map itself. */ abstract static class AbstractSerializationProxy<K, V> extends ForwardingConcurrentMap<K, V> implements Serializable { private static final long serialVersionUID = 3; final Strength keyStrength; final Strength valueStrength; final Equivalence<Object> keyEquivalence; final Equivalence<Object> valueEquivalence; final long expireAfterWriteNanos; final long expireAfterAccessNanos; final int maximumSize; final int concurrencyLevel; final RemovalListener<? super K, ? super V> removalListener; transient ConcurrentMap<K, V> delegate; AbstractSerializationProxy(Strength keyStrength, Strength valueStrength, Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence, long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize, int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener, ConcurrentMap<K, V> delegate) { this.keyStrength = keyStrength; this.valueStrength = valueStrength; this.keyEquivalence = keyEquivalence; this.valueEquivalence = valueEquivalence; this.expireAfterWriteNanos = expireAfterWriteNanos; this.expireAfterAccessNanos = expireAfterAccessNanos; this.maximumSize = maximumSize; this.concurrencyLevel = concurrencyLevel; this.removalListener = removalListener; this.delegate = delegate; } @Override protected ConcurrentMap<K, V> delegate() { return delegate; } void writeMapTo(ObjectOutputStream out) throws IOException { out.writeInt(delegate.size()); for (Entry<K, V> entry : delegate.entrySet()) { out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } out.writeObject(null); // terminate entries } @SuppressWarnings("deprecation") // serialization of deprecated feature MapMaker readMapMaker(ObjectInputStream in) throws IOException { int size = in.readInt(); MapMaker mapMaker = new MapMaker() .initialCapacity(size) .setKeyStrength(keyStrength) .setValueStrength(valueStrength) .keyEquivalence(keyEquivalence) .concurrencyLevel(concurrencyLevel); mapMaker.removalListener(removalListener); if (expireAfterWriteNanos > 0) { mapMaker.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS); } if (expireAfterAccessNanos > 0) { mapMaker.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS); } if (maximumSize != MapMaker.UNSET_INT) { mapMaker.maximumSize(maximumSize); } return mapMaker; } @SuppressWarnings("unchecked") void readEntries(ObjectInputStream in) throws IOException, ClassNotFoundException { while (true) { K key = (K) in.readObject(); if (key == null) { break; // terminator } V value = (V) in.readObject(); delegate.put(key, value); } } } /** * The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a * circular dependency is present, so the proxy must be able to behave as the map itself. */ private static final class SerializationProxy<K, V> extends AbstractSerializationProxy<K, V> { private static final long serialVersionUID = 3; SerializationProxy(Strength keyStrength, Strength valueStrength, Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence, long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize, int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener, ConcurrentMap<K, V> delegate) { super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate); } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); writeMapTo(out); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); MapMaker mapMaker = readMapMaker(in); delegate = mapMaker.makeMap(); readEntries(in); } private Object readResolve() { return delegate; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/MapMakerInternalMap.java
Java
asf20
119,186
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableMap<K, V> { private ForwardingImmutableMap() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingImmutableMap.java
Java
asf20
923
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkRemove; import static com.google.common.collect.Maps.keyOrNull; import com.google.common.annotations.Beta; import java.util.Iterator; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.SortedMap; /** * A navigable map which forwards all its method calls to another navigable map. Subclasses should * override one or more methods to modify the behavior of the backing map as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingNavigableMap} forward <i>indiscriminately</i> * to the methods of the delegate. For example, overriding {@link #put} alone <i>will not</i> * change the behavior of {@link #putAll}, which can lead to unexpected behavior. In this case, you * should override {@code putAll} as well, either providing your own implementation, or delegating * to the provided {@code standardPutAll} method. * * <p>Each of the {@code standard} methods uses the map's comparator (or the natural ordering of * the elements, if there is no comparator) to test element equality. As a result, if the comparator * is not consistent with equals, some of the standard implementations may violate the {@code Map} * contract. * * <p>The {@code standard} methods and the collection views they return are not guaranteed to be * thread-safe, even when all of the methods that they depend on are thread-safe. * * @author Louis Wasserman * @since 12.0 */ public abstract class ForwardingNavigableMap<K, V> extends ForwardingSortedMap<K, V> implements NavigableMap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingNavigableMap() {} @Override protected abstract NavigableMap<K, V> delegate(); @Override public Entry<K, V> lowerEntry(K key) { return delegate().lowerEntry(key); } /** * A sensible definition of {@link #lowerEntry} in terms of the {@code lastEntry()} of * {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override * {@code lowerEntry} to forward to this implementation. */ protected Entry<K, V> standardLowerEntry(K key) { return headMap(key, false).lastEntry(); } @Override public K lowerKey(K key) { return delegate().lowerKey(key); } /** * A sensible definition of {@link #lowerKey} in terms of {@code lowerEntry}. If you override * {@link #lowerEntry}, you may wish to override {@code lowerKey} to forward to this * implementation. */ protected K standardLowerKey(K key) { return keyOrNull(lowerEntry(key)); } @Override public Entry<K, V> floorEntry(K key) { return delegate().floorEntry(key); } /** * A sensible definition of {@link #floorEntry} in terms of the {@code lastEntry()} of * {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override * {@code floorEntry} to forward to this implementation. */ protected Entry<K, V> standardFloorEntry(K key) { return headMap(key, true).lastEntry(); } @Override public K floorKey(K key) { return delegate().floorKey(key); } /** * A sensible definition of {@link #floorKey} in terms of {@code floorEntry}. If you override * {@code floorEntry}, you may wish to override {@code floorKey} to forward to this * implementation. */ protected K standardFloorKey(K key) { return keyOrNull(floorEntry(key)); } @Override public Entry<K, V> ceilingEntry(K key) { return delegate().ceilingEntry(key); } /** * A sensible definition of {@link #ceilingEntry} in terms of the {@code firstEntry()} of * {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override * {@code ceilingEntry} to forward to this implementation. */ protected Entry<K, V> standardCeilingEntry(K key) { return tailMap(key, true).firstEntry(); } @Override public K ceilingKey(K key) { return delegate().ceilingKey(key); } /** * A sensible definition of {@link #ceilingKey} in terms of {@code ceilingEntry}. If you override * {@code ceilingEntry}, you may wish to override {@code ceilingKey} to forward to this * implementation. */ protected K standardCeilingKey(K key) { return keyOrNull(ceilingEntry(key)); } @Override public Entry<K, V> higherEntry(K key) { return delegate().higherEntry(key); } /** * A sensible definition of {@link #higherEntry} in terms of the {@code firstEntry()} of * {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override * {@code higherEntry} to forward to this implementation. */ protected Entry<K, V> standardHigherEntry(K key) { return tailMap(key, false).firstEntry(); } @Override public K higherKey(K key) { return delegate().higherKey(key); } /** * A sensible definition of {@link #higherKey} in terms of {@code higherEntry}. If you override * {@code higherEntry}, you may wish to override {@code higherKey} to forward to this * implementation. */ protected K standardHigherKey(K key) { return keyOrNull(higherEntry(key)); } @Override public Entry<K, V> firstEntry() { return delegate().firstEntry(); } /** * A sensible definition of {@link #firstEntry} in terms of the {@code iterator()} of * {@link #entrySet}. If you override {@code entrySet}, you may wish to override * {@code firstEntry} to forward to this implementation. */ protected Entry<K, V> standardFirstEntry() { return Iterables.getFirst(entrySet(), null); } /** * A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If you override * {@code firstEntry}, you may wish to override {@code firstKey} to forward to this * implementation. */ protected K standardFirstKey() { Entry<K, V> entry = firstEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } @Override public Entry<K, V> lastEntry() { return delegate().lastEntry(); } /** * A sensible definition of {@link #lastEntry} in terms of the {@code iterator()} of the * {@link #entrySet} of {@link #descendingMap}. If you override {@code descendingMap}, you may * wish to override {@code lastEntry} to forward to this implementation. */ protected Entry<K, V> standardLastEntry() { return Iterables.getFirst(descendingMap().entrySet(), null); } /** * A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If you override * {@code lastEntry}, you may wish to override {@code lastKey} to forward to this implementation. */ protected K standardLastKey() { Entry<K, V> entry = lastEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } @Override public Entry<K, V> pollFirstEntry() { return delegate().pollFirstEntry(); } /** * A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of * {@code entrySet}. If you override {@code entrySet}, you may wish to override * {@code pollFirstEntry} to forward to this implementation. */ protected Entry<K, V> standardPollFirstEntry() { return Iterators.pollNext(entrySet().iterator()); } @Override public Entry<K, V> pollLastEntry() { return delegate().pollLastEntry(); } /** * A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of the * {@code entrySet} of {@code descendingMap}. If you override {@code descendingMap}, you may wish * to override {@code pollFirstEntry} to forward to this implementation. */ protected Entry<K, V> standardPollLastEntry() { return Iterators.pollNext(descendingMap().entrySet().iterator()); } @Override public NavigableMap<K, V> descendingMap() { return delegate().descendingMap(); } /** * A sensible implementation of {@link NavigableMap#descendingMap} in terms of the methods of * this {@code NavigableMap}. In many cases, you may wish to override * {@link ForwardingNavigableMap#descendingMap} to forward to this implementation or a subclass * thereof. * * <p>In particular, this map iterates over entries with repeated calls to * {@link NavigableMap#lowerEntry}. If a more efficient means of iteration is available, you may * wish to override the {@code entryIterator()} method of this class. * * @since 12.0 */ @Beta protected class StandardDescendingMap extends Maps.DescendingMap<K, V> { /** Constructor for use by subclasses. */ public StandardDescendingMap() {} @Override NavigableMap<K, V> forward() { return ForwardingNavigableMap.this; } @Override protected Iterator<Entry<K, V>> entryIterator() { return new Iterator<Entry<K, V>>() { private Entry<K, V> toRemove = null; private Entry<K, V> nextOrNull = forward().lastEntry(); @Override public boolean hasNext() { return nextOrNull != null; } @Override public java.util.Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } try { return nextOrNull; } finally { toRemove = nextOrNull; nextOrNull = forward().lowerEntry(nextOrNull.getKey()); } } @Override public void remove() { checkRemove(toRemove != null); forward().remove(toRemove.getKey()); toRemove = null; } }; } } @Override public NavigableSet<K> navigableKeySet() { return delegate().navigableKeySet(); } /** * A sensible implementation of {@link NavigableMap#navigableKeySet} in terms of the methods of * this {@code NavigableMap}. In many cases, you may wish to override * {@link ForwardingNavigableMap#navigableKeySet} to forward to this implementation or a subclass * thereof. * * @since 12.0 */ @Beta protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> { /** Constructor for use by subclasses. */ public StandardNavigableKeySet() { super(ForwardingNavigableMap.this); } } @Override public NavigableSet<K> descendingKeySet() { return delegate().descendingKeySet(); } /** * A sensible definition of {@link #descendingKeySet} as the {@code navigableKeySet} of * {@link #descendingMap}. (The {@link StandardDescendingMap} implementation implements * {@code navigableKeySet} on its own, so as not to cause an infinite loop.) If you override * {@code descendingMap}, you may wish to override {@code descendingKeySet} to forward to this * implementation. */ @Beta protected NavigableSet<K> standardDescendingKeySet() { return descendingMap().navigableKeySet(); } /** * A sensible definition of {@link #subMap(Object, Object)} in terms of * {@link #subMap(Object, boolean, Object, boolean)}. If you override * {@code subMap(K, boolean, K, boolean)}, you may wish to override {@code subMap} to forward to * this implementation. */ @Override protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return delegate().headMap(toKey, inclusive); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return delegate().tailMap(fromKey, inclusive); } /** * A sensible definition of {@link #headMap(Object)} in terms of * {@link #headMap(Object, boolean)}. If you override {@code headMap(K, boolean)}, you may wish * to override {@code headMap} to forward to this implementation. */ protected SortedMap<K, V> standardHeadMap(K toKey) { return headMap(toKey, false); } /** * A sensible definition of {@link #tailMap(Object)} in terms of * {@link #tailMap(Object, boolean)}. If you override {@code tailMap(K, boolean)}, you may wish * to override {@code tailMap} to forward to this implementation. */ protected SortedMap<K, V> standardTailMap(K fromKey) { return tailMap(fromKey, true); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingNavigableMap.java
Java
asf20
13,206
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * An immutable {@link Multimap}. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableMultimap(Multimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableMultimap} is convenient for * {@code public static final} multimaps ("constant multimaps") and also lets * you easily make a "defensive copy" of a multimap provided to your class by * a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this class * are guaranteed to be immutable. * * <p>In addition to methods defined by {@link Multimap}, an {@link #inverse} * method is also supported. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public abstract class ImmutableMultimap<K, V> extends AbstractMultimap<K, V> implements Serializable { /** Returns an empty multimap. */ public static <K, V> ImmutableMultimap<K, V> of() { return ImmutableListMultimap.of(); } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) { return ImmutableListMultimap.of(k1, v1); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) { return ImmutableListMultimap.of(k1, v1, k2, v2); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * Multimap for {@link ImmutableMultimap.Builder} that maintains key and * value orderings, allows duplicate values, and performs better than * {@link LinkedListMultimap}. */ private static class BuilderMultimap<K, V> extends AbstractMapBasedMultimap<K, V> { BuilderMultimap() { super(new LinkedHashMap<K, Collection<V>>()); } @Override Collection<V> createCollection() { return Lists.newArrayList(); } private static final long serialVersionUID = 0; } /** * A builder for creating immutable multimap instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<K, V> { Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>(); Comparator<? super K> keyComparator; Comparator<? super V> valueComparator; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMultimap#builder}. */ public Builder() {} /** * Adds a key-value mapping to the built multimap. */ public Builder<K, V> put(K key, V value) { checkEntryNotNull(key, value); builderMultimap.put(key, value); return this; } /** * Adds an entry to the built multimap. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { return put(entry.getKey(), entry.getValue()); } /** * Stores a collection of values with the same key in the built multimap. * * @throws NullPointerException if {@code key}, {@code values}, or any * element in {@code values} is null. The builder is left in an invalid * state. */ public Builder<K, V> putAll(K key, Iterable<? extends V> values) { if (key == null) { throw new NullPointerException( "null key in entry: null=" + Iterables.toString(values)); } Collection<V> valueList = builderMultimap.get(key); for (V value : values) { checkEntryNotNull(key, value); valueList.add(value); } return this; } /** * Stores an array of values with the same key in the built multimap. * * @throws NullPointerException if the key or any value is null. The builder * is left in an invalid state. */ public Builder<K, V> putAll(K key, V... values) { return putAll(key, Arrays.asList(values)); } /** * Stores another multimap's entries in the built multimap. The generated * multimap's key and value orderings correspond to the iteration ordering * of the {@code multimap.asMap()} view, with new keys and values following * any existing keys and values. * * @throws NullPointerException if any key or value in {@code multimap} is * null. The builder is left in an invalid state. */ public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { putAll(entry.getKey(), entry.getValue()); } return this; } /** * Specifies the ordering of the generated multimap's keys. * * @since 8.0 */ 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. * * @since 8.0 */ public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { this.valueComparator = checkNotNull(valueComparator); return this; } /** * Returns a newly-created immutable multimap. */ public ImmutableMultimap<K, V> build() { if (valueComparator != null) { for (Collection<V> values : builderMultimap.asMap().values()) { List<V> list = (List <V>) values; Collections.sort(list, valueComparator); } } if (keyComparator != null) { Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>(); List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList( builderMultimap.asMap().entrySet()); Collections.sort( entries, Ordering.from(keyComparator).<K>onKeys()); for (Map.Entry<K, Collection<V>> entry : entries) { sortedCopy.putAll(entry.getKey(), entry.getValue()); } builderMultimap = sortedCopy; } return copyOf(builderMultimap); } } /** * Returns an immutable multimap containing the same mappings as {@code * multimap}. The generated multimap's key and value orderings correspond to * the iteration ordering of the {@code multimap.asMap()} view. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws NullPointerException if any key or value in {@code multimap} is * null */ public static <K, V> ImmutableMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { if (multimap instanceof ImmutableMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableMultimap<K, V> kvMultimap = (ImmutableMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } return ImmutableListMultimap.copyOf(multimap); } final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map; final transient int size; // These constants allow the deserialization code to set final fields. This // holder class makes sure they are not initialized unless an instance is // deserialized. @GwtIncompatible("java serialization is not supported") static class FieldSettersHolder { static final Serialization.FieldSetter<ImmutableMultimap> MAP_FIELD_SETTER = Serialization.getFieldSetter( ImmutableMultimap.class, "map"); static final Serialization.FieldSetter<ImmutableMultimap> SIZE_FIELD_SETTER = Serialization.getFieldSetter( ImmutableMultimap.class, "size"); static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER = Serialization.getFieldSetter( ImmutableSetMultimap.class, "emptySet"); } ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map, int size) { this.map = map; this.size = size; } // mutators (not supported) /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableCollection<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 ImmutableCollection<V> replaceValues(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public void clear() { throw new UnsupportedOperationException(); } /** * Returns an immutable collection of the values for the given key. If no * mappings in the multimap have the provided key, an empty immutable * collection is returned. The values are in the same order as the parameters * used to build this multimap. */ @Override public abstract ImmutableCollection<V> get(K key); /** * Returns an immutable multimap which is the inverse of this one. For every * key-value mapping in the original, the result will have a mapping with * key and value reversed. * * @since 11.0 */ public abstract ImmutableMultimap<V, K> inverse(); /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } /** * Returns {@code true} if this immutable multimap's implementation contains references to * user-created objects that aren't accessible via this multimap's methods. This is generally * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid * memory leaks. */ boolean isPartialView() { return map.isPartialView(); } // accessors @Override public boolean containsKey(@Nullable Object key) { return map.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return value != null && super.containsValue(value); } @Override public int size() { return size; } // views /** * Returns an immutable set of the distinct keys in this multimap. These keys * are ordered according to when they first appeared during the construction * of this multimap. */ @Override public ImmutableSet<K> keySet() { return map.keySet(); } /** * Returns an immutable map that associates each key with its corresponding * values in the multimap. */ @Override @SuppressWarnings("unchecked") // a widening cast public ImmutableMap<K, Collection<V>> asMap() { return (ImmutableMap) map; } @Override Map<K, Collection<V>> createAsMap() { throw new AssertionError("should never be called"); } /** * Returns an immutable collection of all key-value pairs in the multimap. Its * iterator traverses the values for the first key, the values for the second * key, and so on. */ @Override public ImmutableCollection<Entry<K, V>> entries() { return (ImmutableCollection<Entry<K, V>>) super.entries(); } @Override ImmutableCollection<Entry<K, V>> createEntries() { return new EntryCollection<K, V>(this); } private static class EntryCollection<K, V> extends ImmutableCollection<Entry<K, V>> { final ImmutableMultimap<K, V> multimap; EntryCollection(ImmutableMultimap<K, V> multimap) { this.multimap = multimap; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return multimap.entryIterator(); } @Override boolean isPartialView() { return multimap.isPartialView(); } @Override public int size() { return multimap.size(); } @Override public boolean contains(Object object) { if (object instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) object; return multimap.containsEntry(entry.getKey(), entry.getValue()); } return false; } private static final long serialVersionUID = 0; } private abstract class Itr<T> extends UnmodifiableIterator<T> { final Iterator<Entry<K, Collection<V>>> mapIterator = asMap().entrySet().iterator(); K key = null; Iterator<V> valueIterator = Iterators.emptyIterator(); abstract T output(K key, V value); @Override public boolean hasNext() { return mapIterator.hasNext() || valueIterator.hasNext(); } @Override public T next() { if (!valueIterator.hasNext()) { Entry<K, Collection<V>> mapEntry = mapIterator.next(); key = mapEntry.getKey(); valueIterator = mapEntry.getValue().iterator(); } return output(key, valueIterator.next()); } } @Override UnmodifiableIterator<Entry<K, V>> entryIterator() { return new Itr<Entry<K, V>>() { @Override Entry<K, V> output(K key, V value) { return Maps.immutableEntry(key, value); } }; } /** * Returns a collection, which may contain duplicates, of all keys. The number * of times a key appears in the returned multiset equals the number of * mappings the key has in the multimap. Duplicate keys appear consecutively * in the multiset's iteration order. */ @Override public ImmutableMultiset<K> keys() { return (ImmutableMultiset<K>) super.keys(); } @Override ImmutableMultiset<K> createKeys() { return new Keys(); } @SuppressWarnings("serial") // Uses writeReplace, not default serialization class Keys extends ImmutableMultiset<K> { @Override public boolean contains(@Nullable Object object) { return containsKey(object); } @Override public int count(@Nullable Object element) { Collection<V> values = map.get(element); return (values == null) ? 0 : values.size(); } @Override public Set<K> elementSet() { return keySet(); } @Override public int size() { return ImmutableMultimap.this.size(); } @Override Multiset.Entry<K> getEntry(int index) { Map.Entry<K, ? extends Collection<V>> entry = map.entrySet().asList().get(index); return Multisets.immutableEntry(entry.getKey(), entry.getValue().size()); } @Override boolean isPartialView() { return true; } } /** * Returns an immutable collection of the values in this multimap. Its * iterator traverses the values for the first key, the values for the second * key, and so on. */ @Override public ImmutableCollection<V> values() { return (ImmutableCollection<V>) super.values(); } @Override ImmutableCollection<V> createValues() { return new Values<K, V>(this); } @Override UnmodifiableIterator<V> valueIterator() { return new Itr<V>() { @Override V output(K key, V value) { return value; } }; } private static final class Values<K, V> extends ImmutableCollection<V> { private transient final ImmutableMultimap<K, V> multimap; Values(ImmutableMultimap<K, V> multimap) { this.multimap = multimap; } @Override public boolean contains(@Nullable Object object) { return multimap.containsValue(object); } @Override public UnmodifiableIterator<V> iterator() { return multimap.valueIterator(); } @GwtIncompatible("not present in emulated superclass") @Override int copyIntoArray(Object[] dst, int offset) { for (ImmutableCollection<V> valueCollection : multimap.map.values()) { offset = valueCollection.copyIntoArray(dst, offset); } return offset; } @Override public int size() { return multimap.size(); } @Override boolean isPartialView() { return true; } private static final long serialVersionUID = 0; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableMultimap.java
Java
asf20
20,653
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.ObjectArrays.checkElementsNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import javax.annotation.Nullable; /** * An immutable collection. Does not permit null elements. * * <p>In addition to the {@link Collection} methods, this class has an {@link * #asList()} method, which returns a list view of the collection's elements. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed * outside of this package as it has no public or protected constructors. Thus, * instances of this type are guaranteed to be immutable. * * @author Jesse Wilson * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable { ImmutableCollection() {} /** * Returns an unmodifiable iterator across the elements in this collection. */ @Override public abstract UnmodifiableIterator<E> iterator(); @Override public final Object[] toArray() { int size = size(); if (size == 0) { return ObjectArrays.EMPTY_ARRAY; } Object[] result = new Object[size()]; copyIntoArray(result, 0); return result; } @Override public final <T> T[] toArray(T[] other) { checkNotNull(other); int size = size(); if (other.length < size) { other = ObjectArrays.newArray(other, size); } else if (other.length > size) { other[size] = null; } copyIntoArray(other, 0); return other; } @Override public boolean contains(@Nullable Object object) { return object != null && super.contains(object); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean add(E e) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean remove(Object object) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean addAll(Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void clear() { throw new UnsupportedOperationException(); } /* * TODO(kevinb): Restructure code so ImmutableList doesn't contain this * variable, which it doesn't use. */ private transient ImmutableList<E> asList; /** * Returns a list view of the collection. * * @since 2.0 */ public ImmutableList<E> asList() { ImmutableList<E> list = asList; return (list == null) ? (asList = createAsList()) : list; } ImmutableList<E> createAsList() { switch (size()) { case 0: return ImmutableList.of(); case 1: return ImmutableList.of(iterator().next()); default: return new RegularImmutableAsList<E>(this, toArray()); } } /** * Returns {@code true} if this immutable collection's implementation contains references to * user-created objects that aren't accessible via this collection's methods. This is generally * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid * memory leaks. */ abstract boolean isPartialView(); /** * Copies the contents of this immutable collection into the specified array at the specified * offset. Returns {@code offset + size()}. */ int copyIntoArray(Object[] dst, int offset) { for (E e : this) { dst[offset++] = e; } return offset; } Object writeReplace() { // We serialize by default to ImmutableList, the simplest thing that works. return new ImmutableList.SerializedForm(toArray()); } /** * Abstract base class for builders of {@link ImmutableCollection} types. * * @since 10.0 */ public abstract static class Builder<E> { static final int DEFAULT_INITIAL_CAPACITY = 4; static int expandedCapacity(int oldCapacity, int minCapacity) { if (minCapacity < 0) { throw new AssertionError("cannot store more than MAX_VALUE elements"); } // careful of overflow! int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; if (newCapacity < minCapacity) { newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; } if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; // guaranteed to be >= newCapacity } return newCapacity; } Builder() { } /** * Adds {@code element} to the {@code ImmutableCollection} being built. * * <p>Note that each builder class covariantly returns its own type from * this method. * * @param element the element to add * @return this {@code Builder} instance * @throws NullPointerException if {@code element} is null */ public abstract Builder<E> add(E element); /** * Adds each element of {@code elements} to the {@code ImmutableCollection} * being built. * * <p>Note that each builder class overrides this method in order to * covariantly return its own type. * * @param elements the elements to add * @return this {@code Builder} instance * @throws NullPointerException if {@code elements} is null or contains a * null element */ public Builder<E> add(E... elements) { for (E element : elements) { add(element); } return this; } /** * Adds each element of {@code elements} to the {@code ImmutableCollection} * being built. * * <p>Note that each builder class overrides this method in order to * covariantly return its own type. * * @param elements the elements to add * @return this {@code Builder} instance * @throws NullPointerException if {@code elements} is null or contains a * null element */ public Builder<E> addAll(Iterable<? extends E> elements) { for (E element : elements) { add(element); } return this; } /** * Adds each element of {@code elements} to the {@code ImmutableCollection} * being built. * * <p>Note that each builder class overrides this method in order to * covariantly return its own type. * * @param elements the elements to add * @return this {@code Builder} instance * @throws NullPointerException if {@code elements} is null or contains a * null element */ public Builder<E> addAll(Iterator<? extends E> elements) { while (elements.hasNext()) { add(elements.next()); } return this; } /** * Returns a newly-created {@code ImmutableCollection} of the appropriate * type, containing the elements provided to this builder. * * <p>Note that each builder class covariantly returns the appropriate type * of {@code ImmutableCollection} from this method. */ public abstract ImmutableCollection<E> build(); } abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> { Object[] contents; int size; ArrayBasedBuilder(int initialCapacity) { checkNonnegative(initialCapacity, "initialCapacity"); this.contents = new Object[initialCapacity]; this.size = 0; } /** * Expand the absolute capacity of the builder so it can accept at least * the specified number of elements without being resized. */ private void ensureCapacity(int minCapacity) { if (contents.length < minCapacity) { this.contents = ObjectArrays.arraysCopyOf( this.contents, expandedCapacity(contents.length, minCapacity)); } } @Override public ArrayBasedBuilder<E> add(E element) { checkNotNull(element); ensureCapacity(size + 1); contents[size++] = element; return this; } @Override public Builder<E> add(E... elements) { checkElementsNotNull(elements); ensureCapacity(size + elements.length); System.arraycopy(elements, 0, contents, size, elements.length); size += elements.length; return this; } @Override public Builder<E> addAll(Iterable<? extends E> elements) { if (elements instanceof Collection) { Collection<?> collection = (Collection<?>) elements; ensureCapacity(size + collection.size()); } super.addAll(elements); return this; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableCollection.java
Java
asf20
10,720
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.AbstractMap; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import javax.annotation.Nullable; /** * Skeletal implementation of {@link NavigableMap}. * * @author Louis Wasserman */ abstract class AbstractNavigableMap<K, V> extends AbstractMap<K, V> implements NavigableMap<K, V> { @Override @Nullable public abstract V get(@Nullable Object key); @Override @Nullable public Entry<K, V> firstEntry() { return Iterators.getNext(entryIterator(), null); } @Override @Nullable public Entry<K, V> lastEntry() { return Iterators.getNext(descendingEntryIterator(), null); } @Override @Nullable public Entry<K, V> pollFirstEntry() { return Iterators.pollNext(entryIterator()); } @Override @Nullable public Entry<K, V> pollLastEntry() { return Iterators.pollNext(descendingEntryIterator()); } @Override public K firstKey() { Entry<K, V> entry = firstEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } @Override public K lastKey() { Entry<K, V> entry = lastEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } @Override @Nullable public Entry<K, V> lowerEntry(K key) { return headMap(key, false).lastEntry(); } @Override @Nullable public Entry<K, V> floorEntry(K key) { return headMap(key, true).lastEntry(); } @Override @Nullable public Entry<K, V> ceilingEntry(K key) { return tailMap(key, true).firstEntry(); } @Override @Nullable public Entry<K, V> higherEntry(K key) { return tailMap(key, false).firstEntry(); } @Override public K lowerKey(K key) { return Maps.keyOrNull(lowerEntry(key)); } @Override public K floorKey(K key) { return Maps.keyOrNull(floorEntry(key)); } @Override public K ceilingKey(K key) { return Maps.keyOrNull(ceilingEntry(key)); } @Override public K higherKey(K key) { return Maps.keyOrNull(higherEntry(key)); } abstract Iterator<Entry<K, V>> entryIterator(); abstract Iterator<Entry<K, V>> descendingEntryIterator(); @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableSet<K> navigableKeySet() { return new Maps.NavigableKeySet<K, V>(this); } @Override public Set<K> keySet() { return navigableKeySet(); } @Override public abstract int size(); @Override public Set<Entry<K, V>> entrySet() { return new Maps.EntrySet<K, V>() { @Override Map<K, V> map() { return AbstractNavigableMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } }; } @Override public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } @Override public NavigableMap<K, V> descendingMap() { return new DescendingMap(); } private final class DescendingMap extends Maps.DescendingMap<K, V> { @Override NavigableMap<K, V> forward() { return AbstractNavigableMap.this; } @Override Iterator<Entry<K, V>> entryIterator() { return descendingEntryIterator(); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractNavigableMap.java
Java
asf20
4,304
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.EnumMap; import java.util.Iterator; /** * Multiset implementation backed by an {@link EnumMap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> { /** Creates an empty {@code EnumMultiset}. */ public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) { return new EnumMultiset<E>(type); } /** * Creates a new {@code EnumMultiset} 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 * @throws IllegalArgumentException if {@code elements} is empty */ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) { Iterator<E> iterator = elements.iterator(); checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable"); EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass()); Iterables.addAll(multiset, elements); return multiset; } /** * Returns a new {@code EnumMultiset} instance containing the given elements. Unlike * {@link EnumMultiset#create(Iterable)}, this method does not produce an exception on an empty * iterable. * * @since 14.0 */ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements, Class<E> type) { EnumMultiset<E> result = create(type); Iterables.addAll(result, elements); return result; } private transient Class<E> type; /** Creates an empty {@code EnumMultiset}. */ private EnumMultiset(Class<E> type) { super(WellBehavedMap.wrap(new EnumMap<E, Count>(type))); this.type = type; } @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(type); Serialization.writeMultiset(this, stream); } /** * @serialData the {@code Class<E>} for the enum type, the number of distinct * elements, the first element, its count, the second element, its * count, and so on */ @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject Class<E> localType = (Class<E>) stream.readObject(); type = localType; setBackingMap(WellBehavedMap.wrap(new EnumMap<E, Count>(type))); Serialization.populateMultiset(this, stream); } @GwtIncompatible("Not needed in emulated source") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EnumMultiset.java
Java
asf20
3,932
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableMap} with exactly one entry. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization final class SingletonImmutableBiMap<K, V> extends ImmutableBiMap<K, V> { final transient K singleKey; final transient V singleValue; SingletonImmutableBiMap(K singleKey, V singleValue) { checkEntryNotNull(singleKey, singleValue); this.singleKey = singleKey; this.singleValue = singleValue; } private SingletonImmutableBiMap(K singleKey, V singleValue, ImmutableBiMap<V, K> inverse) { this.singleKey = singleKey; this.singleValue = singleValue; this.inverse = inverse; } SingletonImmutableBiMap(Entry<? extends K, ? extends V> entry) { this(entry.getKey(), entry.getValue()); } @Override public V get(@Nullable Object key) { return singleKey.equals(key) ? singleValue : null; } @Override public int size() { return 1; } @Override public boolean containsKey(@Nullable Object key) { return singleKey.equals(key); } @Override public boolean containsValue(@Nullable Object value) { return singleValue.equals(value); } @Override boolean isPartialView() { return false; } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return ImmutableSet.of(Maps.immutableEntry(singleKey, singleValue)); } @Override ImmutableSet<K> createKeySet() { return ImmutableSet.of(singleKey); } transient ImmutableBiMap<V, K> inverse; @Override public ImmutableBiMap<V, K> inverse() { // racy single-check idiom ImmutableBiMap<V, K> result = inverse; if (result == null) { return inverse = new SingletonImmutableBiMap<V, K>( singleValue, singleKey, this); } else { return result; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/SingletonImmutableBiMap.java
Java
asf20
2,705
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableSet<E> { private ForwardingImmutableSet() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingImmutableSet.java
Java
asf20
920
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import javax.annotation.Nullable; /** * An empty immutable sorted map. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization final class EmptyImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> { private final transient ImmutableSortedSet<K> keySet; EmptyImmutableSortedMap(Comparator<? super K> comparator) { this.keySet = ImmutableSortedSet.emptySet(comparator); } EmptyImmutableSortedMap( Comparator<? super K> comparator, ImmutableSortedMap<K, V> descendingMap) { super(descendingMap); this.keySet = ImmutableSortedSet.emptySet(comparator); } @Override public V get(@Nullable Object key) { return null; } @Override public ImmutableSortedSet<K> keySet() { return keySet; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public ImmutableCollection<V> values() { return ImmutableList.of(); } @Override public String toString() { return "{}"; } @Override boolean isPartialView() { return false; } @Override public ImmutableSet<Entry<K, V>> entrySet() { return ImmutableSet.of(); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { throw new AssertionError("should never be called"); } @Override public ImmutableSetMultimap<K, V> asMultimap() { return ImmutableSetMultimap.of(); } @Override public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) { checkNotNull(toKey); return this; } @Override public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) { checkNotNull(fromKey); return this; } @Override ImmutableSortedMap<K, V> createDescendingMap() { return new EmptyImmutableSortedMap<K, V>(Ordering.from(comparator()).reverse(), this); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EmptyImmutableSortedMap.java
Java
asf20
2,691
/* * 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.primitives.Primitives; import java.io.Serializable; import java.util.Map; import javax.annotation.Nullable; /** * A class-to-instance map backed by an {@link ImmutableMap}. See also {@link * MutableClassToInstanceMap}. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B> implements ClassToInstanceMap<B>, Serializable { /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <B> Builder<B> builder() { return new Builder<B>(); } /** * A builder for creating immutable class-to-instance maps. Example: * <pre> {@code * * static final ImmutableClassToInstanceMap<Handler> HANDLERS = * new ImmutableClassToInstanceMap.Builder<Handler>() * .put(FooHandler.class, new FooHandler()) * .put(BarHandler.class, new SubBarHandler()) * .put(Handler.class, new QuuxHandler()) * .build();}</pre> * * <p>After invoking {@link #build()} it is still possible to add more entries * and build again. Thus each map generated by this builder will be a superset * of any map generated before it. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<B> { private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder = ImmutableMap.builder(); /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys are not allowed, and will cause {@link #build} to fail. */ public <T extends B> Builder<B> put(Class<T> key, T value) { mapBuilder.put(key, value); return this; } /** * Associates all of {@code map's} keys and values in the built map. * Duplicate keys are not allowed, and will cause {@link #build} to fail. * * @throws NullPointerException if any key or value in {@code map} is null * @throws ClassCastException if any value is not an instance of the type * specified by its key */ public <T extends B> Builder<B> putAll( Map<? extends Class<? extends T>, ? extends T> map) { for (Entry<? extends Class<? extends T>, ? extends T> entry : map.entrySet()) { Class<? extends T> type = entry.getKey(); T value = entry.getValue(); mapBuilder.put(type, cast(type, value)); } return this; } private static <B, T extends B> T cast(Class<T> type, B value) { return Primitives.wrap(type).cast(value); } /** * Returns a new immutable class-to-instance map containing the entries * provided to this builder. * * @throws IllegalArgumentException if duplicate keys were added */ public ImmutableClassToInstanceMap<B> build() { return new ImmutableClassToInstanceMap<B>(mapBuilder.build()); } } /** * Returns an immutable map containing the same entries as {@code map}. If * {@code map} somehow contains entries with duplicate keys (for example, if * it is a {@code SortedMap} whose comparator is not <i>consistent with * equals</i>), the results of this method are undefined. * * <p><b>Note:</b> Despite what the method name suggests, if {@code map} is * an {@code ImmutableClassToInstanceMap}, no copy will actually be performed. * * @throws NullPointerException if any key or value in {@code map} is null * @throws ClassCastException if any value is not an instance of the type * specified by its key */ public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf( Map<? extends Class<? extends S>, ? extends S> map) { if (map instanceof ImmutableClassToInstanceMap) { @SuppressWarnings("unchecked") // covariant casts safe (unmodifiable) // Eclipse won't compile if we cast to the parameterized type. ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap) map; return cast; } return new Builder<B>().putAll(map).build(); } private final ImmutableMap<Class<? extends B>, B> delegate; private ImmutableClassToInstanceMap( ImmutableMap<Class<? extends B>, B> delegate) { this.delegate = delegate; } @Override protected Map<Class<? extends B>, B> delegate() { return delegate; } @Override @SuppressWarnings("unchecked") // value could not get in if not a T @Nullable public <T extends B> T getInstance(Class<T> type) { return (T) delegate.get(checkNotNull(type)); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public <T extends B> T putInstance(Class<T> type, T value) { throw new UnsupportedOperationException(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
Java
asf20
5,694
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Supplier; import com.google.common.collect.Table.Cell; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.Nullable; /** * Provides static methods that involve a {@code Table}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Tables"> * {@code Tables}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 7.0 */ @GwtCompatible public final class Tables { private Tables() {} /** * Returns an immutable cell with the specified row key, column key, and * value. * * <p>The returned cell is serializable. * * @param rowKey the row key to be associated with the returned cell * @param columnKey the column key to be associated with the returned cell * @param value the value to be associated with the returned cell */ public static <R, C, V> Cell<R, C, V> immutableCell( @Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { return new ImmutableCell<R, C, V>(rowKey, columnKey, value); } static final class ImmutableCell<R, C, V> extends AbstractCell<R, C, V> implements Serializable { private final R rowKey; private final C columnKey; private final V value; ImmutableCell( @Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { this.rowKey = rowKey; this.columnKey = columnKey; this.value = value; } @Override public R getRowKey() { return rowKey; } @Override public C getColumnKey() { return columnKey; } @Override public V getValue() { return value; } private static final long serialVersionUID = 0; } abstract static class AbstractCell<R, C, V> implements Cell<R, C, V> { // needed for serialization AbstractCell() {} @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Cell) { Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj; return Objects.equal(getRowKey(), other.getRowKey()) && Objects.equal(getColumnKey(), other.getColumnKey()) && Objects.equal(getValue(), other.getValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(getRowKey(), getColumnKey(), getValue()); } @Override public String toString() { return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue(); } } /** * Creates a transposed view of a given table that flips its row and column * keys. In other words, calling {@code get(columnKey, rowKey)} on the * generated table always returns the same value as calling {@code * get(rowKey, columnKey)} on the original table. Updating the original table * changes the contents of the transposed table and vice versa. * * <p>The returned table supports update operations as long as the input table * supports the analogous operation with swapped rows and columns. For * example, in a {@link HashBasedTable} instance, {@code * rowKeySet().iterator()} supports {@code remove()} but {@code * columnKeySet().iterator()} doesn't. With a transposed {@link * HashBasedTable}, it's the other way around. */ public static <R, C, V> Table<C, R, V> transpose(Table<R, C, V> table) { return (table instanceof TransposeTable) ? ((TransposeTable<R, C, V>) table).original : new TransposeTable<C, R, V>(table); } private static class TransposeTable<C, R, V> extends AbstractTable<C, R, V> { final Table<R, C, V> original; TransposeTable(Table<R, C, V> original) { this.original = checkNotNull(original); } @Override public void clear() { original.clear(); } @Override public Map<C, V> column(R columnKey) { return original.row(columnKey); } @Override public Set<R> columnKeySet() { return original.rowKeySet(); } @Override public Map<R, Map<C, V>> columnMap() { return original.rowMap(); } @Override public boolean contains( @Nullable Object rowKey, @Nullable Object columnKey) { return original.contains(columnKey, rowKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { return original.containsRow(columnKey); } @Override public boolean containsRow(@Nullable Object rowKey) { return original.containsColumn(rowKey); } @Override public boolean containsValue(@Nullable Object value) { return original.containsValue(value); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { return original.get(columnKey, rowKey); } @Override public V put(C rowKey, R columnKey, V value) { return original.put(columnKey, rowKey, value); } @Override public void putAll(Table<? extends C, ? extends R, ? extends V> table) { original.putAll(transpose(table)); } @Override public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { return original.remove(columnKey, rowKey); } @Override public Map<R, V> row(C rowKey) { return original.column(rowKey); } @Override public Set<C> rowKeySet() { return original.columnKeySet(); } @Override public Map<C, Map<R, V>> rowMap() { return original.columnMap(); } @Override public int size() { return original.size(); } @Override public Collection<V> values() { return original.values(); } // Will cast TRANSPOSE_CELL to a type that always succeeds private static final Function<Cell<?, ?, ?>, Cell<?, ?, ?>> TRANSPOSE_CELL = new Function<Cell<?, ?, ?>, Cell<?, ?, ?>>() { @Override public Cell<?, ?, ?> apply(Cell<?, ?, ?> cell) { return immutableCell( cell.getColumnKey(), cell.getRowKey(), cell.getValue()); } }; @SuppressWarnings("unchecked") @Override Iterator<Cell<C, R, V>> cellIterator() { return Iterators.transform(original.cellSet().iterator(), (Function) TRANSPOSE_CELL); } } /** * Creates a table that uses the specified backing map and factory. It can * generate a table based on arbitrary {@link Map} classes. * * <p>The {@code factory}-generated and {@code backingMap} classes determine * the table iteration order. However, the table's {@code row()} method * returns instances of a different class than {@code factory.get()} does. * * <p>Call this method only when the simpler factory methods in classes like * {@link HashBasedTable} and {@link TreeBasedTable} won't suffice. * * <p>The views returned by the {@code Table} methods {@link Table#column}, * {@link Table#columnKeySet}, and {@link Table#columnMap} have iterators that * don't support {@code remove()}. Otherwise, all optional operations are * supported. Null row keys, columns keys, and values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like * {@code column(columnKey).get(rowKey)} still runs quickly, since the row key * is provided. However, {@code column(columnKey).size()} takes longer, since * an iteration across all row keys occurs. * * <p>Note that this implementation is not synchronized. If multiple threads * access this table concurrently and one of the threads modifies the table, * it must be synchronized externally. * * <p>The table is serializable if {@code backingMap}, {@code factory}, the * maps generated by {@code factory}, and the table contents are all * serializable. * * <p>Note: the table assumes complete ownership over of {@code backingMap} * and the maps returned by {@code factory}. Those objects should not be * manually updated and they should not use soft, weak, or phantom references. * * @param backingMap place to store the mapping from each row key to its * corresponding column key / value map * @param factory supplier of new, empty maps that will each hold all column * key / value mappings for a given row key * @throws IllegalArgumentException if {@code backingMap} is not empty * @since 10.0 */ @Beta public static <R, C, V> Table<R, C, V> newCustomTable( Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { checkArgument(backingMap.isEmpty()); checkNotNull(factory); // TODO(jlevy): Wrap factory to validate that the supplied maps are empty? return new StandardTable<R, C, V>(backingMap, factory); } /** * Returns a view of a table where each value is transformed by a function. * All other properties of the table, such as iteration order, are left * intact. * * <p>Changes in the underlying table are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying table. * * <p>It's acceptable for the underlying table to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed table might contain null values, if the function sometimes * gives a null result. * * <p>The returned table is not thread-safe or serializable, even if the * underlying table is. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned table to be a view, but it means that the function will be * applied many times for bulk operations like {@link Table#containsValue} and * {@code Table.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned table doesn't need to * be a view, copy the returned table into a new table of your choosing. * * @since 10.0 */ @Beta public static <R, C, V1, V2> Table<R, C, V2> transformValues( Table<R, C, V1> fromTable, Function<? super V1, V2> function) { return new TransformedTable<R, C, V1, V2>(fromTable, function); } private static class TransformedTable<R, C, V1, V2> extends AbstractTable<R, C, V2> { final Table<R, C, V1> fromTable; final Function<? super V1, V2> function; TransformedTable( Table<R, C, V1> fromTable, Function<? super V1, V2> function) { this.fromTable = checkNotNull(fromTable); this.function = checkNotNull(function); } @Override public boolean contains(Object rowKey, Object columnKey) { return fromTable.contains(rowKey, columnKey); } @Override public V2 get(Object rowKey, Object columnKey) { // The function is passed a null input only when the table contains a null // value. return contains(rowKey, columnKey) ? function.apply(fromTable.get(rowKey, columnKey)) : null; } @Override public int size() { return fromTable.size(); } @Override public void clear() { fromTable.clear(); } @Override public V2 put(R rowKey, C columnKey, V2 value) { throw new UnsupportedOperationException(); } @Override public void putAll( Table<? extends R, ? extends C, ? extends V2> table) { throw new UnsupportedOperationException(); } @Override public V2 remove(Object rowKey, Object columnKey) { return contains(rowKey, columnKey) ? function.apply(fromTable.remove(rowKey, columnKey)) : null; } @Override public Map<C, V2> row(R rowKey) { return Maps.transformValues(fromTable.row(rowKey), function); } @Override public Map<R, V2> column(C columnKey) { return Maps.transformValues(fromTable.column(columnKey), function); } Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() { return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() { @Override public Cell<R, C, V2> apply(Cell<R, C, V1> cell) { return immutableCell( cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue())); } }; } @Override Iterator<Cell<R, C, V2>> cellIterator() { return Iterators.transform(fromTable.cellSet().iterator(), cellFunction()); } @Override public Set<R> rowKeySet() { return fromTable.rowKeySet(); } @Override public Set<C> columnKeySet() { return fromTable.columnKeySet(); } @Override Collection<V2> createValues() { return Collections2.transform(fromTable.values(), function); } @Override public Map<R, Map<C, V2>> rowMap() { Function<Map<C, V1>, Map<C, V2>> rowFunction = new Function<Map<C, V1>, Map<C, V2>>() { @Override public Map<C, V2> apply(Map<C, V1> row) { return Maps.transformValues(row, function); } }; return Maps.transformValues(fromTable.rowMap(), rowFunction); } @Override public Map<C, Map<R, V2>> columnMap() { Function<Map<R, V1>, Map<R, V2>> columnFunction = new Function<Map<R, V1>, Map<R, V2>>() { @Override public Map<R, V2> apply(Map<R, V1> column) { return Maps.transformValues(column, function); } }; return Maps.transformValues(fromTable.columnMap(), columnFunction); } } /** * Returns an unmodifiable view of the specified table. This method allows modules to provide * users with "read-only" access to internal tables. Query operations on the returned table * "read through" to the specified table, and attempts to modify the returned table, whether * direct or via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned table will be serializable if the specified table is serializable. * * <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change. * * @param table * the table for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified table * @since 11.0 */ public static <R, C, V> Table<R, C, V> unmodifiableTable( Table<? extends R, ? extends C, ? extends V> table) { return new UnmodifiableTable<R, C, V>(table); } private static class UnmodifiableTable<R, C, V> extends ForwardingTable<R, C, V> implements Serializable { final Table<? extends R, ? extends C, ? extends V> delegate; UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) { this.delegate = checkNotNull(delegate); } @SuppressWarnings("unchecked") // safe, covariant cast @Override protected Table<R, C, V> delegate() { return (Table<R, C, V>) delegate; } @Override public Set<Cell<R, C, V>> cellSet() { return Collections.unmodifiableSet(super.cellSet()); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Map<R, V> column(@Nullable C columnKey) { return Collections.unmodifiableMap(super.column(columnKey)); } @Override public Set<C> columnKeySet() { return Collections.unmodifiableSet(super.columnKeySet()); } @Override public Map<C, Map<R, V>> columnMap() { Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper)); } @Override public V put(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { throw new UnsupportedOperationException(); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { throw new UnsupportedOperationException(); } @Override public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { throw new UnsupportedOperationException(); } @Override public Map<C, V> row(@Nullable R rowKey) { return Collections.unmodifiableMap(super.row(rowKey)); } @Override public Set<R> rowKeySet() { return Collections.unmodifiableSet(super.rowKeySet()); } @Override public Map<R, Map<C, V>> rowMap() { Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper)); } @Override public Collection<V> values() { return Collections.unmodifiableCollection(super.values()); } private static final long serialVersionUID = 0; } /** * Returns an unmodifiable view of the specified row-sorted table. This method allows modules to * provide users with "read-only" access to internal tables. Query operations on the returned * table "read through" to the specified table, and attemps to modify the returned table, whether * direct or via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned table will be serializable if the specified table is serializable. * * @param table the row-sorted table for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified table * @since 11.0 */ @Beta public static <R, C, V> RowSortedTable<R, C, V> unmodifiableRowSortedTable( RowSortedTable<R, ? extends C, ? extends V> table) { /* * It's not ? extends R, because it's technically not covariant in R. Specifically, * table.rowMap().comparator() could return a comparator that only works for the ? extends R. * Collections.unmodifiableSortedMap makes the same distinction. */ return new UnmodifiableRowSortedMap<R, C, V>(table); } static final class UnmodifiableRowSortedMap<R, C, V> extends UnmodifiableTable<R, C, V> implements RowSortedTable<R, C, V> { public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) { super(delegate); } @Override protected RowSortedTable<R, C, V> delegate() { return (RowSortedTable<R, C, V>) super.delegate(); } @Override public SortedMap<R, Map<C, V>> rowMap() { Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper)); } @Override public SortedSet<R> rowKeySet() { return Collections.unmodifiableSortedSet(delegate().rowKeySet()); } private static final long serialVersionUID = 0; } @SuppressWarnings("unchecked") private static <K, V> Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() { return (Function) UNMODIFIABLE_WRAPPER; } private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER = new Function<Map<Object, Object>, Map<Object, Object>>() { @Override public Map<Object, Object> apply(Map<Object, Object> input) { return Collections.unmodifiableMap(input); } }; static boolean equalsImpl(Table<?, ?, ?> table, @Nullable Object obj) { if (obj == table) { return true; } else if (obj instanceof Table) { Table<?, ?, ?> that = (Table<?, ?, ?>) obj; return table.cellSet().equals(that.cellSet()); } else { return false; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Tables.java
Java
asf20
20,506
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.alwaysTrue; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Maps.safeContainsKey; import static com.google.common.collect.Maps.safeGet; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Maps.ImprovedAbstractMap; import com.google.common.collect.Sets.ImprovedAbstractSet; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * {@link Table} implementation backed by a map that associates row keys with * column key / value secondary maps. This class provides rapid access to * records by the row key alone or by both keys, but not by just the column key. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link * #columnMap()} have iterators that don't support {@code remove()}. Otherwise, * all optional operations are supported. Null row keys, columns keys, and * values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code * column(columnKey).get(rowKey)} still runs quickly, since the row key is * provided. However, {@code column(columnKey).size()} takes longer, since an * iteration across all row keys occurs. * * <p>Note that this implementation is not synchronized. If multiple threads * access this table concurrently and one of the threads modifies the table, it * must be synchronized externally. * * @author Jared Levy */ @GwtCompatible class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable { @GwtTransient final Map<R, Map<C, V>> backingMap; @GwtTransient final Supplier<? extends Map<C, V>> factory; StandardTable(Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { this.backingMap = backingMap; this.factory = factory; } // Accessors @Override public boolean contains( @Nullable Object rowKey, @Nullable Object columnKey) { return rowKey != null && columnKey != null && super.contains(rowKey, columnKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { if (columnKey == null) { return false; } for (Map<C, V> map : backingMap.values()) { if (safeContainsKey(map, columnKey)) { return true; } } return false; } @Override public boolean containsRow(@Nullable Object rowKey) { return rowKey != null && safeContainsKey(backingMap, rowKey); } @Override public boolean containsValue(@Nullable Object value) { return value != null && super.containsValue(value); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { return (rowKey == null || columnKey == null) ? null : super.get(rowKey, columnKey); } @Override public boolean isEmpty() { return backingMap.isEmpty(); } @Override public int size() { int size = 0; for (Map<C, V> map : backingMap.values()) { size += map.size(); } return size; } // Mutators @Override public void clear() { backingMap.clear(); } private Map<C, V> getOrCreate(R rowKey) { Map<C, V> map = backingMap.get(rowKey); if (map == null) { map = factory.get(); backingMap.put(rowKey, map); } return map; } @Override public V put(R rowKey, C columnKey, V value) { checkNotNull(rowKey); checkNotNull(columnKey); checkNotNull(value); return getOrCreate(rowKey).put(columnKey, value); } @Override public V remove( @Nullable Object rowKey, @Nullable Object columnKey) { if ((rowKey == null) || (columnKey == null)) { return null; } Map<C, V> map = safeGet(backingMap, rowKey); if (map == null) { return null; } V value = map.remove(columnKey); if (map.isEmpty()) { backingMap.remove(rowKey); } return value; } private Map<R, V> removeColumn(Object column) { Map<R, V> output = new LinkedHashMap<R, V>(); Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<R, Map<C, V>> entry = iterator.next(); V value = entry.getValue().remove(column); if (value != null) { output.put(entry.getKey(), value); if (entry.getValue().isEmpty()) { iterator.remove(); } } } return output; } private boolean containsMapping( Object rowKey, Object columnKey, Object value) { return value != null && value.equals(get(rowKey, columnKey)); } /** Remove a row key / column key / value mapping, if present. */ private boolean removeMapping(Object rowKey, Object columnKey, Object value) { if (containsMapping(rowKey, columnKey, value)) { remove(rowKey, columnKey); return true; } return false; } // Views /** * Abstract set whose {@code isEmpty()} returns whether the table is empty and * whose {@code clear()} clears all table mappings. */ private abstract class TableSet<T> extends ImprovedAbstractSet<T> { @Override public boolean isEmpty() { return backingMap.isEmpty(); } @Override public void clear() { backingMap.clear(); } } /** * {@inheritDoc} * * <p>The set's iterator traverses the mappings for the first row, the * mappings for the second row, and so on. * * <p>Each cell is an immutable snapshot of a row key / column key / value * mapping, taken at the time the cell is returned by a method call to the * set or its iterator. */ @Override public Set<Cell<R, C, V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, V>> cellIterator() { return new CellIterator(); } private class CellIterator implements Iterator<Cell<R, C, V>> { final Iterator<Entry<R, Map<C, V>>> rowIterator = backingMap.entrySet().iterator(); Entry<R, Map<C, V>> rowEntry; Iterator<Entry<C, V>> columnIterator = Iterators.emptyModifiableIterator(); @Override public boolean hasNext() { return rowIterator.hasNext() || columnIterator.hasNext(); } @Override public Cell<R, C, V> next() { if (!columnIterator.hasNext()) { rowEntry = rowIterator.next(); columnIterator = rowEntry.getValue().entrySet().iterator(); } Entry<C, V> columnEntry = columnIterator.next(); return Tables.immutableCell( rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue()); } @Override public void remove() { columnIterator.remove(); if (rowEntry.getValue().isEmpty()) { rowIterator.remove(); } } } @Override public Map<C, V> row(R rowKey) { return new Row(rowKey); } class Row extends ImprovedAbstractMap<C, V> { final R rowKey; Row(R rowKey) { this.rowKey = checkNotNull(rowKey); } Map<C, V> backingRowMap; Map<C, V> backingRowMap() { return (backingRowMap == null || (backingRowMap.isEmpty() && backingMap.containsKey(rowKey))) ? backingRowMap = computeBackingRowMap() : backingRowMap; } Map<C, V> computeBackingRowMap() { return backingMap.get(rowKey); } // Call this every time we perform a removal. void maintainEmptyInvariant() { if (backingRowMap() != null && backingRowMap.isEmpty()) { backingMap.remove(rowKey); backingRowMap = null; } } @Override public boolean containsKey(Object key) { Map<C, V> backingRowMap = backingRowMap(); return (key != null && backingRowMap != null) && Maps.safeContainsKey(backingRowMap, key); } @Override public V get(Object key) { Map<C, V> backingRowMap = backingRowMap(); return (key != null && backingRowMap != null) ? Maps.safeGet(backingRowMap, key) : null; } @Override public V put(C key, V value) { checkNotNull(key); checkNotNull(value); if (backingRowMap != null && !backingRowMap.isEmpty()) { return backingRowMap.put(key, value); } return StandardTable.this.put(rowKey, key, value); } @Override public V remove(Object key) { Map<C, V> backingRowMap = backingRowMap(); if (backingRowMap == null) { return null; } V result = Maps.safeRemove(backingRowMap, key); maintainEmptyInvariant(); return result; } @Override public void clear() { Map<C, V> backingRowMap = backingRowMap(); if (backingRowMap != null) { backingRowMap.clear(); } maintainEmptyInvariant(); } @Override protected Set<Entry<C, V>> createEntrySet() { return new RowEntrySet(); } private final class RowEntrySet extends Maps.EntrySet<C, V> { @Override Map<C, V> map() { return Row.this; } @Override public int size() { Map<C, V> map = backingRowMap(); return (map == null) ? 0 : map.size(); } @Override public Iterator<Entry<C, V>> iterator() { final Map<C, V> map = backingRowMap(); if (map == null) { return Iterators.emptyModifiableIterator(); } final Iterator<Entry<C, V>> iterator = map.entrySet().iterator(); return new Iterator<Entry<C, V>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<C, V> next() { final Entry<C, V> entry = iterator.next(); return new ForwardingMapEntry<C, V>() { @Override protected Entry<C, V> delegate() { return entry; } @Override public V setValue(V value) { return super.setValue(checkNotNull(value)); } @Override public boolean equals(Object object) { // TODO(user): identify why this affects GWT tests return standardEquals(object); } }; } @Override public void remove() { iterator.remove(); maintainEmptyInvariant(); } }; } } } /** * {@inheritDoc} * * <p>The returned map's views have iterators that don't support * {@code remove()}. */ @Override public Map<R, V> column(C columnKey) { return new Column(columnKey); } private class Column extends ImprovedAbstractMap<R, V> { final C columnKey; Column(C columnKey) { this.columnKey = checkNotNull(columnKey); } @Override public V put(R key, V value) { return StandardTable.this.put(key, columnKey, value); } @Override public V get(Object key) { return StandardTable.this.get(key, columnKey); } @Override public boolean containsKey(Object key) { return StandardTable.this.contains(key, columnKey); } @Override public V remove(Object key) { return StandardTable.this.remove(key, columnKey); } /** * Removes all {@code Column} mappings whose row key and value satisfy the * given predicate. */ boolean removeFromColumnIf(Predicate<? super Entry<R, V>> predicate) { boolean changed = false; Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<R, Map<C, V>> entry = iterator.next(); Map<C, V> map = entry.getValue(); V value = map.get(columnKey); if (value != null && predicate.apply(Maps.immutableEntry(entry.getKey(), value))) { map.remove(columnKey); changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override Set<Entry<R, V>> createEntrySet() { return new EntrySet(); } private class EntrySet extends ImprovedAbstractSet<Entry<R, V>> { @Override public Iterator<Entry<R, V>> iterator() { return new EntrySetIterator(); } @Override public int size() { int size = 0; for (Map<C, V> map : backingMap.values()) { if (map.containsKey(columnKey)) { size++; } } return size; } @Override public boolean isEmpty() { return !containsColumn(columnKey); } @Override public void clear() { removeFromColumnIf(alwaysTrue()); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; return containsMapping(entry.getKey(), columnKey, entry.getValue()); } return false; } @Override public boolean remove(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return removeMapping(entry.getKey(), columnKey, entry.getValue()); } return false; } @Override public boolean retainAll(Collection<?> c) { return removeFromColumnIf(not(in(c))); } } private class EntrySetIterator extends AbstractIterator<Entry<R, V>> { final Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); @Override protected Entry<R, V> computeNext() { while (iterator.hasNext()) { final Entry<R, Map<C, V>> entry = iterator.next(); if (entry.getValue().containsKey(columnKey)) { return new AbstractMapEntry<R, V>() { @Override public R getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue().get(columnKey); } @Override public V setValue(V value) { return entry.getValue().put(columnKey, checkNotNull(value)); } }; } } return endOfData(); } } @Override Set<R> createKeySet() { return new KeySet(); } private class KeySet extends Maps.KeySet<R, V> { KeySet() { super(Column.this); } @Override public boolean contains(Object obj) { return StandardTable.this.contains(obj, columnKey); } @Override public boolean remove(Object obj) { return StandardTable.this.remove(obj, columnKey) != null; } @Override public boolean retainAll(final Collection<?> c) { return removeFromColumnIf(Maps.<R>keyPredicateOnEntries(not(in(c)))); } } @Override Collection<V> createValues() { return new Values(); } private class Values extends Maps.Values<R, V> { Values() { super(Column.this); } @Override public boolean remove(Object obj) { return obj != null && removeFromColumnIf(Maps.<V>valuePredicateOnEntries(equalTo(obj))); } @Override public boolean removeAll(final Collection<?> c) { return removeFromColumnIf(Maps.<V>valuePredicateOnEntries(in(c))); } @Override public boolean retainAll(final Collection<?> c) { return removeFromColumnIf(Maps.<V>valuePredicateOnEntries(not(in(c)))); } } } @Override public Set<R> rowKeySet() { return rowMap().keySet(); } private transient Set<C> columnKeySet; /** * {@inheritDoc} * * <p>The returned set has an iterator that does not support {@code remove()}. * * <p>The set's iterator traverses the columns of the first row, the * columns of the second row, etc., skipping any columns that have * appeared previously. */ @Override public Set<C> columnKeySet() { Set<C> result = columnKeySet; return (result == null) ? columnKeySet = new ColumnKeySet() : result; } private class ColumnKeySet extends TableSet<C> { @Override public Iterator<C> iterator() { return createColumnKeyIterator(); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean remove(Object obj) { if (obj == null) { return false; } boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); if (map.keySet().remove(obj)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); // map.keySet().removeAll(c) can throw a NPE when map is a TreeMap with // natural ordering and c contains a null. if (Iterators.removeAll(map.keySet().iterator(), c)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); if (map.keySet().retainAll(c)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean contains(Object obj) { return containsColumn(obj); } } /** * Creates an iterator that returns each column value with duplicates * omitted. */ Iterator<C> createColumnKeyIterator() { return new ColumnKeyIterator(); } private class ColumnKeyIterator extends AbstractIterator<C> { // Use the same map type to support TreeMaps with comparators that aren't // consistent with equals(). final Map<C, V> seen = factory.get(); final Iterator<Map<C, V>> mapIterator = backingMap.values().iterator(); Iterator<Entry<C, V>> entryIterator = Iterators.emptyIterator(); @Override protected C computeNext() { while (true) { if (entryIterator.hasNext()) { Entry<C, V> entry = entryIterator.next(); if (!seen.containsKey(entry.getKey())) { seen.put(entry.getKey(), entry.getValue()); return entry.getKey(); } } else if (mapIterator.hasNext()) { entryIterator = mapIterator.next().entrySet().iterator(); } else { return endOfData(); } } } } /** * {@inheritDoc} * * <p>The collection's iterator traverses the values for the first row, * the values for the second row, and so on. */ @Override public Collection<V> values() { return super.values(); } private transient Map<R, Map<C, V>> rowMap; @Override public Map<R, Map<C, V>> rowMap() { Map<R, Map<C, V>> result = rowMap; return (result == null) ? rowMap = createRowMap() : result; } Map<R, Map<C, V>> createRowMap() { return new RowMap(); } class RowMap extends ImprovedAbstractMap<R, Map<C, V>> { @Override public boolean containsKey(Object key) { return containsRow(key); } // performing cast only when key is in backing map and has the correct type @SuppressWarnings("unchecked") @Override public Map<C, V> get(Object key) { return containsRow(key) ? row((R) key) : null; } @Override public Map<C, V> remove(Object key) { return (key == null) ? null : backingMap.remove(key); } @Override protected Set<Entry<R, Map<C, V>>> createEntrySet() { return new EntrySet(); } class EntrySet extends TableSet<Entry<R, Map<C, V>>> { @Override public Iterator<Entry<R, Map<C, V>>> iterator() { return Maps.asMapEntryIterator(backingMap.keySet(), new Function<R, Map<C, V>>() { @Override public Map<C, V> apply(R rowKey) { return row(rowKey); } }); } @Override public int size() { return backingMap.size(); } @Override public boolean contains(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return entry.getKey() != null && entry.getValue() instanceof Map && Collections2.safeContains(backingMap.entrySet(), entry); } return false; } @Override public boolean remove(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return entry.getKey() != null && entry.getValue() instanceof Map && backingMap.entrySet().remove(entry); } return false; } } } private transient ColumnMap columnMap; @Override public Map<C, Map<R, V>> columnMap() { ColumnMap result = columnMap; return (result == null) ? columnMap = new ColumnMap() : result; } private class ColumnMap extends ImprovedAbstractMap<C, Map<R, V>> { // The cast to C occurs only when the key is in the map, implying that it // has the correct type. @SuppressWarnings("unchecked") @Override public Map<R, V> get(Object key) { return containsColumn(key) ? column((C) key) : null; } @Override public boolean containsKey(Object key) { return containsColumn(key); } @Override public Map<R, V> remove(Object key) { return containsColumn(key) ? removeColumn(key) : null; } @Override public Set<Entry<C, Map<R, V>>> createEntrySet() { return new ColumnMapEntrySet(); } @Override public Set<C> keySet() { return columnKeySet(); } @Override Collection<Map<R, V>> createValues() { return new ColumnMapValues(); } class ColumnMapEntrySet extends TableSet<Entry<C, Map<R, V>>> { @Override public Iterator<Entry<C, Map<R, V>>> iterator() { return Maps.asMapEntryIterator(columnKeySet(), new Function<C, Map<R, V>>() { @Override public Map<R, V> apply(C columnKey) { return column(columnKey); } }); } @Override public int size() { return columnKeySet().size(); } @Override public boolean contains(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; if (containsColumn(entry.getKey())) { // The cast to C occurs only when the key is in the map, implying // that it has the correct type. @SuppressWarnings("unchecked") C columnKey = (C) entry.getKey(); return get(columnKey).equals(entry.getValue()); } } return false; } @Override public boolean remove(Object obj) { if (contains(obj)) { Entry<?, ?> entry = (Entry<?, ?>) obj; removeColumn(entry.getKey()); return true; } return false; } @Override public boolean removeAll(Collection<?> c) { /* * We can't inherit the normal implementation (which calls * Sets.removeAllImpl(Set, *Collection*) because, under some * circumstances, it attempts to call columnKeySet().iterator().remove, * which is unsupported. */ checkNotNull(c); return Sets.removeAllImpl(this, c.iterator()); } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (!c.contains(Maps.immutableEntry(columnKey, column(columnKey)))) { removeColumn(columnKey); changed = true; } } return changed; } } private class ColumnMapValues extends Maps.Values<C, Map<R, V>> { ColumnMapValues() { super(ColumnMap.this); } @Override public boolean remove(Object obj) { for (Entry<C, Map<R, V>> entry : ColumnMap.this.entrySet()) { if (entry.getValue().equals(obj)) { removeColumn(entry.getKey()); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (c.contains(column(columnKey))) { removeColumn(columnKey); changed = true; } } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (!c.contains(column(columnKey))) { removeColumn(columnKey); changed = true; } } return changed; } } } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/StandardTable.java
Java
asf20
26,295
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * "Overrides" the {@link ImmutableMultiset} static methods that lack * {@link ImmutableSortedMultiset} equivalents with deprecated, exception-throwing versions. This * prevents accidents like the following: * * <pre> {@code * * List<Object> objects = ...; * // Sort them: * Set<Object> sorted = ImmutableSortedMultiset.copyOf(objects); * // BAD CODE! The returned multiset is actually an unsorted ImmutableMultiset!}</pre> * * <p>While we could put the overrides in {@link ImmutableSortedMultiset} itself, it seems clearer * to separate these "do not call" methods from those intended for normal use. * * @author Louis Wasserman */ abstract class ImmutableSortedMultisetFauxverideShim<E> extends ImmutableMultiset<E> { /** * Not supported. Use {@link ImmutableSortedMultiset#naturalOrder}, which offers better * type-safety, instead. This method exists only to hide {@link ImmutableMultiset#builder} from * consumers of {@code ImmutableSortedMultiset}. * * @throws UnsupportedOperationException always * @deprecated Use {@link ImmutableSortedMultiset#naturalOrder}, which offers better type-safety. */ @Deprecated public static <E> ImmutableSortedMultiset.Builder<E> builder() { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass a parameter of type {@code Comparable} to use * {@link ImmutableSortedMultiset#of(Comparable)}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E element) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use * {@link ImmutableSortedMultiset#of(Comparable, Comparable)}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use * {@link ImmutableSortedMultiset#of(Comparable, Comparable, Comparable)}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link * ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable)}. </b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3, E e4) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link * ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable, * Comparable)} . </b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3, E e4, E e5) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link * ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable, * Comparable, Comparable, Comparable...)} . </b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain non-{@code * Comparable} elements.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass parameters of type {@code Comparable} to use * {@link ImmutableSortedMultiset#copyOf(Comparable[])}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> copyOf(E[] elements) { throw new UnsupportedOperationException(); } /* * We would like to include an unsupported "<E> copyOf(Iterable<E>)" here, providing only the * properly typed "<E extends Comparable<E>> copyOf(Iterable<E>)" in ImmutableSortedMultiset (and * likewise for the Iterator equivalent). However, due to a change in Sun's interpretation of the * JLS (as described at http://bugs.sun.com/view_bug.do?bug_id=6182950), the OpenJDK 7 compiler * available as of this writing rejects our attempts. To maintain compatibility with that version * and with any other compilers that interpret the JLS similarly, there is no definition of * copyOf() here, and the definition in ImmutableSortedMultiset matches that in * ImmutableMultiset. * * The result is that ImmutableSortedMultiset.copyOf() may be called on non-Comparable elements. * We have not discovered a better solution. In retrospect, the static factory methods should * have gone in a separate class so that ImmutableSortedMultiset wouldn't "inherit" * too-permissive factory methods from ImmutableMultiset. */ }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableSortedMultisetFauxverideShim.java
Java
asf20
7,313
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Maps.EntryTransformer; import java.lang.reflect.Array; import java.util.Collections; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Hayward Chan */ @GwtCompatible(emulated = true) final class Platform { /** * 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 */ static <T> T[] newArray(T[] reference, int length) { Class<?> type = reference.getClass().getComponentType(); // the cast is safe because // result.getClass() == reference.getClass().getComponentType() @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(type, length); return result; } static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return Collections.newSetFromMap(map); } /** * Configures the given map maker to use weak keys, if possible; does nothing * otherwise (i.e., in GWT). This is sometimes acceptable, when only * server-side code could generate enough volume that reclamation becomes * important. */ static MapMaker tryWeakKeys(MapMaker mapMaker) { return mapMaker.weakKeys(); } static <K, V1, V2> SortedMap<K, V2> mapsTransformEntriesSortedMap( SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return (fromMap instanceof NavigableMap) ? Maps.transformEntries((NavigableMap<K, V1>) fromMap, transformer) : Maps.transformEntriesIgnoreNavigable(fromMap, transformer); } static <K, V> SortedMap<K, V> mapsAsMapSortedSet(SortedSet<K> set, Function<? super K, V> function) { return (set instanceof NavigableSet) ? Maps.asMap((NavigableSet<K>) set, function) : Maps.asMapSortedIgnoreNavigable(set, function); } static <E> SortedSet<E> setsFilterSortedSet(SortedSet<E> set, Predicate<? super E> predicate) { return (set instanceof NavigableSet) ? Sets.filter((NavigableSet<E>) set, predicate) : Sets.filterSortedIgnoreNavigable(set, predicate); } static <K, V> SortedMap<K, V> mapsFilterSortedMap(SortedMap<K, V> map, Predicate<? super Map.Entry<K, V>> predicate) { return (map instanceof NavigableMap) ? Maps.filterEntries((NavigableMap<K, V>) map, predicate) : Maps.filterSortedIgnoreNavigable(map, predicate); } private Platform() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Platform.java
Java
asf20
3,428
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Comparator; /** An ordering that tries several comparators in order. */ @GwtCompatible(serializable = true) final class CompoundOrdering<T> extends Ordering<T> implements Serializable { final ImmutableList<Comparator<? super T>> comparators; CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) { this.comparators = ImmutableList.<Comparator<? super T>>of(primary, secondary); } CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) { this.comparators = ImmutableList.copyOf(comparators); } @Override public int compare(T left, T right) { // Avoid using the Iterator to avoid generating garbage (issue 979). int size = comparators.size(); for (int i = 0; i < size; i++) { int result = comparators.get(i).compare(left, right); if (result != 0) { return result; } } return 0; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof CompoundOrdering) { CompoundOrdering<?> that = (CompoundOrdering<?>) object; return this.comparators.equals(that.comparators); } return false; } @Override public int hashCode() { return comparators.hashCode(); } @Override public String toString() { return "Ordering.compound(" + comparators + ")"; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/CompoundOrdering.java
Java
asf20
2,167
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** An ordering that treats {@code null} as less than all other values. */ @GwtCompatible(serializable = true) final class NullsFirstOrdering<T> extends Ordering<T> implements Serializable { final Ordering<? super T> ordering; NullsFirstOrdering(Ordering<? super T> ordering) { this.ordering = ordering; } @Override public int compare(@Nullable T left, @Nullable T right) { if (left == right) { return 0; } if (left == null) { return RIGHT_IS_GREATER; } if (right == null) { return LEFT_IS_GREATER; } return ordering.compare(left, right); } @Override public <S extends T> Ordering<S> reverse() { // ordering.reverse() might be optimized, so let it do its thing return ordering.reverse().nullsLast(); } @SuppressWarnings("unchecked") // still need the right way to explain this @Override public <S extends T> Ordering<S> nullsFirst() { return (Ordering<S>) this; } @Override public <S extends T> Ordering<S> nullsLast() { return ordering.nullsLast(); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof NullsFirstOrdering) { NullsFirstOrdering<?> that = (NullsFirstOrdering<?>) object; return this.ordering.equals(that.ordering); } return false; } @Override public int hashCode() { return ordering.hashCode() ^ 957692532; // meaningless } @Override public String toString() { return ordering + ".nullsFirst()"; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/NullsFirstOrdering.java
Java
asf20
2,345
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import java.util.Map.Entry; /** * An interface for all filtered multimap types. * * @author Louis Wasserman */ @GwtCompatible interface FilteredMultimap<K, V> extends Multimap<K, V> { Multimap<K, V> unfiltered(); Predicate<? super Entry<K, V>> entryPredicate(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/FilteredMultimap.java
Java
asf20
1,009
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * A supertype for filtered {@link SetMultimap} implementations. * * @author Louis Wasserman */ @GwtCompatible interface FilteredSetMultimap<K, V> extends FilteredMultimap<K, V>, SetMultimap<K, V> { @Override SetMultimap<K, V> unfiltered(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/FilteredSetMultimap.java
Java
asf20
946
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import java.util.Set; /** * A skeleton implementation of a descending multiset. Only needs * {@code forwardMultiset()} and {@code entryIterator()}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) abstract class DescendingMultiset<E> extends ForwardingMultiset<E> implements SortedMultiset<E> { abstract SortedMultiset<E> forwardMultiset(); private transient Comparator<? super E> comparator; @Override public Comparator<? super E> comparator() { Comparator<? super E> result = comparator; if (result == null) { return comparator = Ordering.from(forwardMultiset().comparator()).<E>reverse(); } return result; } private transient NavigableSet<E> elementSet; @Override public NavigableSet<E> elementSet() { NavigableSet<E> result = elementSet; if (result == null) { return elementSet = new SortedMultisets.NavigableElementSet<E>(this); } return result; } @Override public Entry<E> pollFirstEntry() { return forwardMultiset().pollLastEntry(); } @Override public Entry<E> pollLastEntry() { return forwardMultiset().pollFirstEntry(); } @Override public SortedMultiset<E> headMultiset(E toElement, BoundType boundType) { return forwardMultiset().tailMultiset(toElement, boundType) .descendingMultiset(); } @Override public SortedMultiset<E> subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { return forwardMultiset().subMultiset(toElement, toBoundType, fromElement, fromBoundType).descendingMultiset(); } @Override public SortedMultiset<E> tailMultiset(E fromElement, BoundType boundType) { return forwardMultiset().headMultiset(fromElement, boundType) .descendingMultiset(); } @Override protected Multiset<E> delegate() { return forwardMultiset(); } @Override public SortedMultiset<E> descendingMultiset() { return forwardMultiset(); } @Override public Entry<E> firstEntry() { return forwardMultiset().lastEntry(); } @Override public Entry<E> lastEntry() { return forwardMultiset().firstEntry(); } abstract Iterator<Entry<E>> entryIterator(); private transient Set<Entry<E>> entrySet; @Override public Set<Entry<E>> entrySet() { Set<Entry<E>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } Set<Entry<E>> createEntrySet() { return new Multisets.EntrySet<E>() { @Override Multiset<E> multiset() { return DescendingMultiset.this; } @Override public Iterator<Entry<E>> iterator() { return entryIterator(); } @Override public int size() { return forwardMultiset().entrySet().size(); } }; } @Override public Iterator<E> iterator() { return Multisets.iteratorImpl(this); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return entrySet().toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/DescendingMultiset.java
Java
asf20
3,882
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A general-purpose bimap implementation using any two backing {@code Map} * instances. * * <p>Note that this class contains {@code equals()} calls that keep it from * supporting {@code IdentityHashMap} backing maps. * * @author Kevin Bourrillion * @author Mike Bostock */ @GwtCompatible(emulated = true) abstract class AbstractBiMap<K, V> extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable { private transient Map<K, V> delegate; transient AbstractBiMap<V, K> inverse; /** Package-private constructor for creating a map-backed bimap. */ AbstractBiMap(Map<K, V> forward, Map<V, K> backward) { setDelegates(forward, backward); } /** Private constructor for inverse bimap. */ private AbstractBiMap(Map<K, V> backward, AbstractBiMap<V, K> forward) { delegate = backward; inverse = forward; } @Override protected Map<K, V> delegate() { return delegate; } /** * Returns its input, or throws an exception if this is not a valid key. */ K checkKey(@Nullable K key) { return key; } /** * Returns its input, or throws an exception if this is not a valid value. */ V checkValue(@Nullable V value) { return value; } /** * Specifies the delegate maps going in each direction. Called by the * constructor and by subclasses during deserialization. */ void setDelegates(Map<K, V> forward, Map<V, K> backward) { checkState(delegate == null); checkState(inverse == null); checkArgument(forward.isEmpty()); checkArgument(backward.isEmpty()); checkArgument(forward != backward); delegate = forward; inverse = new Inverse<V, K>(backward, this); } void setInverse(AbstractBiMap<V, K> inverse) { this.inverse = inverse; } // Query Operations (optimizations) @Override public boolean containsValue(@Nullable Object value) { return inverse.containsKey(value); } // Modification Operations @Override public V put(@Nullable K key, @Nullable V value) { return putInBothMaps(key, value, false); } @Override public V forcePut(@Nullable K key, @Nullable V value) { return putInBothMaps(key, value, true); } private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) { checkKey(key); checkValue(value); boolean containedKey = containsKey(key); if (containedKey && Objects.equal(value, get(key))) { return value; } if (force) { inverse().remove(value); } else { checkArgument(!containsValue(value), "value already present: %s", value); } V oldValue = delegate.put(key, value); updateInverseMap(key, containedKey, oldValue, value); return oldValue; } private void updateInverseMap( K key, boolean containedKey, V oldValue, V newValue) { if (containedKey) { removeFromInverseMap(oldValue); } inverse.delegate.put(newValue, key); } @Override public V remove(@Nullable Object key) { return containsKey(key) ? removeFromBothMaps(key) : null; } private V removeFromBothMaps(Object key) { V oldValue = delegate.remove(key); removeFromInverseMap(oldValue); return oldValue; } private void removeFromInverseMap(V oldValue) { inverse.delegate.remove(oldValue); } // Bulk Operations @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { delegate.clear(); inverse.delegate.clear(); } // Views @Override public BiMap<V, K> inverse() { return inverse; } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = new KeySet() : result; } private class KeySet extends ForwardingSet<K> { @Override protected Set<K> delegate() { return delegate.keySet(); } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object key) { if (!contains(key)) { return false; } removeFromBothMaps(key); return true; } @Override public boolean removeAll(Collection<?> keysToRemove) { return standardRemoveAll(keysToRemove); } @Override public boolean retainAll(Collection<?> keysToRetain) { return standardRetainAll(keysToRetain); } @Override public Iterator<K> iterator() { return Maps.keyIterator(entrySet().iterator()); } } private transient Set<V> valueSet; @Override public Set<V> values() { /* * We can almost reuse the inverse's keySet, except we have to fix the * iteration order so that it is consistent with the forward map. */ Set<V> result = valueSet; return (result == null) ? valueSet = new ValueSet() : result; } private class ValueSet extends ForwardingSet<V> { final Set<V> valuesDelegate = inverse.keySet(); @Override protected Set<V> delegate() { return valuesDelegate; } @Override public Iterator<V> iterator() { return Maps.valueIterator(entrySet().iterator()); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } private transient 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>> { final Set<Entry<K, V>> esDelegate = delegate.entrySet(); @Override protected Set<Entry<K, V>> delegate() { return esDelegate; } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object object) { if (!esDelegate.contains(object)) { return false; } // safe because esDelgate.contains(object). Entry<?, ?> entry = (Entry<?, ?>) object; inverse.delegate.remove(entry.getValue()); /* * Remove the mapping in inverse before removing from esDelegate because * if entry is part of esDelegate, entry might be invalidated after the * mapping is removed from esDelegate. */ esDelegate.remove(entry); return true; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> iterator = esDelegate.iterator(); return new Iterator<Entry<K, V>>() { Entry<K, V> entry; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<K, V> next() { entry = iterator.next(); final Entry<K, V> finalEntry = entry; return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return finalEntry; } @Override public V setValue(V value) { // Preconditions keep the map and inverse consistent. checkState(contains(this), "entry no longer in map"); // similar to putInBothMaps, but set via entry if (Objects.equal(value, getValue())) { return value; } checkArgument(!containsValue(value), "value already present: %s", value); V oldValue = finalEntry.setValue(value); checkState(Objects.equal(value, get(getKey())), "entry no longer in map"); updateInverseMap(getKey(), true, oldValue, value); return oldValue; } }; } @Override public void remove() { checkRemove(entry != null); V value = entry.getValue(); iterator.remove(); removeFromInverseMap(value); } }; } // See java.util.Collections.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } /** The inverse of any other {@code AbstractBiMap} subclass. */ private static class Inverse<K, V> extends AbstractBiMap<K, V> { private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) { super(backward, forward); } /* * Serialization stores the forward bimap, the inverse of this inverse. * Deserialization calls inverse() on the forward bimap and returns that * inverse. * * If a bimap and its inverse are serialized together, the deserialized * instances have inverse() methods that return the other. */ @Override K checkKey(K key) { return inverse.checkValue(key); } @Override V checkValue(V value) { return inverse.checkKey(value); } /** * @serialData the forward bimap */ @GwtIncompatible("java.io.ObjectOuputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(inverse()); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); setInverse((AbstractBiMap<V, K>) stream.readObject()); } @GwtIncompatible("Not needed in the emulated source.") Object readResolve() { return inverse().inverse(); } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractBiMap.java
Java
asf20
11,607
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; /** * List returned by {@link ImmutableCollection#asList} that delegates {@code contains} checks * to the backing collection. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") abstract class ImmutableAsList<E> extends ImmutableList<E> { abstract ImmutableCollection<E> delegateCollection(); @Override public boolean contains(Object target) { // The collection's contains() is at least as fast as ImmutableList's // and is often faster. return delegateCollection().contains(target); } @Override public int size() { return delegateCollection().size(); } @Override public boolean isEmpty() { return delegateCollection().isEmpty(); } @Override boolean isPartialView() { return delegateCollection().isPartialView(); } /** * Serialized form that leads to the same performance as the original list. */ @GwtIncompatible("serialization") static class SerializedForm implements Serializable { final ImmutableCollection<?> collection; SerializedForm(ImmutableCollection<?> collection) { this.collection = collection; } Object readResolve() { return collection.asList(); } private static final long serialVersionUID = 0; } @GwtIncompatible("serialization") private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm(delegateCollection()); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableAsList.java
Java
asf20
2,474
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; /** * A sorted multiset which forwards all its method calls to another sorted multiset. Subclasses * should override one or more methods to modify the behavior of the backing multiset as desired * per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingSortedMultiset} forward * <b>indiscriminately</b> to the methods of the delegate. For example, overriding * {@link #add(Object, int)} alone <b>will not</b> change the behavior of {@link #add(Object)}, * which can lead to unexpected behavior. In this case, you should override {@code add(Object)} as * well, either providing your own implementation, or delegating to the provided {@code * standardAdd} method. * * <p>The {@code standard} methods and any collection views they return are not guaranteed to be * thread-safe, even when all of the methods that they depend on are thread-safe. * * @author Louis Wasserman * @since 15.0 */ @Beta @GwtCompatible(emulated = true) public abstract class ForwardingSortedMultiset<E> extends ForwardingMultiset<E> implements SortedMultiset<E> { /** Constructor for use by subclasses. */ protected ForwardingSortedMultiset() {} @Override protected abstract SortedMultiset<E> delegate(); @Override public NavigableSet<E> elementSet() { return (NavigableSet<E>) super.elementSet(); } /** * A sensible implementation of {@link SortedMultiset#elementSet} in terms of the following * methods: {@link SortedMultiset#clear}, {@link SortedMultiset#comparator}, {@link * SortedMultiset#contains}, {@link SortedMultiset#containsAll}, {@link SortedMultiset#count}, * {@link SortedMultiset#firstEntry} {@link SortedMultiset#headMultiset}, {@link * SortedMultiset#isEmpty}, {@link SortedMultiset#lastEntry}, {@link SortedMultiset#subMultiset}, * {@link SortedMultiset#tailMultiset}, the {@code size()} and {@code iterator()} methods of * {@link SortedMultiset#entrySet}, and {@link SortedMultiset#remove(Object, int)}. In many * situations, you may wish to override {@link SortedMultiset#elementSet} to forward to this * implementation or a subclass thereof. */ protected class StandardElementSet extends SortedMultisets.NavigableElementSet<E> { /** Constructor for use by subclasses. */ public StandardElementSet() { super(ForwardingSortedMultiset.this); } } @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override public SortedMultiset<E> descendingMultiset() { return delegate().descendingMultiset(); } /** * A skeleton implementation of a descending multiset view. Normally, * {@link #descendingMultiset()} will not reflect any changes you make to the behavior of methods * such as {@link #add(Object)} or {@link #pollFirstEntry}. This skeleton implementation * correctly delegates each of its operations to the appropriate methods of this {@code * ForwardingSortedMultiset}. * * In many cases, you may wish to override {@link #descendingMultiset()} to return an instance of * a subclass of {@code StandardDescendingMultiset}. */ protected abstract class StandardDescendingMultiset extends DescendingMultiset<E> { /** Constructor for use by subclasses. */ public StandardDescendingMultiset() {} @Override SortedMultiset<E> forwardMultiset() { return ForwardingSortedMultiset.this; } } @Override public Entry<E> firstEntry() { return delegate().firstEntry(); } /** * A sensible definition of {@link #firstEntry()} in terms of {@code entrySet().iterator()}. * * If you override {@link #entrySet()}, you may wish to override {@link #firstEntry()} to forward * to this implementation. */ protected Entry<E> standardFirstEntry() { Iterator<Entry<E>> entryIterator = entrySet().iterator(); if (!entryIterator.hasNext()) { return null; } Entry<E> entry = entryIterator.next(); return Multisets.immutableEntry(entry.getElement(), entry.getCount()); } @Override public Entry<E> lastEntry() { return delegate().lastEntry(); } /** * A sensible definition of {@link #lastEntry()} in terms of {@code * descendingMultiset().entrySet().iterator()}. * * If you override {@link #descendingMultiset} or {@link #entrySet()}, you may wish to override * {@link #firstEntry()} to forward to this implementation. */ protected Entry<E> standardLastEntry() { Iterator<Entry<E>> entryIterator = descendingMultiset() .entrySet() .iterator(); if (!entryIterator.hasNext()) { return null; } Entry<E> entry = entryIterator.next(); return Multisets.immutableEntry(entry.getElement(), entry.getCount()); } @Override public Entry<E> pollFirstEntry() { return delegate().pollFirstEntry(); } /** * A sensible definition of {@link #pollFirstEntry()} in terms of {@code entrySet().iterator()}. * * If you override {@link #entrySet()}, you may wish to override {@link #pollFirstEntry()} to * forward to this implementation. */ protected Entry<E> standardPollFirstEntry() { Iterator<Entry<E>> entryIterator = entrySet().iterator(); if (!entryIterator.hasNext()) { return null; } Entry<E> entry = entryIterator.next(); entry = Multisets.immutableEntry(entry.getElement(), entry.getCount()); entryIterator.remove(); return entry; } @Override public Entry<E> pollLastEntry() { return delegate().pollLastEntry(); } /** * A sensible definition of {@link #pollLastEntry()} in terms of {@code * descendingMultiset().entrySet().iterator()}. * * If you override {@link #descendingMultiset()} or {@link #entrySet()}, you may wish to override * {@link #pollLastEntry()} to forward to this implementation. */ protected Entry<E> standardPollLastEntry() { Iterator<Entry<E>> entryIterator = descendingMultiset() .entrySet() .iterator(); if (!entryIterator.hasNext()) { return null; } Entry<E> entry = entryIterator.next(); entry = Multisets.immutableEntry(entry.getElement(), entry.getCount()); entryIterator.remove(); return entry; } @Override public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return delegate().headMultiset(upperBound, boundType); } @Override public SortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return delegate().subMultiset(lowerBound, lowerBoundType, upperBound, upperBoundType); } /** * A sensible definition of {@link #subMultiset(Object, BoundType, Object, BoundType)} in terms * of {@link #headMultiset(Object, BoundType) headMultiset} and * {@link #tailMultiset(Object, BoundType) tailMultiset}. * * If you override either of these methods, you may wish to override * {@link #subMultiset(Object, BoundType, Object, BoundType)} to forward to this implementation. */ protected SortedMultiset<E> standardSubMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType); } @Override public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return delegate().tailMultiset(lowerBound, boundType); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingSortedMultiset.java
Java
asf20
8,276
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /** * A builder for a multimap implementation that allows customization of the backing map and value * collection implementations used in a particular multimap. * * <p>This can be used to easily configure multimap data structure implementations not provided * explicitly in {@code com.google.common.collect}, for example: * * <pre> {@code * ListMultimap<String, Integer> treeListMultimap = * MultimapBuilder.treeKeys().arrayListValues().build(); * SetMultimap<Integer, MyEnum> hashEnumMultimap = * MultimapBuilder.hashKeys().enumSetValues(MyEnum.class).build();}</pre> * * <p>{@code MultimapBuilder} instances are immutable. Invoking a configuration method has no * effect on the receiving instance; you must store and use the new builder instance it returns * instead. * * <p>The generated multimaps are serializable if the key and value types are serializable, * unless stated otherwise in one of the configuration methods. * * @author Louis Wasserman * @param <K0> An upper bound on the key type of the generated multimap. * @param <V0> An upper bound on the value type of the generated multimap. * @since 16.0 */ @Beta @GwtCompatible public abstract class MultimapBuilder<K0, V0> { /* * Leaving K and V as upper bounds rather than the actual key and value types allows type * parameters to be left implicit more often. CacheBuilder uses the same technique. */ private MultimapBuilder() {} private static final int DEFAULT_EXPECTED_KEYS = 8; /** * Uses a {@link HashMap} to map keys to value collections. */ public static MultimapBuilderWithKeys<Object> hashKeys() { return hashKeys(DEFAULT_EXPECTED_KEYS); } /** * Uses a {@link HashMap} to map keys to value collections, initialized to expect the specified * number of keys. * * @throws IllegalArgumentException if {@code expectedKeys < 0} */ public static MultimapBuilderWithKeys<Object> hashKeys(final int expectedKeys) { checkNonnegative(expectedKeys, "expectedKeys"); return new MultimapBuilderWithKeys<Object>() { @Override <K, V> Map<K, Collection<V>> createMap() { return new HashMap<K, Collection<V>>(expectedKeys); } }; } /** * Uses a {@link LinkedHashMap} to map keys to value collections. * * <p>The collections returned by {@link Multimap#keySet()}, {@link Multimap#keys()}, and * {@link Multimap#asMap()} will iterate through the keys in the order that they were first added * to the multimap, save that if all values associated with a key are removed and then the key is * added back into the multimap, that key will come last in the key iteration order. */ public static MultimapBuilderWithKeys<Object> linkedHashKeys() { return linkedHashKeys(DEFAULT_EXPECTED_KEYS); } /** * Uses a {@link LinkedHashMap} to map keys to value collections, initialized to expect the * specified number of keys. * * <p>The collections returned by {@link Multimap#keySet()}, {@link Multimap#keys()}, and * {@link Multimap#asMap()} will iterate through the keys in the order that they were first added * to the multimap, save that if all values associated with a key are removed and then the key is * added back into the multimap, that key will come last in the key iteration order. */ public static MultimapBuilderWithKeys<Object> linkedHashKeys(final int expectedKeys) { checkNonnegative(expectedKeys, "expectedKeys"); return new MultimapBuilderWithKeys<Object>() { @Override <K, V> Map<K, Collection<V>> createMap() { return new LinkedHashMap<K, Collection<V>>(expectedKeys); } }; } /** * Uses a naturally-ordered {@link TreeMap} to map keys to value collections. * * <p>The collections returned by {@link Multimap#keySet()}, {@link Multimap#keys()}, and * {@link Multimap#asMap()} will iterate through the keys in sorted order. * * <p>For all multimaps generated by the resulting builder, the {@link Multimap#keySet()} can be * safely cast to a {@link java.util.SortedSet}, and the {@link Multimap#asMap()} can safely be * cast to a {@link java.util.SortedMap}. */ @SuppressWarnings("rawtypes") public static MultimapBuilderWithKeys<Comparable> treeKeys() { return treeKeys(Ordering.natural()); } /** * Uses a {@link TreeMap} sorted by the specified comparator to map keys to value collections. * * <p>The collections returned by {@link Multimap#keySet()}, {@link Multimap#keys()}, and * {@link Multimap#asMap()} will iterate through the keys in sorted order. * * <p>For all multimaps generated by the resulting builder, the {@link Multimap#keySet()} can be * safely cast to a {@link java.util.SortedSet}, and the {@link Multimap#asMap()} can safely be * cast to a {@link java.util.SortedMap}. * * <p>Multimaps generated by the resulting builder will not be serializable if {@code comparator} * is not serializable. */ public static <K0> MultimapBuilderWithKeys<K0> treeKeys(final Comparator<K0> comparator) { checkNotNull(comparator); return new MultimapBuilderWithKeys<K0>() { @Override <K extends K0, V> Map<K, Collection<V>> createMap() { return new TreeMap<K, Collection<V>>(comparator); } }; } /** * Uses an {@link EnumMap} to map keys to value collections. */ public static <K0 extends Enum<K0>> MultimapBuilderWithKeys<K0> enumKeys( final Class<K0> keyClass) { checkNotNull(keyClass); return new MultimapBuilderWithKeys<K0>() { @SuppressWarnings("unchecked") @Override <K extends K0, V> Map<K, Collection<V>> createMap() { // K must actually be K0, since enums are effectively final // (their subclasses are inaccessible) return (Map<K, Collection<V>>) new EnumMap<K0, Collection<V>>(keyClass); } }; } private static final class ArrayListSupplier<V> implements Supplier<List<V>>, Serializable { private final int expectedValuesPerKey; ArrayListSupplier(int expectedValuesPerKey) { this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); } @Override public List<V> get() { return new ArrayList<V>(expectedValuesPerKey); } } private enum LinkedListSupplier implements Supplier<List<Object>> { INSTANCE; public static <V> Supplier<List<V>> instance() { // Each call generates a fresh LinkedList, which can serve as a List<V> for any V. @SuppressWarnings({"rawtypes", "unchecked"}) Supplier<List<V>> result = (Supplier) INSTANCE; return result; } @Override public List<Object> get() { return new LinkedList<Object>(); } } private static final class HashSetSupplier<V> implements Supplier<Set<V>>, Serializable { private final int expectedValuesPerKey; HashSetSupplier(int expectedValuesPerKey) { this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); } @Override public Set<V> get() { return new HashSet<V>(expectedValuesPerKey); } } private static final class LinkedHashSetSupplier<V> implements Supplier<Set<V>>, Serializable { private final int expectedValuesPerKey; LinkedHashSetSupplier(int expectedValuesPerKey) { this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); } @Override public Set<V> get() { return new LinkedHashSet<V>(expectedValuesPerKey); } } private static final class TreeSetSupplier<V> implements Supplier<SortedSet<V>>, Serializable { private final Comparator<? super V> comparator; TreeSetSupplier(Comparator<? super V> comparator) { this.comparator = checkNotNull(comparator); } @Override public SortedSet<V> get() { return new TreeSet<V>(comparator); } } private static final class EnumSetSupplier<V extends Enum<V>> implements Supplier<Set<V>>, Serializable { private final Class<V> clazz; EnumSetSupplier(Class<V> clazz) { this.clazz = checkNotNull(clazz); } @Override public Set<V> get() { return EnumSet.noneOf(clazz); } } /** * An intermediate stage in a {@link MultimapBuilder} in which the key-value collection map * implementation has been specified, but the value collection implementation has not. * * @param <K0> The upper bound on the key type of the generated multimap. */ public abstract static class MultimapBuilderWithKeys<K0> { private static final int DEFAULT_EXPECTED_VALUES_PER_KEY = 2; MultimapBuilderWithKeys() {} abstract <K extends K0, V> Map<K, Collection<V>> createMap(); /** * Uses an {@link ArrayList} to store value collections. */ public ListMultimapBuilder<K0, Object> arrayListValues() { return arrayListValues(DEFAULT_EXPECTED_VALUES_PER_KEY); } /** * Uses an {@link ArrayList} to store value collections, initialized to expect the specified * number of values per key. * * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} */ public ListMultimapBuilder<K0, Object> arrayListValues(final int expectedValuesPerKey) { checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); return new ListMultimapBuilder<K0, Object>() { @Override public <K extends K0, V> ListMultimap<K, V> build() { return Multimaps.newListMultimap( MultimapBuilderWithKeys.this.<K, V>createMap(), new ArrayListSupplier<V>(expectedValuesPerKey)); } }; } /** * Uses a {@link LinkedList} to store value collections. */ public ListMultimapBuilder<K0, Object> linkedListValues() { return new ListMultimapBuilder<K0, Object>() { @Override public <K extends K0, V> ListMultimap<K, V> build() { return Multimaps.newListMultimap( MultimapBuilderWithKeys.this.<K, V>createMap(), LinkedListSupplier.<V>instance()); } }; } /** * Uses a {@link HashSet} to store value collections. */ public SetMultimapBuilder<K0, Object> hashSetValues() { return hashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY); } /** * Uses a {@link HashSet} to store value collections, initialized to expect the specified number * of values per key. * * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} */ public SetMultimapBuilder<K0, Object> hashSetValues(final int expectedValuesPerKey) { checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); return new SetMultimapBuilder<K0, Object>() { @Override public <K extends K0, V> SetMultimap<K, V> build() { return Multimaps.newSetMultimap( MultimapBuilderWithKeys.this.<K, V>createMap(), new HashSetSupplier<V>(expectedValuesPerKey)); } }; } /** * Uses a {@link LinkedHashSet} to store value collections. */ public SetMultimapBuilder<K0, Object> linkedHashSetValues() { return linkedHashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY); } /** * Uses a {@link LinkedHashSet} to store value collections, initialized to expect the specified * number of values per key. * * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} */ public SetMultimapBuilder<K0, Object> linkedHashSetValues(final int expectedValuesPerKey) { checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); return new SetMultimapBuilder<K0, Object>() { @Override public <K extends K0, V> SetMultimap<K, V> build() { return Multimaps.newSetMultimap( MultimapBuilderWithKeys.this.<K, V>createMap(), new LinkedHashSetSupplier<V>(expectedValuesPerKey)); } }; } /** * Uses a naturally-ordered {@link TreeSet} to store value collections. */ @SuppressWarnings("rawtypes") public SortedSetMultimapBuilder<K0, Comparable> treeSetValues() { return treeSetValues(Ordering.natural()); } /** * Uses a {@link TreeSet} ordered by the specified comparator to store value collections. * * <p>Multimaps generated by the resulting builder will not be serializable if * {@code comparator} is not serializable. */ public <V0> SortedSetMultimapBuilder<K0, V0> treeSetValues(final Comparator<V0> comparator) { checkNotNull(comparator, "comparator"); return new SortedSetMultimapBuilder<K0, V0>() { @Override public <K extends K0, V extends V0> SortedSetMultimap<K, V> build() { return Multimaps.newSortedSetMultimap( MultimapBuilderWithKeys.this.<K, V>createMap(), new TreeSetSupplier<V>(comparator)); } }; } /** * Uses an {@link EnumSet} to store value collections. */ public <V0 extends Enum<V0>> SetMultimapBuilder<K0, V0> enumSetValues( final Class<V0> valueClass) { checkNotNull(valueClass, "valueClass"); return new SetMultimapBuilder<K0, V0>() { @Override public <K extends K0, V extends V0> SetMultimap<K, V> build() { // V must actually be V0, since enums are effectively final // (their subclasses are inaccessible) @SuppressWarnings({"unchecked", "rawtypes"}) Supplier<Set<V>> factory = (Supplier) new EnumSetSupplier<V0>(valueClass); return Multimaps.newSetMultimap( MultimapBuilderWithKeys.this.<K, V>createMap(), factory); } }; } } /** * Returns a new, empty {@code Multimap} with the specified implementation. */ public abstract <K extends K0, V extends V0> Multimap<K, V> build(); /** * Returns a {@code Multimap} with the specified implementation, initialized with the entries of * {@code multimap}. */ public <K extends K0, V extends V0> Multimap<K, V> build( Multimap<? extends K, ? extends V> multimap) { Multimap<K, V> result = build(); result.putAll(multimap); return result; } /** * A specialization of {@link MultimapBuilder} that generates {@link ListMultimap} instances. */ public abstract static class ListMultimapBuilder<K0, V0> extends MultimapBuilder<K0, V0> { ListMultimapBuilder() {} @Override public abstract <K extends K0, V extends V0> ListMultimap<K, V> build(); @Override public <K extends K0, V extends V0> ListMultimap<K, V> build( Multimap<? extends K, ? extends V> multimap) { return (ListMultimap<K, V>) super.build(multimap); } } /** * A specialization of {@link MultimapBuilder} that generates {@link SetMultimap} instances. */ public abstract static class SetMultimapBuilder<K0, V0> extends MultimapBuilder<K0, V0> { SetMultimapBuilder() {} @Override public abstract <K extends K0, V extends V0> SetMultimap<K, V> build(); @Override public <K extends K0, V extends V0> SetMultimap<K, V> build( Multimap<? extends K, ? extends V> multimap) { return (SetMultimap<K, V>) super.build(multimap); } } /** * A specialization of {@link MultimapBuilder} that generates {@link SortedSetMultimap} instances. */ public abstract static class SortedSetMultimapBuilder<K0, V0> extends SetMultimapBuilder<K0, V0> { SortedSetMultimapBuilder() {} @Override public abstract <K extends K0, V extends V0> SortedSetMultimap<K, V> build(); @Override public <K extends K0, V extends V0> SortedSetMultimap<K, V> build( Multimap<? extends K, ? extends V> multimap) { return (SortedSetMultimap<K, V>) super.build(multimap); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/MultimapBuilder.java
Java
asf20
17,245
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.SortedLists.KeyAbsentBehavior.INVERTED_INSERTION_INDEX; import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_HIGHER; import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT; import static com.google.common.collect.SortedLists.KeyPresentBehavior.FIRST_AFTER; import static com.google.common.collect.SortedLists.KeyPresentBehavior.FIRST_PRESENT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An immutable sorted set with one or more elements. TODO(jlevy): Consider * separate class for a single-element sorted set. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") final class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> { private transient final ImmutableList<E> elements; RegularImmutableSortedSet( ImmutableList<E> elements, Comparator<? super E> comparator) { super(comparator); this.elements = elements; checkArgument(!elements.isEmpty()); } @Override public UnmodifiableIterator<E> iterator() { return elements.iterator(); } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<E> descendingIterator() { return elements.reverse().iterator(); } @Override public boolean isEmpty() { return false; } @Override public int size() { return elements.size(); } @Override public boolean contains(Object o) { try { return o != null && unsafeBinarySearch(o) >= 0; } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { // TODO(jlevy): For optimal performance, use a binary search when // targets.size() < size() / log(size()) // TODO(kevinb): see if we can share code with OrderedIterator after it // graduates from labs. if (targets instanceof Multiset) { targets = ((Multiset<?>) targets).elementSet(); } if (!SortedIterables.hasSameComparator(comparator(), targets) || (targets.size() <= 1)) { return super.containsAll(targets); } /* * If targets is a sorted set with the same comparator, containsAll can run * in O(n) time stepping through the two collections. */ PeekingIterator<E> thisIterator = Iterators.peekingIterator(iterator()); Iterator<?> thatIterator = targets.iterator(); Object target = thatIterator.next(); try { while (thisIterator.hasNext()) { int cmp = unsafeCompare(thisIterator.peek(), target); if (cmp < 0) { thisIterator.next(); } else if (cmp == 0) { if (!thatIterator.hasNext()) { return true; } target = thatIterator.next(); } else if (cmp > 0) { return false; } } } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } return false; } private int unsafeBinarySearch(Object key) throws ClassCastException { return Collections.binarySearch(elements, key, unsafeComparator()); } @Override boolean isPartialView() { return elements.isPartialView(); } @Override int copyIntoArray(Object[] dst, int offset) { return elements.copyIntoArray(dst, offset); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (!(object instanceof Set)) { return false; } Set<?> that = (Set<?>) object; if (size() != that.size()) { return false; } if (SortedIterables.hasSameComparator(comparator, that)) { Iterator<?> otherIterator = that.iterator(); try { Iterator<E> iterator = iterator(); while (iterator.hasNext()) { Object element = iterator.next(); Object otherElement = otherIterator.next(); if (otherElement == null || unsafeCompare(element, otherElement) != 0) { return false; } } return true; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; // concurrent change to other set } } return this.containsAll(that); } @Override public E first() { return elements.get(0); } @Override public E last() { return elements.get(size() - 1); } @Override public E lower(E element) { int index = headIndex(element, false) - 1; return (index == -1) ? null : elements.get(index); } @Override public E floor(E element) { int index = headIndex(element, true) - 1; return (index == -1) ? null : elements.get(index); } @Override public E ceiling(E element) { int index = tailIndex(element, true); return (index == size()) ? null : elements.get(index); } @Override public E higher(E element) { int index = tailIndex(element, false); return (index == size()) ? null : elements.get(index); } @Override ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) { return getSubSet(0, headIndex(toElement, inclusive)); } int headIndex(E toElement, boolean inclusive) { return SortedLists.binarySearch( elements, checkNotNull(toElement), comparator(), inclusive ? FIRST_AFTER : FIRST_PRESENT, NEXT_HIGHER); } @Override ImmutableSortedSet<E> subSetImpl( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return tailSetImpl(fromElement, fromInclusive) .headSetImpl(toElement, toInclusive); } @Override ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) { return getSubSet(tailIndex(fromElement, inclusive), size()); } int tailIndex(E fromElement, boolean inclusive) { return SortedLists.binarySearch( elements, checkNotNull(fromElement), comparator(), inclusive ? FIRST_PRESENT : FIRST_AFTER, NEXT_HIGHER); } // Pretend the comparator can compare anything. If it turns out it can't // compare two elements, it'll throw a CCE. Only methods that are specified to // throw CCE should call this. @SuppressWarnings("unchecked") Comparator<Object> unsafeComparator() { return (Comparator<Object>) comparator; } ImmutableSortedSet<E> getSubSet(int newFromIndex, int newToIndex) { if (newFromIndex == 0 && newToIndex == size()) { return this; } else if (newFromIndex < newToIndex) { return new RegularImmutableSortedSet<E>( elements.subList(newFromIndex, newToIndex), comparator); } else { return emptySet(comparator); } } @Override int indexOf(@Nullable Object target) { if (target == null) { return -1; } int position; try { position = SortedLists.binarySearch(elements, target, unsafeComparator(), ANY_PRESENT, INVERTED_INSERTION_INDEX); } catch (ClassCastException e) { return -1; } return (position >= 0) ? position : -1; } @Override ImmutableList<E> createAsList() { return new ImmutableSortedAsList<E>(this, elements); } @Override ImmutableSortedSet<E> createDescendingSet() { return new RegularImmutableSortedSet<E>(elements.reverse(), Ordering.from(comparator).reverse()); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularImmutableSortedSet.java
Java
asf20
8,390
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.SortedSet; import javax.annotation.Nullable; /** * Basic implementation of the {@link SortedSetMultimap} interface. It's a * wrapper around {@link AbstractMapBasedMultimap} that converts the returned * collections into sorted sets. The {@link #createCollection} method * must return a {@code SortedSet}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractSortedSetMultimap<K, V> extends AbstractSetMultimap<K, V> implements SortedSetMultimap<K, V> { /** * Creates a new multimap that uses the provided map. * * @param map place to store the mapping from each key to its corresponding * values */ protected AbstractSortedSetMultimap(Map<K, Collection<V>> map) { super(map); } @Override abstract SortedSet<V> createCollection(); @Override SortedSet<V> createUnmodifiableEmptyCollection() { Comparator<? super V> comparator = valueComparator(); if (comparator == null) { return Collections.unmodifiableSortedSet(createCollection()); } else { return ImmutableSortedSet.emptySet(valueComparator()); } } // Following Javadoc copied from Multimap and SortedSetMultimap. /** * Returns a collection view of all values associated with a key. If no * mappings in the multimap have the provided key, an empty collection is * returned. * * <p>Changes to the returned collection will update the underlying multimap, * and vice versa. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link Collection} specified in the {@link Multimap} interface. */ @Override public SortedSet<V> get(@Nullable K key) { return (SortedSet<V>) super.get(key); } /** * Removes all values associated with a given key. The returned collection is * immutable. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link Collection} specified in the {@link Multimap} interface. */ @Override public SortedSet<V> removeAll(@Nullable Object key) { return (SortedSet<V>) super.removeAll(key); } /** * Stores a collection of values with the same key, replacing any existing * values for that key. The returned collection is immutable. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link Collection} specified in the {@link Multimap} interface. * * <p>Any duplicates in {@code values} will be stored in the multimap once. */ @Override public SortedSet<V> replaceValues( @Nullable K key, Iterable<? extends V> values) { return (SortedSet<V>) super.replaceValues(key, values); } /** * Returns a map view that associates each key with the corresponding values * in the multimap. Changes to the returned map, such as element removal, will * update the underlying multimap. The map does not support {@code setValue} * on its entries, {@code put}, or {@code putAll}. * * <p>When passed a key that is present in the map, {@code * asMap().get(Object)} has the same behavior as {@link #get}, returning a * live collection. When passed a key that is not present, however, {@code * asMap().get(Object)} returns {@code null} instead of an empty collection. * * <p>Though the method signature doesn't say so explicitly, the returned map * has {@link SortedSet} values. */ @Override public Map<K, Collection<V>> asMap() { return super.asMap(); } /** * {@inheritDoc} * * Consequently, the values do not follow their natural ordering or the * ordering of the value comparator. */ @Override public Collection<V> values() { return super.values(); } private static final long serialVersionUID = 430848587173315748L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractSortedSetMultimap.java
Java
asf20
4,758
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.common.annotations.GwtCompatible; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} * to work around build-system quirks. This annotation should be used * <b>only</b> in {@code com.google.common.collect}. */ @Documented @GwtCompatible @Retention(RUNTIME) @Target(FIELD) @interface GwtTransient { }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/GwtTransient.java
Java
asf20
1,222
/* * 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.NoSuchElementException; import java.util.Queue; /** * A queue which forwards all its method calls to another queue. Subclasses * should override one or more methods to modify the behavior of the backing * queue as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingQueue} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #offer} which can lead to unexpected behavior. In this case, you should * override {@code offer} as well, either providing your own implementation, or * delegating to the provided {@code standardOffer} method. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingQueue<E> extends ForwardingCollection<E> implements Queue<E> { /** Constructor for use by subclasses. */ protected ForwardingQueue() {} @Override protected abstract Queue<E> delegate(); @Override public boolean offer(E o) { return delegate().offer(o); } @Override public E poll() { return delegate().poll(); } @Override public E remove() { return delegate().remove(); } @Override public E peek() { return delegate().peek(); } @Override public E element() { return delegate().element(); } /** * A sensible definition of {@link #offer} in terms of {@link #add}. If you * override {@link #add}, you may wish to override {@link #offer} to forward * to this implementation. * * @since 7.0 */ protected boolean standardOffer(E e) { try { return add(e); } catch (IllegalStateException caught) { return false; } } /** * A sensible definition of {@link #peek} in terms of {@link #element}. If you * override {@link #element}, you may wish to override {@link #peek} to * forward to this implementation. * * @since 7.0 */ protected E standardPeek() { try { return element(); } catch (NoSuchElementException caught) { return null; } } /** * A sensible definition of {@link #poll} in terms of {@link #remove}. If you * override {@link #remove}, you may wish to override {@link #poll} to forward * to this implementation. * * @since 7.0 */ protected E standardPoll() { try { return remove(); } catch (NoSuchElementException caught) { return null; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingQueue.java
Java
asf20
3,426
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.collect.BoundType.CLOSED; import com.google.common.primitives.Ints; import javax.annotation.Nullable; /** * An immutable sorted multiset with one or more distinct elements. * * @author Louis Wasserman */ @SuppressWarnings("serial") // uses writeReplace, not default serialization final class RegularImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private final transient RegularImmutableSortedSet<E> elementSet; private final transient int[] counts; private final transient long[] cumulativeCounts; private final transient int offset; private final transient int length; RegularImmutableSortedMultiset( RegularImmutableSortedSet<E> elementSet, int[] counts, long[] cumulativeCounts, int offset, int length) { this.elementSet = elementSet; this.counts = counts; this.cumulativeCounts = cumulativeCounts; this.offset = offset; this.length = length; } @Override Entry<E> getEntry(int index) { return Multisets.immutableEntry( elementSet.asList().get(index), counts[offset + index]); } @Override public Entry<E> firstEntry() { return getEntry(0); } @Override public Entry<E> lastEntry() { return getEntry(length - 1); } @Override public int count(@Nullable Object element) { int index = elementSet.indexOf(element); return (index == -1) ? 0 : counts[index + offset]; } @Override public int size() { long size = cumulativeCounts[offset + length] - cumulativeCounts[offset]; return Ints.saturatedCast(size); } @Override public ImmutableSortedSet<E> elementSet() { return elementSet; } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return getSubMultiset(0, elementSet.headIndex(upperBound, checkNotNull(boundType) == CLOSED)); } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return getSubMultiset(elementSet.tailIndex(lowerBound, checkNotNull(boundType) == CLOSED), length); } ImmutableSortedMultiset<E> getSubMultiset(int from, int to) { checkPositionIndexes(from, to, length); if (from == to) { return emptyMultiset(comparator()); } else if (from == 0 && to == length) { return this; } else { RegularImmutableSortedSet<E> subElementSet = (RegularImmutableSortedSet<E>) elementSet.getSubSet(from, to); return new RegularImmutableSortedMultiset<E>( subElementSet, counts, cumulativeCounts, offset + from, to - from); } } @Override boolean isPartialView() { return offset > 0 || length < counts.length; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularImmutableSortedMultiset.java
Java
asf20
3,485
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Collection; import javax.annotation.Nullable; /** * An implementation of {@link ContiguousSet} that contains one or more elements. * * @author Gregory Kick */ @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> { private final Range<C> range; RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) { super(domain); this.range = range; } private ContiguousSet<C> intersectionInCurrentDomain(Range<C> other) { return (range.isConnected(other)) ? ContiguousSet.create(range.intersection(other), domain) : new EmptyContiguousSet<C>(domain); } @Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive))); } @Override ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) { // Range would reject our attempt to create (x, x). return new EmptyContiguousSet<C>(domain); } return intersectionInCurrentDomain(Range.range( fromElement, BoundType.forBoolean(fromInclusive), toElement, BoundType.forBoolean(toInclusive))); } @Override ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) { return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); } @GwtIncompatible("not used by GWT emulation") @Override int indexOf(Object target) { return contains(target) ? (int) domain.distance(first(), (C) target) : -1; } @Override public UnmodifiableIterator<C> iterator() { return new AbstractSequentialIterator<C>(first()) { final C last = last(); @Override protected C computeNext(C previous) { return equalsOrThrow(previous, last) ? null : domain.next(previous); } }; } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<C> descendingIterator() { return new AbstractSequentialIterator<C>(last()) { final C first = first(); @Override protected C computeNext(C previous) { return equalsOrThrow(previous, first) ? null : domain.previous(previous); } }; } private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) { return right != null && Range.compareOrThrow(left, right) == 0; } @Override boolean isPartialView() { return false; } @Override public C first() { return range.lowerBound.leastValueAbove(domain); } @Override public C last() { return range.upperBound.greatestValueBelow(domain); } @Override public int size() { long distance = domain.distance(first(), last()); return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1; } @Override public boolean contains(@Nullable Object object) { if (object == null) { return false; } try { return range.contains((C) object); } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { return Collections2.containsAllImpl(this, targets); } @Override public boolean isEmpty() { return false; } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { checkNotNull(other); checkArgument(this.domain.equals(other.domain)); if (other.isEmpty()) { return other; } else { C lowerEndpoint = Ordering.natural().max(this.first(), other.first()); C upperEndpoint = Ordering.natural().min(this.last(), other.last()); return (lowerEndpoint.compareTo(upperEndpoint) < 0) ? ContiguousSet.create(Range.closed(lowerEndpoint, upperEndpoint), domain) : new EmptyContiguousSet<C>(domain); } } @Override public Range<C> range() { return range(CLOSED, CLOSED); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { return Range.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain), range.upperBound.withUpperBoundType(upperBoundType, domain)); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } else if (object instanceof RegularContiguousSet) { RegularContiguousSet<?> that = (RegularContiguousSet<?>) object; if (this.domain.equals(that.domain)) { return this.first().equals(that.first()) && this.last().equals(that.last()); } } return super.equals(object); } // copied to make sure not to use the GWT-emulated version @Override public int hashCode() { return Sets.hashCodeImpl(this); } @GwtIncompatible("serialization") private static final class SerializedForm<C extends Comparable> implements Serializable { final Range<C> range; final DiscreteDomain<C> domain; private SerializedForm(Range<C> range, DiscreteDomain<C> domain) { this.range = range; this.domain = domain; } private Object readResolve() { return new RegularContiguousSet<C>(range, domain); } } @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm<C>(range, domain); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularContiguousSet.java
Java
asf20
6,429
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * Implementation of {@link Table} using hash tables. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link * #columnMap()} have iterators that don't support {@code remove()}. Otherwise, * all optional operations are supported. Null row keys, columns keys, and * values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code * column(columnKey).get(rowKey)} still runs quickly, since the row key is * provided. However, {@code column(columnKey).size()} takes longer, since an * iteration across all row keys occurs. * * <p>Note that this implementation is not synchronized. If multiple threads * access this table concurrently and one of the threads modifies the table, it * must be synchronized externally. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @since 7.0 */ @GwtCompatible(serializable = true) public class HashBasedTable<R, C, V> extends StandardTable<R, C, V> { private static class Factory<C, V> implements Supplier<Map<C, V>>, Serializable { final int expectedSize; Factory(int expectedSize) { this.expectedSize = expectedSize; } @Override public Map<C, V> get() { return Maps.newHashMapWithExpectedSize(expectedSize); } private static final long serialVersionUID = 0; } /** * Creates an empty {@code HashBasedTable}. */ public static <R, C, V> HashBasedTable<R, C, V> create() { return new HashBasedTable<R, C, V>( new HashMap<R, Map<C, V>>(), new Factory<C, V>(0)); } /** * Creates an empty {@code HashBasedTable} with the specified map sizes. * * @param expectedRows the expected number of distinct row keys * @param expectedCellsPerRow the expected number of column key / value * mappings in each row * @throws IllegalArgumentException if {@code expectedRows} or {@code * expectedCellsPerRow} is negative */ public static <R, C, V> HashBasedTable<R, C, V> create( int expectedRows, int expectedCellsPerRow) { checkNonnegative(expectedCellsPerRow, "expectedCellsPerRow"); Map<R, Map<C, V>> backingMap = Maps.newHashMapWithExpectedSize(expectedRows); return new HashBasedTable<R, C, V>( backingMap, new Factory<C, V>(expectedCellsPerRow)); } /** * Creates a {@code HashBasedTable} with the same mappings as the specified * table. * * @param table the table to copy * @throws NullPointerException if any of the row keys, column keys, or values * in {@code table} is null */ public static <R, C, V> HashBasedTable<R, C, V> create( Table<? extends R, ? extends C, ? extends V> table) { HashBasedTable<R, C, V> result = create(); result.putAll(table); return result; } HashBasedTable(Map<R, Map<C, V>> backingMap, Factory<C, V> factory) { super(backingMap, factory); } // Overriding so NullPointerTester test passes. @Override public boolean contains( @Nullable Object rowKey, @Nullable Object columnKey) { return super.contains(rowKey, columnKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { return super.containsColumn(columnKey); } @Override public boolean containsRow(@Nullable Object rowKey) { return super.containsRow(rowKey); } @Override public boolean containsValue(@Nullable Object value) { return super.containsValue(value); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { return super.get(rowKey, columnKey); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj); } @Override public V remove( @Nullable Object rowKey, @Nullable Object columnKey) { return super.remove(rowKey, columnKey); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/HashBasedTable.java
Java
asf20
4,979
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; /** * An ordering that uses the natural order of the string representation of the * values. */ @GwtCompatible(serializable = true) final class UsingToStringOrdering extends Ordering<Object> implements Serializable { static final UsingToStringOrdering INSTANCE = new UsingToStringOrdering(); @Override public int compare(Object left, Object right) { return left.toString().compareTo(right.toString()); } // preserve singleton-ness, so equals() and hashCode() work correctly private Object readResolve() { return INSTANCE; } @Override public String toString() { return "Ordering.usingToString()"; } private UsingToStringOrdering() {} private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/UsingToStringOrdering.java
Java
asf20
1,447
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@code Multimap} that does not allow duplicate key-value * entries and that returns collections whose iterators follow the ordering in * which the data was added to the multimap. * * <p>The collections returned by {@code keySet}, {@code keys}, and {@code * asMap} iterate through the keys in the order they were first added to the * multimap. Similarly, {@code get}, {@code removeAll}, and {@code * replaceValues} return collections that iterate through the values in the * order they were added. The collections generated by {@code entries} and * {@code values} iterate across the key-value mappings in the order they were * added to the multimap. * * <p>The iteration ordering of the collections generated by {@code keySet}, * {@code keys}, and {@code asMap} has a few subtleties. As long as the set of * keys remains unchanged, adding or removing mappings does not affect the key * iteration order. However, if you remove all values associated with a key and * then add the key back to the multimap, that key will come last in the key * iteration order. * * <p>The multimap does not store duplicate key-value pairs. Adding a new * key-value pair equal to an existing key-value pair has no effect. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedSetMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> { /** * Creates a new, empty {@code LinkedHashMultimap} with the default initial * capacities. */ public static <K, V> LinkedHashMultimap<K, V> create() { return new LinkedHashMultimap<K, V>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY); } /** * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold * the specified numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> LinkedHashMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new LinkedHashMultimap<K, V>( Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey)); } /** * Constructs a {@code LinkedHashMultimap} with the same mappings as the * specified multimap. If a key-value mapping appears multiple times in the * input multimap, it only appears once in the constructed multimap. The new * multimap has the same {@link Multimap#entries()} iteration order as the * input multimap, except for excluding duplicate mappings. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> LinkedHashMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY); result.putAll(multimap); return result; } private interface ValueSetLink<K, V> { ValueSetLink<K, V> getPredecessorInValueSet(); ValueSetLink<K, V> getSuccessorInValueSet(); void setPredecessorInValueSet(ValueSetLink<K, V> entry); void setSuccessorInValueSet(ValueSetLink<K, V> entry); } private static <K, V> void succeedsInValueSet(ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) { pred.setSuccessorInValueSet(succ); succ.setPredecessorInValueSet(pred); } private static <K, V> void succeedsInMultimap( ValueEntry<K, V> pred, ValueEntry<K, V> succ) { pred.setSuccessorInMultimap(succ); succ.setPredecessorInMultimap(pred); } private static <K, V> void deleteFromValueSet(ValueSetLink<K, V> entry) { succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet()); } private static <K, V> void deleteFromMultimap(ValueEntry<K, V> entry) { succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap()); } /** * LinkedHashMultimap entries are in no less than three coexisting linked lists: * a bucket in the hash table for a Set<V> associated with a key, the linked list * of insertion-ordered entries in that Set<V>, and the linked list of entries * in the LinkedHashMultimap as a whole. */ @VisibleForTesting static final class ValueEntry<K, V> extends ImmutableEntry<K, V> implements ValueSetLink<K, V> { final int smearedValueHash; @Nullable ValueEntry<K, V> nextInValueBucket; ValueSetLink<K, V> predecessorInValueSet; ValueSetLink<K, V> successorInValueSet; ValueEntry<K, V> predecessorInMultimap; ValueEntry<K, V> successorInMultimap; ValueEntry(@Nullable K key, @Nullable V value, int smearedValueHash, @Nullable ValueEntry<K, V> nextInValueBucket) { super(key, value); this.smearedValueHash = smearedValueHash; this.nextInValueBucket = nextInValueBucket; } boolean matchesValue(@Nullable Object v, int smearedVHash) { return smearedValueHash == smearedVHash && Objects.equal(getValue(), v); } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return predecessorInValueSet; } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return successorInValueSet; } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { predecessorInValueSet = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { successorInValueSet = entry; } public ValueEntry<K, V> getPredecessorInMultimap() { return predecessorInMultimap; } public ValueEntry<K, V> getSuccessorInMultimap() { return successorInMultimap; } public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) { this.successorInMultimap = multimapSuccessor; } public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) { this.predecessorInMultimap = multimapPredecessor; } } private static final int DEFAULT_KEY_CAPACITY = 16; private static final int DEFAULT_VALUE_SET_CAPACITY = 2; @VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0; @VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; private transient ValueEntry<K, V> multimapHeaderEntry; private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) { super(new LinkedHashMap<K, Collection<V>>(keyCapacity)); checkNonnegative(valueSetCapacity, "expectedValuesPerKey"); this.valueSetCapacity = valueSetCapacity; this.multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * {@inheritDoc} * * <p>Creates an empty {@code LinkedHashSet} for a collection of values for * one key. * * @return a new {@code LinkedHashSet} containing a collection of values for * one key */ @Override Set<V> createCollection() { return new LinkedHashSet<V>(valueSetCapacity); } /** * {@inheritDoc} * * <p>Creates a decorated insertion-ordered set that also keeps track of the * order in which key-value pairs are added to the multimap. * * @param key key to associate with values in the collection * @return a new decorated set containing a collection of values for one key */ @Override Collection<V> createCollection(K key) { return new ValueSet(key, valueSetCapacity); } /** * {@inheritDoc} * * <p>If {@code values} is not empty and the multimap already contains a * mapping for {@code key}, the {@code keySet()} ordering is unchanged. * However, the provided values always come last in the {@link #entries()} and * {@link #values()} iteration orderings. */ @Override public Set<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { return super.replaceValues(key, values); } /** * Returns a set of all key-value pairs. Changes to the returned set will * update the underlying multimap, and vice versa. The entries set does not * support the {@code add} or {@code addAll} operations. * * <p>The iterator generated by the returned set traverses the entries in the * order they were added to the multimap. * * <p>Each entry is an immutable snapshot of a key-value mapping in the * multimap, taken at the time the entry is returned by a method call to the * collection or its iterator. */ @Override public Set<Map.Entry<K, V>> entries() { return super.entries(); } /** * Returns a collection of all values in the multimap. Changes to the returned * collection will update the underlying multimap, and vice versa. * * <p>The iterator generated by the returned collection traverses the values * in the order they were added to the multimap. */ @Override public Collection<V> values() { return super.values(); } @VisibleForTesting final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> { /* * We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory * consumption. */ private final K key; @VisibleForTesting ValueEntry<K, V>[] hashTable; private int size = 0; private int modCount = 0; // We use the set object itself as the end of the linked list, avoiding an unnecessary // entry object per key. private ValueSetLink<K, V> firstEntry; private ValueSetLink<K, V> lastEntry; ValueSet(K key, int expectedValues) { this.key = key; this.firstEntry = this; this.lastEntry = this; // Round expected values up to a power of 2 to get the table size. int tableSize = Hashing.closedTableSize(expectedValues, VALUE_SET_LOAD_FACTOR); @SuppressWarnings("unchecked") ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize]; this.hashTable = hashTable; } private int mask() { return hashTable.length - 1; } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return lastEntry; } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return firstEntry; } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { lastEntry = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { firstEntry = entry; } @Override public Iterator<V> iterator() { return new Iterator<V>() { ValueSetLink<K, V> nextEntry = firstEntry; ValueEntry<K, V> toRemove; int expectedModCount = modCount; private void checkForComodification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForComodification(); return nextEntry != ValueSet.this; } @Override public V next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry; V result = entry.getValue(); toRemove = entry; nextEntry = entry.getSuccessorInValueSet(); return result; } @Override public void remove() { checkForComodification(); checkRemove(toRemove != null); ValueSet.this.remove(toRemove.getValue()); expectedModCount = modCount; toRemove = null; } }; } @Override public int size() { return size; } @Override public boolean contains(@Nullable Object o) { int smearedHash = Hashing.smearedHash(o); for (ValueEntry<K, V> entry = hashTable[smearedHash & mask()]; entry != null; entry = entry.nextInValueBucket) { if (entry.matchesValue(o, smearedHash)) { return true; } } return false; } @Override public boolean add(@Nullable V value) { int smearedHash = Hashing.smearedHash(value); int bucket = smearedHash & mask(); ValueEntry<K, V> rowHead = hashTable[bucket]; for (ValueEntry<K, V> entry = rowHead; entry != null; entry = entry.nextInValueBucket) { if (entry.matchesValue(value, smearedHash)) { return false; } } ValueEntry<K, V> newEntry = new ValueEntry<K, V>(key, value, smearedHash, rowHead); succeedsInValueSet(lastEntry, newEntry); succeedsInValueSet(newEntry, this); succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry); succeedsInMultimap(newEntry, multimapHeaderEntry); hashTable[bucket] = newEntry; size++; modCount++; rehashIfNecessary(); return true; } private void rehashIfNecessary() { if (Hashing.needsResizing(size, hashTable.length, VALUE_SET_LOAD_FACTOR)) { @SuppressWarnings("unchecked") ValueEntry<K, V>[] hashTable = new ValueEntry[this.hashTable.length * 2]; this.hashTable = hashTable; int mask = hashTable.length - 1; for (ValueSetLink<K, V> entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry; int bucket = valueEntry.smearedValueHash & mask; valueEntry.nextInValueBucket = hashTable[bucket]; hashTable[bucket] = valueEntry; } } } @Override public boolean remove(@Nullable Object o) { int smearedHash = Hashing.smearedHash(o); int bucket = smearedHash & mask(); ValueEntry<K, V> prev = null; for (ValueEntry<K, V> entry = hashTable[bucket]; entry != null; prev = entry, entry = entry.nextInValueBucket) { if (entry.matchesValue(o, smearedHash)) { if (prev == null) { // first entry in the bucket hashTable[bucket] = entry.nextInValueBucket; } else { prev.nextInValueBucket = entry.nextInValueBucket; } deleteFromValueSet(entry); deleteFromMultimap(entry); size--; modCount++; return true; } } return false; } @Override public void clear() { Arrays.fill(hashTable, null); size = 0; for (ValueSetLink<K, V> entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry; deleteFromMultimap(valueEntry); } succeedsInValueSet(this, this); modCount++; } } @Override Iterator<Map.Entry<K, V>> entryIterator() { return new Iterator<Map.Entry<K, V>>() { ValueEntry<K, V> nextEntry = multimapHeaderEntry.successorInMultimap; ValueEntry<K, V> toRemove; @Override public boolean hasNext() { return nextEntry != multimapHeaderEntry; } @Override public Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> result = nextEntry; toRemove = result; nextEntry = nextEntry.successorInMultimap; return result; } @Override public void remove() { checkRemove(toRemove != null); LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue()); toRemove = null; } }; } @Override Iterator<V> valueIterator() { return Maps.valueIterator(entryIterator()); } @Override public void clear() { super.clear(); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * @serialData the expected values per key, the number of distinct keys, * the number of entries, and the entries in order */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(valueSetCapacity); stream.writeInt(keySet().size()); for (K key : keySet()) { stream.writeObject(key); } stream.writeInt(size()); for (Map.Entry<K, V> entry : entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); valueSetCapacity = stream.readInt(); int distinctKeys = stream.readInt(); Map<K, Collection<V>> map = new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys)); for (int i = 0; i < distinctKeys; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); map.put(key, createCollection(key)); } int entries = stream.readInt(); for (int i = 0; i < entries; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); @SuppressWarnings("unchecked") V value = (V) stream.readObject(); map.get(key).add(value); } setMap(map); } @GwtIncompatible("java serialization not supported") private static final long serialVersionUID = 1; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/LinkedHashMultimap.java
Java
asf20
19,594
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedSet; import javax.annotation.Nullable; /** * A sorted set which forwards all its method calls to another sorted set. * Subclasses should override one or more methods to modify the behavior of the * backing sorted set as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingSortedSet} forward * <i>indiscriminately</i> to the methods of the delegate. For example, * overriding {@link #add} alone <i>will not</i> change the behavior of {@link * #addAll}, which can lead to unexpected behavior. In this case, you should * override {@code addAll} as well, either providing your own implementation, or * delegating to the provided {@code standardAddAll} method. * * <p>Each of the {@code standard} methods, where appropriate, uses the set's * comparator (or the natural ordering of the elements, if there is no * comparator) to test element equality. As a result, if the comparator is not * consistent with equals, some of the standard implementations may violate the * {@code Set} contract. * * <p>The {@code standard} methods and the collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSortedSet<E> extends ForwardingSet<E> implements SortedSet<E> { /** Constructor for use by subclasses. */ protected ForwardingSortedSet() {} @Override protected abstract SortedSet<E> delegate(); @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override public E first() { return delegate().first(); } @Override public SortedSet<E> headSet(E toElement) { return delegate().headSet(toElement); } @Override public E last() { return delegate().last(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return delegate().subSet(fromElement, toElement); } @Override public SortedSet<E> tailSet(E fromElement) { return delegate().tailSet(fromElement); } // unsafe, but worst case is a CCE is thrown, which callers will be expecting @SuppressWarnings("unchecked") private int unsafeCompare(Object o1, Object o2) { Comparator<? super E> comparator = comparator(); return (comparator == null) ? ((Comparable<Object>) o1).compareTo(o2) : ((Comparator<Object>) comparator).compare(o1, o2); } /** * A sensible definition of {@link #contains} in terms of the {@code first()} * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish * to override {@link #contains} to forward to this implementation. * * @since 7.0 */ @Override @Beta protected boolean standardContains(@Nullable Object object) { try { // any ClassCastExceptions are caught @SuppressWarnings("unchecked") SortedSet<Object> self = (SortedSet<Object>) this; Object ceiling = self.tailSet(object).first(); return unsafeCompare(ceiling, object) == 0; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; } catch (NullPointerException e) { return false; } } /** * A sensible definition of {@link #remove} in terms of the {@code iterator()} * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish * to override {@link #remove} to forward to this implementation. * * @since 7.0 */ @Override @Beta protected boolean standardRemove(@Nullable Object object) { try { // any ClassCastExceptions are caught @SuppressWarnings("unchecked") SortedSet<Object> self = (SortedSet<Object>) this; Iterator<Object> iterator = self.tailSet(object).iterator(); if (iterator.hasNext()) { Object ceiling = iterator.next(); if (unsafeCompare(ceiling, object) == 0) { iterator.remove(); return true; } } } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } return false; } /** * A sensible default implementation of {@link #subSet(Object, Object)} in * terms of {@link #headSet(Object)} and {@link #tailSet(Object)}. In some * situations, you may wish to override {@link #subSet(Object, Object)} to * forward to this implementation. * * @since 7.0 */ @Beta protected SortedSet<E> standardSubSet(E fromElement, E toElement) { return tailSet(fromElement).headSet(toElement); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingSortedSet.java
Java
asf20
5,570
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; /** * An {@link ImmutableAsList} implementation specialized for when the delegate collection is * already backed by an {@code ImmutableList} or array. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization class RegularImmutableAsList<E> extends ImmutableAsList<E> { private final ImmutableCollection<E> delegate; private final ImmutableList<? extends E> delegateList; RegularImmutableAsList(ImmutableCollection<E> delegate, ImmutableList<? extends E> delegateList) { this.delegate = delegate; this.delegateList = delegateList; } RegularImmutableAsList(ImmutableCollection<E> delegate, Object[] array) { this(delegate, ImmutableList.<E>asImmutableList(array)); } @Override ImmutableCollection<E> delegateCollection() { return delegate; } ImmutableList<? extends E> delegateList() { return delegateList; } @SuppressWarnings("unchecked") // safe covariant cast! @Override public UnmodifiableListIterator<E> listIterator(int index) { return (UnmodifiableListIterator<E>) delegateList.listIterator(index); } @GwtIncompatible("not present in emulated superclass") @Override int copyIntoArray(Object[] dst, int offset) { return delegateList.copyIntoArray(dst, offset); } @Override public E get(int index) { return delegateList.get(index); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularImmutableAsList.java
Java
asf20
2,155
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.math.LongMath.binomial; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; /** * Provides static methods for working with {@code Collection} instances. * * @author Chris Povirk * @author Mike Bostock * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Collections2 { private Collections2() {} /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * returned collection is a live view of {@code unfiltered}; changes to one * affect the other. * * <p>The resulting collection's iterator does not support {@code remove()}, * but all other collection methods are supported. When given an element that * doesn't satisfy the predicate, the collection's {@code add()} and {@code * addAll()} methods throw an {@link IllegalArgumentException}. When methods * such as {@code removeAll()} and {@code clear()} are called on the filtered * collection, only elements that satisfy the filter will be removed from the * underlying collection. * * <p>The returned collection isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered collection's methods, such as {@code size()}, * iterate across every element in the underlying collection and determine * which elements satisfy the filter. When a live view is <i>not</i> needed, * it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} * and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent * with equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) */ // TODO(kevinb): how can we omit that Iterables link when building gwt // javadoc? public static <E> Collection<E> filter( Collection<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredCollection) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. return ((FilteredCollection<E>) unfiltered).createCombined(predicate); } return new FilteredCollection<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } /** * Delegates to {@link Collection#contains}. Returns {@code false} if the * {@code contains} method throws a {@code ClassCastException} or * {@code NullPointerException}. */ static boolean safeContains( Collection<?> collection, @Nullable Object object) { checkNotNull(collection); try { return collection.contains(object); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } /** * Delegates to {@link Collection#remove}. Returns {@code false} if the * {@code remove} method throws a {@code ClassCastException} or * {@code NullPointerException}. */ static boolean safeRemove(Collection<?> collection, @Nullable Object object) { checkNotNull(collection); try { return collection.remove(object); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } static class FilteredCollection<E> extends AbstractCollection<E> { final Collection<E> unfiltered; final Predicate<? super E> predicate; FilteredCollection(Collection<E> unfiltered, Predicate<? super E> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) { return new FilteredCollection<E>(unfiltered, Predicates.<E>and(predicate, newPredicate)); // .<E> above needed to compile in JDK 5 } @Override public boolean add(E element) { checkArgument(predicate.apply(element)); return unfiltered.add(element); } @Override public boolean addAll(Collection<? extends E> collection) { for (E element : collection) { checkArgument(predicate.apply(element)); } return unfiltered.addAll(collection); } @Override public void clear() { Iterables.removeIf(unfiltered, predicate); } @Override public boolean contains(@Nullable Object element) { if (safeContains(unfiltered, element)) { @SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E E e = (E) element; return predicate.apply(e); } return false; } @Override public boolean containsAll(Collection<?> collection) { return containsAllImpl(this, collection); } @Override public boolean isEmpty() { return !Iterables.any(unfiltered, predicate); } @Override public Iterator<E> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } @Override public boolean remove(Object element) { return contains(element) && unfiltered.remove(element); } @Override public boolean removeAll(final Collection<?> collection) { return Iterables.removeIf(unfiltered, and(predicate, in(collection))); } @Override public boolean retainAll(final Collection<?> collection) { return Iterables.removeIf(unfiltered, and(predicate, not(in(collection)))); } @Override public int size() { return Iterators.size(iterator()); } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public <T> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } /** * Returns a collection that applies {@code function} to each element of * {@code fromCollection}. The returned collection is a live view of {@code * fromCollection}; changes to one affect the other. * * <p>The returned collection's {@code add()} and {@code addAll()} methods * throw an {@link UnsupportedOperationException}. All other collection * methods are supported, as long as {@code fromCollection} supports them. * * <p>The returned collection isn't threadsafe or serializable, even if * {@code fromCollection} is. * * <p>When a live view is <i>not</i> needed, it may be faster to copy the * transformed collection and use the copy. * * <p>If the input {@code Collection} is known to be a {@code List}, consider * {@link Lists#transform}. If only an {@code Iterable} is available, use * {@link Iterables#transform}. */ public static <F, T> Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) { return new TransformedCollection<F, T>(fromCollection, function); } static class TransformedCollection<F, T> extends AbstractCollection<T> { final Collection<F> fromCollection; final Function<? super F, ? extends T> function; TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) { this.fromCollection = checkNotNull(fromCollection); this.function = checkNotNull(function); } @Override public void clear() { fromCollection.clear(); } @Override public boolean isEmpty() { return fromCollection.isEmpty(); } @Override public Iterator<T> iterator() { return Iterators.transform(fromCollection.iterator(), function); } @Override public int size() { return fromCollection.size(); } } /** * Returns {@code true} if the collection {@code self} contains all of the * elements in the collection {@code c}. * * <p>This method iterates over the specified collection {@code c}, checking * each element returned by the iterator in turn to see if it is contained in * the specified collection {@code self}. If all elements are so contained, * {@code true} is returned, otherwise {@code false}. * * @param self a collection which might contain all elements in {@code c} * @param c a collection whose elements might be contained by {@code self} */ static boolean containsAllImpl(Collection<?> self, Collection<?> c) { return Iterables.all(c, Predicates.in(self)); } /** * An implementation of {@link Collection#toString()}. */ static String toStringImpl(final Collection<?> collection) { StringBuilder sb = newStringBuilderForCollection(collection.size()).append('['); STANDARD_JOINER.appendTo( sb, Iterables.transform(collection, new Function<Object, Object>() { @Override public Object apply(Object input) { return input == collection ? "(this Collection)" : input; } })); return sb.append(']').toString(); } /** * Returns best-effort-sized StringBuilder based on the given collection size. */ static StringBuilder newStringBuilderForCollection(int size) { checkNonnegative(size, "size"); return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO)); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> Collection<T> cast(Iterable<T> iterable) { return (Collection<T>) iterable; } static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null"); /** * Returns a {@link Collection} of all the permutations of the specified * {@link Iterable}. * * <p><i>Notes:</i> This is an implementation of the algorithm for * Lexicographical Permutations Generation, described in Knuth's "The Art of * Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The * iteration order follows the lexicographical order. This means that * the first permutation will be in ascending order, and the last will be in * descending order. * * <p>Duplicate elements are considered equal. For example, the list [1, 1] * will have only one permutation, instead of two. This is why the elements * have to implement {@link Comparable}. * * <p>An empty iterable has only one permutation, which is an empty list. * * <p>This method is equivalent to * {@code Collections2.orderedPermutations(list, Ordering.natural())}. * * @param elements the original iterable whose elements have to be permuted. * @return an immutable {@link Collection} containing all the different * permutations of the original iterable. * @throws NullPointerException if the specified iterable is null or has any * null elements. * @since 12.0 */ @Beta public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(Iterable<E> elements) { return orderedPermutations(elements, Ordering.natural()); } /** * Returns a {@link Collection} of all the permutations of the specified * {@link Iterable} using the specified {@link Comparator} for establishing * the lexicographical ordering. * * <p>Examples: <pre> {@code * * for (List<String> perm : orderedPermutations(asList("b", "c", "a"))) { * println(perm); * } * // -> ["a", "b", "c"] * // -> ["a", "c", "b"] * // -> ["b", "a", "c"] * // -> ["b", "c", "a"] * // -> ["c", "a", "b"] * // -> ["c", "b", "a"] * * for (List<Integer> perm : orderedPermutations(asList(1, 2, 2, 1))) { * println(perm); * } * // -> [1, 1, 2, 2] * // -> [1, 2, 1, 2] * // -> [1, 2, 2, 1] * // -> [2, 1, 1, 2] * // -> [2, 1, 2, 1] * // -> [2, 2, 1, 1]}</pre> * * <p><i>Notes:</i> This is an implementation of the algorithm for * Lexicographical Permutations Generation, described in Knuth's "The Art of * Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The * iteration order follows the lexicographical order. This means that * the first permutation will be in ascending order, and the last will be in * descending order. * * <p>Elements that compare equal are considered equal and no new permutations * are created by swapping them. * * <p>An empty iterable has only one permutation, which is an empty list. * * @param elements the original iterable whose elements have to be permuted. * @param comparator a comparator for the iterable's elements. * @return an immutable {@link Collection} containing all the different * permutations of the original iterable. * @throws NullPointerException If the specified iterable is null, has any * null elements, or if the specified comparator is null. * @since 12.0 */ @Beta public static <E> Collection<List<E>> orderedPermutations( Iterable<E> elements, Comparator<? super E> comparator) { return new OrderedPermutationCollection<E>(elements, comparator); } private static final class OrderedPermutationCollection<E> extends AbstractCollection<List<E>> { final ImmutableList<E> inputList; final Comparator<? super E> comparator; final int size; OrderedPermutationCollection(Iterable<E> input, Comparator<? super E> comparator) { this.inputList = Ordering.from(comparator).immutableSortedCopy(input); this.comparator = comparator; this.size = calculateSize(inputList, comparator); } /** * The number of permutations with repeated elements is calculated as * follows: * <ul> * <li>For an empty list, it is 1 (base case).</li> * <li>When r numbers are added to a list of n-r elements, the number of * permutations is increased by a factor of (n choose r).</li> * </ul> */ private static <E> int calculateSize( List<E> sortedInputList, Comparator<? super E> comparator) { long permutations = 1; int n = 1; int r = 1; while (n < sortedInputList.size()) { int comparison = comparator.compare( sortedInputList.get(n - 1), sortedInputList.get(n)); if (comparison < 0) { // We move to the next non-repeated element. permutations *= binomial(n, r); r = 0; if (!isPositiveInt(permutations)) { return Integer.MAX_VALUE; } } n++; r++; } permutations *= binomial(n, r); if (!isPositiveInt(permutations)) { return Integer.MAX_VALUE; } return (int) permutations; } @Override public int size() { return size; } @Override public boolean isEmpty() { return false; } @Override public Iterator<List<E>> iterator() { return new OrderedPermutationIterator<E>(inputList, comparator); } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof List) { List<?> list = (List<?>) obj; return isPermutation(inputList, list); } return false; } @Override public String toString() { return "orderedPermutationCollection(" + inputList + ")"; } } private static final class OrderedPermutationIterator<E> extends AbstractIterator<List<E>> { List<E> nextPermutation; final Comparator<? super E> comparator; OrderedPermutationIterator(List<E> list, Comparator<? super E> comparator) { this.nextPermutation = Lists.newArrayList(list); this.comparator = comparator; } @Override protected List<E> computeNext() { if (nextPermutation == null) { return endOfData(); } ImmutableList<E> next = ImmutableList.copyOf(nextPermutation); calculateNextPermutation(); return next; } void calculateNextPermutation() { int j = findNextJ(); if (j == -1) { nextPermutation = null; return; } int l = findNextL(j); Collections.swap(nextPermutation, j, l); int n = nextPermutation.size(); Collections.reverse(nextPermutation.subList(j + 1, n)); } int findNextJ() { for (int k = nextPermutation.size() - 2; k >= 0; k--) { if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) { return k; } } return -1; } int findNextL(int j) { E ak = nextPermutation.get(j); for (int l = nextPermutation.size() - 1; l > j; l--) { if (comparator.compare(ak, nextPermutation.get(l)) < 0) { return l; } } throw new AssertionError("this statement should be unreachable"); } } /** * Returns a {@link Collection} of all the permutations of the specified * {@link Collection}. * * <p><i>Notes:</i> This is an implementation of the Plain Changes algorithm * for permutations generation, described in Knuth's "The Art of Computer * Programming", Volume 4, Chapter 7, Section 7.2.1.2. * * <p>If the input list contains equal elements, some of the generated * permutations will be equal. * * <p>An empty collection has only one permutation, which is an empty list. * * @param elements the original collection whose elements have to be permuted. * @return an immutable {@link Collection} containing all the different * permutations of the original collection. * @throws NullPointerException if the specified collection is null or has any * null elements. * @since 12.0 */ @Beta public static <E> Collection<List<E>> permutations( Collection<E> elements) { return new PermutationCollection<E>(ImmutableList.copyOf(elements)); } private static final class PermutationCollection<E> extends AbstractCollection<List<E>> { final ImmutableList<E> inputList; PermutationCollection(ImmutableList<E> input) { this.inputList = input; } @Override public int size() { return IntMath.factorial(inputList.size()); } @Override public boolean isEmpty() { return false; } @Override public Iterator<List<E>> iterator() { return new PermutationIterator<E>(inputList); } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof List) { List<?> list = (List<?>) obj; return isPermutation(inputList, list); } return false; } @Override public String toString() { return "permutations(" + inputList + ")"; } } private static class PermutationIterator<E> extends AbstractIterator<List<E>> { final List<E> list; final int[] c; final int[] o; int j; PermutationIterator(List<E> list) { this.list = new ArrayList<E>(list); int n = list.size(); c = new int[n]; o = new int[n]; Arrays.fill(c, 0); Arrays.fill(o, 1); j = Integer.MAX_VALUE; } @Override protected List<E> computeNext() { if (j <= 0) { return endOfData(); } ImmutableList<E> next = ImmutableList.copyOf(list); calculateNextPermutation(); return next; } void calculateNextPermutation() { j = list.size() - 1; int s = 0; // Handle the special case of an empty list. Skip the calculation of the // next permutation. if (j == -1) { return; } while (true) { int q = c[j] + o[j]; if (q < 0) { switchDirection(); continue; } if (q == j + 1) { if (j == 0) { break; } s++; switchDirection(); continue; } Collections.swap(list, j - c[j] + s, j - q + s); c[j] = q; break; } } void switchDirection() { o[j] = -o[j]; j--; } } /** * Returns {@code true} if the second list is a permutation of the first. */ private static boolean isPermutation(List<?> first, List<?> second) { if (first.size() != second.size()) { return false; } Multiset<?> firstMultiset = HashMultiset.create(first); Multiset<?> secondMultiset = HashMultiset.create(second); return firstMultiset.equals(secondMultiset); } private static boolean isPositiveInt(long n) { return n >= 0 && n <= Integer.MAX_VALUE; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Collections2.java
Java
asf20
21,848
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; /** * An abstract base class for implementing the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * The {@link #delegate()} method must be overridden to return the instance * being decorated. * * <p>This class does <i>not</i> forward the {@code hashCode} and {@code equals} * methods through to the backing object, but relies on {@code Object}'s * implementation. This is necessary to preserve the symmetry of {@code equals}. * Custom definitions of equality are usually based on an interface, such as * {@code Set} or {@code List}, so that the implementation of {@code equals} can * cast the object being tested for equality to the custom interface. {@code * ForwardingObject} implements no such custom interfaces directly; they * are implemented only in subclasses. Therefore, forwarding {@code equals} * would break symmetry, as the forwarding object might consider itself equal to * the object being tested, but the reverse could not be true. This behavior is * consistent with the JDK's collection wrappers, such as * {@link java.util.Collections#unmodifiableCollection}. Use an * interface-specific subclass of {@code ForwardingObject}, such as {@link * ForwardingList}, to preserve equality behavior, or override {@code equals} * directly. * * <p>The {@code toString} method is forwarded to the delegate. Although this * class does not implement {@link Serializable}, a serializable subclass may be * created since this class has a parameter-less constructor. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingObject { /** Constructor for use by subclasses. */ protected ForwardingObject() {} /** * Returns the backing delegate instance that methods are forwarded to. * Abstract subclasses generally override this method with an abstract method * that has a more specific return type, such as {@link * ForwardingSet#delegate}. Concrete subclasses override this method to supply * the instance being decorated. */ protected abstract Object delegate(); /** * Returns the string representation generated by the delegate's * {@code toString} method. */ @Override public String toString() { return delegate().toString(); } /* No equals or hashCode. See class comments for details. */ }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingObject.java
Java
asf20
3,103
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Collection; import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; /** * A multiset which forwards all its method calls to another multiset. * Subclasses should override one or more methods to modify the behavior of the * backing multiset as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingMultiset} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add(Object, int)} alone <b>will not</b> change the * behavior of {@link #add(Object)}, which can lead to unexpected behavior. In * this case, you should override {@code add(Object)} as well, either providing * your own implementation, or delegating to the provided {@code standardAdd} * method. * * <p>The {@code standard} methods and any collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMultiset<E> extends ForwardingCollection<E> implements Multiset<E> { /** Constructor for use by subclasses. */ protected ForwardingMultiset() {} @Override protected abstract Multiset<E> delegate(); @Override public int count(Object element) { return delegate().count(element); } @Override public int add(E element, int occurrences) { return delegate().add(element, occurrences); } @Override public int remove(Object element, int occurrences) { return delegate().remove(element, occurrences); } @Override public Set<E> elementSet() { return delegate().elementSet(); } @Override public Set<Entry<E>> entrySet() { return delegate().entrySet(); } @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } @Override public int setCount(E element, int count) { return delegate().setCount(element, count); } @Override public boolean setCount(E element, int oldCount, int newCount) { return delegate().setCount(element, oldCount, newCount); } /** * A sensible definition of {@link #contains} in terms of {@link #count}. If * you override {@link #count}, you may wish to override {@link #contains} to * forward to this implementation. * * @since 7.0 */ @Override protected boolean standardContains(@Nullable Object object) { return count(object) > 0; } /** * A sensible definition of {@link #clear} in terms of the {@code iterator} * method of {@link #entrySet}. If you override {@link #entrySet}, you may * wish to override {@link #clear} to forward to this implementation. * * @since 7.0 */ @Override protected void standardClear() { Iterators.clear(entrySet().iterator()); } /** * A sensible, albeit inefficient, definition of {@link #count} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to * override {@link #count} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardCount(@Nullable Object object) { for (Entry<?> entry : this.entrySet()) { if (Objects.equal(entry.getElement(), object)) { return entry.getCount(); } } return 0; } /** * A sensible definition of {@link #add(Object)} in terms of {@link * #add(Object, int)}. If you override {@link #add(Object, int)}, you may * wish to override {@link #add(Object)} to forward to this implementation. * * @since 7.0 */ protected boolean standardAdd(E element) { add(element, 1); return true; } /** * A sensible definition of {@link #addAll(Collection)} in terms of {@link * #add(Object)} and {@link #add(Object, int)}. If you override either of * these methods, you may wish to override {@link #addAll(Collection)} to * forward to this implementation. * * @since 7.0 */ @Beta @Override protected boolean standardAddAll( Collection<? extends E> elementsToAdd) { return Multisets.addAllImpl(this, elementsToAdd); } /** * A sensible definition of {@link #remove(Object)} in terms of {@link * #remove(Object, int)}. If you override {@link #remove(Object, int)}, you * may wish to override {@link #remove(Object)} to forward to this * implementation. * * @since 7.0 */ @Override protected boolean standardRemove(Object element) { return remove(element, 1) > 0; } /** * A sensible definition of {@link #removeAll} in terms of the {@code * removeAll} method of {@link #elementSet}. If you override {@link * #elementSet}, you may wish to override {@link #removeAll} to forward to * this implementation. * * @since 7.0 */ @Override protected boolean standardRemoveAll( Collection<?> elementsToRemove) { return Multisets.removeAllImpl(this, elementsToRemove); } /** * A sensible definition of {@link #retainAll} in terms of the {@code * retainAll} method of {@link #elementSet}. If you override {@link * #elementSet}, you may wish to override {@link #retainAll} to forward to * this implementation. * * @since 7.0 */ @Override protected boolean standardRetainAll( Collection<?> elementsToRetain) { return Multisets.retainAllImpl(this, elementsToRetain); } /** * A sensible definition of {@link #setCount(Object, int)} in terms of {@link * #count(Object)}, {@link #add(Object, int)}, and {@link #remove(Object, * int)}. {@link #entrySet()}. If you override any of these methods, you may * wish to override {@link #setCount(Object, int)} to forward to this * implementation. * * @since 7.0 */ protected int standardSetCount(E element, int count) { return Multisets.setCountImpl(this, element, count); } /** * A sensible definition of {@link #setCount(Object, int, int)} in terms of * {@link #count(Object)} and {@link #setCount(Object, int)}. If you override * either of these methods, you may wish to override {@link #setCount(Object, * int, int)} to forward to this implementation. * * @since 7.0 */ protected boolean standardSetCount(E element, int oldCount, int newCount) { return Multisets.setCountImpl(this, element, oldCount, newCount); } /** * A sensible implementation of {@link Multiset#elementSet} in terms of the * following methods: {@link ForwardingMultiset#clear}, {@link * ForwardingMultiset#contains}, {@link ForwardingMultiset#containsAll}, * {@link ForwardingMultiset#count}, {@link ForwardingMultiset#isEmpty}, the * {@link Set#size} and {@link Set#iterator} methods of {@link * ForwardingMultiset#entrySet}, and {@link ForwardingMultiset#remove(Object, * int)}. In many situations, you may wish to override {@link * ForwardingMultiset#elementSet} to forward to this implementation or a * subclass thereof. * * @since 10.0 */ @Beta protected class StandardElementSet extends Multisets.ElementSet<E> { /** Constructor for use by subclasses. */ public StandardElementSet() {} @Override Multiset<E> multiset() { return ForwardingMultiset.this; } } /** * A sensible definition of {@link #iterator} in terms of {@link #entrySet} * and {@link #remove(Object)}. If you override either of these methods, you * may wish to override {@link #iterator} to forward to this implementation. * * @since 7.0 */ protected Iterator<E> standardIterator() { return Multisets.iteratorImpl(this); } /** * A sensible, albeit inefficient, definition of {@link #size} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to * override {@link #size} to forward to this implementation. * * @since 7.0 */ protected int standardSize() { return Multisets.sizeImpl(this); } /** * A sensible, albeit inefficient, definition of {@link #size} in terms of * {@code entrySet().size()} and {@link #count}. If you override either of * these methods, you may wish to override {@link #size} to forward to this * implementation. * * @since 7.0 */ protected boolean standardEquals(@Nullable Object object) { return Multisets.equalsImpl(this, object); } /** * A sensible definition of {@link #hashCode} as {@code entrySet().hashCode()} * . If you override {@link #entrySet}, you may wish to override {@link * #hashCode} to forward to this implementation. * * @since 7.0 */ protected int standardHashCode() { return entrySet().hashCode(); } /** * A sensible definition of {@link #toString} as {@code entrySet().toString()} * . If you override {@link #entrySet}, you may wish to override {@link * #toString} to forward to this implementation. * * @since 7.0 */ @Override protected String standardToString() { return entrySet().toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingMultiset.java
Java
asf20
9,946
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * This class provides a skeletal implementation of the {@code Iterator} * interface for sequences whose next element can always be derived from the * previous element. Null elements are not supported, nor is the * {@link #remove()} method. * * <p>Example: <pre> {@code * * Iterator<Integer> powersOfTwo = * new AbstractSequentialIterator<Integer>(1) { * protected Integer computeNext(Integer previous) { * return (previous == 1 << 30) ? null : previous * 2; * } * };}</pre> * * @author Chris Povirk * @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0) */ @GwtCompatible public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> { private T nextOrNull; /** * Creates a new iterator with the given first element, or, if {@code * firstOrNull} is null, creates a new empty iterator. */ protected AbstractSequentialIterator(@Nullable T firstOrNull) { this.nextOrNull = firstOrNull; } /** * Returns the element that follows {@code previous}, or returns {@code null} * if no elements remain. This method is invoked during each call to * {@link #next()} in order to compute the result of a <i>future</i> call to * {@code next()}. */ protected abstract T computeNext(T previous); @Override public final boolean hasNext() { return nextOrNull != null; } @Override public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } try { return nextOrNull; } finally { nextOrNull = computeNext(nextOrNull); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractSequentialIterator.java
Java
asf20
2,390
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Map; import javax.annotation.Nullable; /** * An object representing the differences between two maps. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface MapDifference<K, V> { /** * Returns {@code true} if there are no differences between the two maps; * that is, if the maps are equal. */ boolean areEqual(); /** * Returns an unmodifiable map containing the entries from the left map whose * keys are not present in the right map. */ Map<K, V> entriesOnlyOnLeft(); /** * Returns an unmodifiable map containing the entries from the right map whose * keys are not present in the left map. */ Map<K, V> entriesOnlyOnRight(); /** * Returns an unmodifiable map containing the entries that appear in both * maps; that is, the intersection of the two maps. */ Map<K, V> entriesInCommon(); /** * Returns an unmodifiable map describing keys that appear in both maps, but * with different values. */ Map<K, ValueDifference<V>> entriesDiffering(); /** * Compares the specified object with this instance for equality. Returns * {@code true} if the given object is also a {@code MapDifference} and the * values returned by the {@link #entriesOnlyOnLeft()}, {@link * #entriesOnlyOnRight()}, {@link #entriesInCommon()} and {@link * #entriesDiffering()} of the two instances are equal. */ @Override boolean equals(@Nullable Object object); /** * Returns the hash code for this instance. This is defined as the hash code * of <pre> {@code * * Arrays.asList(entriesOnlyOnLeft(), entriesOnlyOnRight(), * entriesInCommon(), entriesDiffering())}</pre> */ @Override int hashCode(); /** * A difference between the mappings from two maps with the same key. The * {@link #leftValue} and {@link #rightValue} are not equal, and one but not * both of them may be null. * * @since 2.0 (imported from Google Collections Library) */ interface ValueDifference<V> { /** * Returns the value from the left map (possibly null). */ V leftValue(); /** * Returns the value from the right map (possibly null). */ V rightValue(); /** * Two instances are considered equal if their {@link #leftValue()} * values are equal and their {@link #rightValue()} values are also equal. */ @Override boolean equals(@Nullable Object other); /** * The hash code equals the value * {@code Arrays.asList(leftValue(), rightValue()).hashCode()}. */ @Override int hashCode(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/MapDifference.java
Java
asf20
3,345
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Maps.ImprovedAbstractMap; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@link Multimaps#filterEntries(Multimap, Predicate)}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible class FilteredEntryMultimap<K, V> extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> { final Multimap<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; FilteredEntryMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { this.unfiltered = checkNotNull(unfiltered); this.predicate = checkNotNull(predicate); } @Override public Multimap<K, V> unfiltered() { return unfiltered; } @Override public Predicate<? super Entry<K, V>> entryPredicate() { return predicate; } @Override public int size() { return entries().size(); } private boolean satisfies(K key, V value) { return predicate.apply(Maps.immutableEntry(key, value)); } final class ValuePredicate implements Predicate<V> { private final K key; ValuePredicate(K key) { this.key = key; } @Override public boolean apply(@Nullable V value) { return satisfies(key, value); } } static <E> Collection<E> filterCollection( Collection<E> collection, Predicate<? super E> predicate) { if (collection instanceof Set) { return Sets.filter((Set<E>) collection, predicate); } else { return Collections2.filter(collection, predicate); } } @Override public boolean containsKey(@Nullable Object key) { return asMap().get(key) != null; } @Override public Collection<V> removeAll(@Nullable Object key) { return Objects.firstNonNull(asMap().remove(key), unmodifiableEmptyCollection()); } Collection<V> unmodifiableEmptyCollection() { // These return false, rather than throwing a UOE, on remove calls. return (unfiltered instanceof SetMultimap) ? Collections.<V>emptySet() : Collections.<V>emptyList(); } @Override public void clear() { entries().clear(); } @Override public Collection<V> get(final K key) { return filterCollection(unfiltered.get(key), new ValuePredicate(key)); } @Override Collection<Entry<K, V>> createEntries() { return filterCollection(unfiltered.entries(), predicate); } @Override Collection<V> createValues() { return new FilteredMultimapValues<K, V>(this); } @Override Iterator<Entry<K, V>> entryIterator() { throw new AssertionError("should never be called"); } @Override Map<K, Collection<V>> createAsMap() { return new AsMap(); } @Override public Set<K> keySet() { return asMap().keySet(); } boolean removeEntriesIf(Predicate<? super Entry<K, Collection<V>>> predicate) { Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<K, Collection<V>> entry = entryIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty() && predicate.apply(Maps.immutableEntry(key, collection))) { if (collection.size() == entry.getValue().size()) { entryIterator.remove(); } else { collection.clear(); } changed = true; } } return changed; } class AsMap extends ImprovedAbstractMap<K, Collection<V>> { @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public void clear() { FilteredEntryMultimap.this.clear(); } @Override public Collection<V> get(@Nullable Object key) { Collection<V> result = unfiltered.asMap().get(key); if (result == null) { return null; } @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself K k = (K) key; result = filterCollection(result, new ValuePredicate(k)); return result.isEmpty() ? null : result; } @Override public Collection<V> remove(@Nullable Object key) { Collection<V> collection = unfiltered.asMap().get(key); if (collection == null) { return null; } @SuppressWarnings("unchecked") // it's definitely equal to a K K k = (K) key; List<V> result = Lists.newArrayList(); Iterator<V> itr = collection.iterator(); while (itr.hasNext()) { V v = itr.next(); if (satisfies(k, v)) { itr.remove(); result.add(v); } } if (result.isEmpty()) { return null; } else if (unfiltered instanceof SetMultimap) { return Collections.unmodifiableSet(Sets.newLinkedHashSet(result)); } else { return Collections.unmodifiableList(result); } } @Override Set<K> createKeySet() { return new Maps.KeySet<K, Collection<V>>(this) { @Override public boolean removeAll(Collection<?> c) { return removeEntriesIf(Maps.<K>keyPredicateOnEntries(in(c))); } @Override public boolean retainAll(Collection<?> c) { return removeEntriesIf(Maps.<K>keyPredicateOnEntries(not(in(c)))); } @Override public boolean remove(@Nullable Object o) { return AsMap.this.remove(o) != null; } }; } @Override Set<Entry<K, Collection<V>>> createEntrySet() { return new Maps.EntrySet<K, Collection<V>>() { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { return new AbstractIterator<Entry<K, Collection<V>>>() { final Iterator<Entry<K, Collection<V>>> backingIterator = unfiltered.asMap().entrySet().iterator(); @Override protected Entry<K, Collection<V>> computeNext() { while (backingIterator.hasNext()) { Entry<K, Collection<V>> entry = backingIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty()) { return Maps.immutableEntry(key, collection); } } return endOfData(); } }; } @Override public boolean removeAll(Collection<?> c) { return removeEntriesIf(in(c)); } @Override public boolean retainAll(Collection<?> c) { return removeEntriesIf(not(in(c))); } @Override public int size() { return Iterators.size(iterator()); } }; } @Override Collection<Collection<V>> createValues() { return new Maps.Values<K, Collection<V>>(AsMap.this) { @Override public boolean remove(@Nullable Object o) { if (o instanceof Collection) { Collection<?> c = (Collection<?>) o; Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator(); while (entryIterator.hasNext()) { Entry<K, Collection<V>> entry = entryIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty() && c.equals(collection)) { if (collection.size() == entry.getValue().size()) { entryIterator.remove(); } else { collection.clear(); } return true; } } } return false; } @Override public boolean removeAll(Collection<?> c) { return removeEntriesIf(Maps.<Collection<V>>valuePredicateOnEntries(in(c))); } @Override public boolean retainAll(Collection<?> c) { return removeEntriesIf(Maps.<Collection<V>>valuePredicateOnEntries(not(in(c)))); } }; } } @Override Multiset<K> createKeys() { return new Keys(); } class Keys extends Multimaps.Keys<K, V> { Keys() { super(FilteredEntryMultimap.this); } @Override public int remove(@Nullable Object key, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(key); } Collection<V> collection = unfiltered.asMap().get(key); if (collection == null) { return 0; } @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself K k = (K) key; int oldCount = 0; Iterator<V> itr = collection.iterator(); while (itr.hasNext()) { V v = itr.next(); if (satisfies(k, v)) { oldCount++; if (oldCount <= occurrences) { itr.remove(); } } } return oldCount; } @Override public Set<Multiset.Entry<K>> entrySet() { return new Multisets.EntrySet<K>() { @Override Multiset<K> multiset() { return Keys.this; } @Override public Iterator<Multiset.Entry<K>> iterator() { return Keys.this.entryIterator(); } @Override public int size() { return FilteredEntryMultimap.this.keySet().size(); } private boolean removeEntriesIf(final Predicate<? super Multiset.Entry<K>> predicate) { return FilteredEntryMultimap.this.removeEntriesIf( new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { return predicate.apply( Multisets.immutableEntry(entry.getKey(), entry.getValue().size())); } }); } @Override public boolean removeAll(Collection<?> c) { return removeEntriesIf(in(c)); } @Override public boolean retainAll(Collection<?> c) { return removeEntriesIf(not(in(c))); } }; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/FilteredEntryMultimap.java
Java
asf20
11,664
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * A set comprising zero or more {@linkplain Range#isEmpty nonempty}, * {@linkplain Range#isConnected(Range) disconnected} ranges of type {@code C}. * * <p>Implementations that choose to support the {@link #add(Range)} operation are required to * ignore empty ranges and coalesce connected ranges. For example: <pre> {@code * * RangeSet<Integer> rangeSet = TreeRangeSet.create(); * rangeSet.add(Range.closed(1, 10)); // {[1, 10]} * rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)} * rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)} * rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)} * rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)}}</pre> * * <p>Note that the behavior of {@link Range#isEmpty()} and {@link Range#isConnected(Range)} may * not be as expected on discrete ranges. See the Javadoc of those methods for details. * * <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 14.0 */ @Beta public interface RangeSet<C extends Comparable> { // Query methods /** * Determines whether any of this range set's member ranges contains {@code value}. */ boolean contains(C value); /** * Returns the unique range from this range set that {@linkplain Range#contains contains} * {@code value}, or {@code null} if this range set does not contain {@code value}. */ Range<C> rangeContaining(C value); /** * Returns {@code true} if there exists a member range in this range set which * {@linkplain Range#encloses encloses} the specified range. */ boolean encloses(Range<C> otherRange); /** * Returns {@code true} if for each member range in {@code other} there exists a member range in * this range set which {@linkplain Range#encloses encloses} it. It follows that * {@code this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if * {@code other} is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in * {@code other}. */ boolean enclosesAll(RangeSet<C> other); /** * Returns {@code true} if this range set contains no ranges. */ boolean isEmpty(); /** * Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges * in this range set. * * @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty} */ Range<C> span(); // Views /** * Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this * range set. The returned set may be empty. The iterators returned by its * {@link Iterable#iterator} method return the ranges in increasing order of lower bound * (equivalently, of upper bound). */ Set<Range<C>> asRanges(); /** * Returns a view of the complement of this {@code RangeSet}. * * <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports * {@link #remove}, and vice versa. */ RangeSet<C> complement(); /** * Returns a view of the intersection of this {@code RangeSet} with the specified range. * * <p>The returned view supports all optional operations supported by this {@code RangeSet}, with * the caveat that an {@link IllegalArgumentException} is thrown on an attempt to * {@linkplain #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by * {@code view}. */ RangeSet<C> subRangeSet(Range<C> view); // Modification /** * Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal * range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal * range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}. * * <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in * the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover, * if {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code add} * operation */ void add(Range<C> range); /** * Removes the specified range from this {@code RangeSet} (optional operation). After this * operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}. * * <p>If {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code remove} * operation */ void remove(Range<C> range); /** * Removes all ranges from this {@code RangeSet} (optional operation). After this operation, * {@code this.contains(c)} will return false for all {@code c}. * * <p>This is equivalent to {@code remove(Range.all())}. * * @throws UnsupportedOperationException if this range set does not support the {@code clear} * operation */ void clear(); /** * Adds all of the ranges from the specified range set to this range set (optional operation). * After this operation, this range set is the minimal range set that * {@linkplain #enclosesAll(RangeSet) encloses} both the original range set and {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation */ void addAll(RangeSet<C> other); /** * Removes all of the ranges from the specified range set from this range set (optional * operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will * return {@code false}. * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation */ void removeAll(RangeSet<C> other); // Object methods /** * Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges * according to {@link Range#equals(Object)}. */ @Override boolean equals(@Nullable Object obj); /** * Returns {@code asRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range set. For example, if this * {@code RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)}, * this might return {@code " [1‥3](4‥+∞)}"}. */ @Override String toString(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RangeSet.java
Java
asf20
7,621
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Collection; import java.util.Iterator; import javax.annotation.Nullable; /** * A collection which forwards all its method calls to another collection. * Subclasses should override one or more methods to modify the behavior of the * backing collection as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingCollection} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #addAll}, which can lead to unexpected behavior. In this case, you should * override {@code addAll} as well, either providing your own implementation, or * delegating to the provided {@code standardAddAll} method. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingCollection<E> extends ForwardingObject implements Collection<E> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingCollection() {} @Override protected abstract Collection<E> delegate(); @Override public Iterator<E> iterator() { return delegate().iterator(); } @Override public int size() { return delegate().size(); } @Override public boolean removeAll(Collection<?> collection) { return delegate().removeAll(collection); } @Override public boolean isEmpty() { return delegate().isEmpty(); } @Override public boolean contains(Object object) { return delegate().contains(object); } @Override public boolean add(E element) { return delegate().add(element); } @Override public boolean remove(Object object) { return delegate().remove(object); } @Override public boolean containsAll(Collection<?> collection) { return delegate().containsAll(collection); } @Override public boolean addAll(Collection<? extends E> collection) { return delegate().addAll(collection); } @Override public boolean retainAll(Collection<?> collection) { return delegate().retainAll(collection); } @Override public void clear() { delegate().clear(); } @Override public Object[] toArray() { return delegate().toArray(); } @Override public <T> T[] toArray(T[] array) { return delegate().toArray(array); } /** * A sensible definition of {@link #contains} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link * #contains} to forward to this implementation. * * @since 7.0 */ protected boolean standardContains(@Nullable Object object) { return Iterators.contains(iterator(), object); } /** * A sensible definition of {@link #containsAll} in terms of {@link #contains} * . If you override {@link #contains}, you may wish to override {@link * #containsAll} to forward to this implementation. * * @since 7.0 */ protected boolean standardContainsAll(Collection<?> collection) { return Collections2.containsAllImpl(this, collection); } /** * A sensible definition of {@link #addAll} in terms of {@link #add}. If you * override {@link #add}, you may wish to override {@link #addAll} to forward * to this implementation. * * @since 7.0 */ protected boolean standardAddAll(Collection<? extends E> collection) { return Iterators.addAll(this, collection.iterator()); } /** * A sensible definition of {@link #remove} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #remove} to forward to this * implementation. * * @since 7.0 */ protected boolean standardRemove(@Nullable Object object) { Iterator<E> iterator = iterator(); while (iterator.hasNext()) { if (Objects.equal(iterator.next(), object)) { iterator.remove(); return true; } } return false; } /** * A sensible definition of {@link #removeAll} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #removeAll} to forward to this * implementation. * * @since 7.0 */ protected boolean standardRemoveAll(Collection<?> collection) { return Iterators.removeAll(iterator(), collection); } /** * A sensible definition of {@link #retainAll} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #retainAll} to forward to this * implementation. * * @since 7.0 */ protected boolean standardRetainAll(Collection<?> collection) { return Iterators.retainAll(iterator(), collection); } /** * A sensible definition of {@link #clear} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #clear} to forward to this * implementation. * * @since 7.0 */ protected void standardClear() { Iterators.clear(iterator()); } /** * A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}. * If you override {@link #isEmpty}, you may wish to override {@link #isEmpty} * to forward to this implementation. Alternately, it may be more efficient to * implement {@code isEmpty} as {@code size() == 0}. * * @since 7.0 */ protected boolean standardIsEmpty() { return !iterator().hasNext(); } /** * A sensible definition of {@link #toString} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link * #toString} to forward to this implementation. * * @since 7.0 */ protected String standardToString() { return Collections2.toStringImpl(this); } /** * A sensible definition of {@link #toArray()} in terms of {@link * #toArray(Object[])}. If you override {@link #toArray(Object[])}, you may * wish to override {@link #toArray} to forward to this implementation. * * @since 7.0 */ protected Object[] standardToArray() { Object[] newArray = new Object[size()]; return toArray(newArray); } /** * A sensible definition of {@link #toArray(Object[])} in terms of {@link * #size} and {@link #iterator}. If you override either of these methods, you * may wish to override {@link #toArray} to forward to this implementation. * * @since 7.0 */ protected <T> T[] standardToArray(T[] array) { return ObjectArrays.toArrayImpl(this, array); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingCollection.java
Java
asf20
7,667
/* * 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.collect.ObjectArrays.checkElementNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; /** * A high-performance, immutable {@code Set} with reliable, user-specified * iteration order. Does not permit null elements. * * <p>Unlike {@link Collections#unmodifiableSet}, which is a <i>view</i> of a * separate collection that can still change, an instance of this class contains * its own private data and will <i>never</i> change. This class is convenient * for {@code public static final} sets ("constant sets") and also lets you * easily make a "defensive copy" of a set provided to your class by a caller. * * <p><b>Warning:</b> Like most sets, an {@code ImmutableSet} will not function * correctly if an element is modified after being placed in the set. For this * reason, and to avoid general confusion, it is strongly recommended to place * only immutable objects into this collection. * * <p>This class has been observed to perform significantly better than {@link * HashSet} for objects with very fast {@link Object#hashCode} implementations * (as a well-behaved immutable object should). While this class's factory * methods create hash-based instances, the {@link ImmutableSortedSet} subclass * performs binary searches instead. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed * outside its package as it has no public or protected constructors. Thus, * instances of this type are guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @see ImmutableList * @see ImmutableMap * @author Kevin Bourrillion * @author Nick Kralevich * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> { /** * Returns the empty immutable set. This set behaves and performs comparably * to {@link Collections#emptySet}, and is preferable mainly for consistency * and maintainability of your code. */ // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings({"unchecked"}) public static <E> ImmutableSet<E> of() { return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE; } /** * Returns an immutable set containing a single element. This set behaves and * performs comparably to {@link Collections#singleton}, but will not accept * a null element. It is preferable mainly for consistency and * maintainability of your code. */ public static <E> ImmutableSet<E> of(E element) { return new SingletonImmutableSet<E>(element); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2) { return construct(2, e1, e2); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3) { return construct(3, e1, e2, e3); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) { return construct(4, e1, e2, e3, e4); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) { return construct(5, e1, e2, e3, e4, e5); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null * @since 3.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { final int paramCount = 6; Object[] elements = new Object[paramCount + others.length]; elements[0] = e1; elements[1] = e2; elements[2] = e3; elements[3] = e4; elements[4] = e5; elements[5] = e6; System.arraycopy(others, 0, elements, paramCount, others.length); return construct(elements.length, elements); } /** * Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array. * If {@code k} is the size of the returned {@code ImmutableSet}, then the unique elements of * {@code elements} will be in the first {@code k} positions, and {@code elements[i] == null} for * {@code k <= i < n}. * * <p>This may modify {@code elements}. Additionally, if {@code n == elements.length} and * {@code elements} contains no duplicates, {@code elements} may be used without copying in the * returned {@code ImmutableSet}, in which case it may no longer be modified. * * <p>{@code elements} may contain only values of type {@code E}. * * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is * null */ private static <E> ImmutableSet<E> construct(int n, Object... elements) { switch (n) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // safe; elements contains only E's E elem = (E) elements[0]; return of(elem); default: // continue below to handle the general case } int tableSize = chooseTableSize(n); Object[] table = new Object[tableSize]; int mask = tableSize - 1; int hashCode = 0; int uniques = 0; for (int i = 0; i < n; i++) { Object element = checkElementNotNull(elements[i], i); int hash = element.hashCode(); for (int j = Hashing.smear(hash); ; j++) { int index = j & mask; Object value = table[index]; if (value == null) { // Came to an empty slot. Put the element here. elements[uniques++] = element; table[index] = element; hashCode += hash; break; } else if (value.equals(element)) { break; } } } Arrays.fill(elements, uniques, n, null); if (uniques == 1) { // There is only one element or elements are all duplicates @SuppressWarnings("unchecked") // we are careful to only pass in E E element = (E) elements[0]; return new SingletonImmutableSet<E>(element, hashCode); } else if (tableSize != chooseTableSize(uniques)) { // Resize the table when the array includes too many duplicates. // when this happens, we have already made a copy return construct(uniques, elements); } else { Object[] uniqueElements = (uniques < elements.length) ? ObjectArrays.arraysCopyOf(elements, uniques) : elements; return new RegularImmutableSet<E>(uniqueElements, hashCode, table, mask); } } // We use power-of-2 tables, and this is the highest int that's a power of 2 static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; // Represents how tightly we can pack things, as a maximum. private static final double DESIRED_LOAD_FACTOR = 0.7; // If the set has this many elements, it will "max out" the table size private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR); /** * 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. * * <p>Do not call this method with setSize < 2. */ @VisibleForTesting static int chooseTableSize(int setSize) { // Correct the size for open addressing to match desired load factor. if (setSize < CUTOFF) { // 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; } // The table can't be completely full or we'll get infinite reprobes checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); return MAX_TABLE_SIZE; } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any of {@code elements} is null * @since 3.0 */ public static <E> ImmutableSet<E> copyOf(E[] elements) { switch (elements.length) { case 0: return of(); case 1: return of(elements[0]); default: return construct(elements.length, elements.clone()); } } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. This method iterates over {@code elements} at most once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns * a {@code ImmutableSet<Set<String>>} containing one element (the given set * itself). * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) { return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) { // We special-case for 0 or 1 elements, but anything further is madness. if (!elements.hasNext()) { return of(); } E first = elements.next(); if (!elements.hasNext()) { return of(first); } else { return new ImmutableSet.Builder<E>() .add(first) .addAll(elements) .build(); } } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. This method iterates over {@code elements} at most * once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns * a {@code ImmutableSet<Set<String>>} containing one element (the given set * itself). * * <p><b>Note:</b> Despite what the method name suggests, {@code copyOf} will * return constant-space views, rather than linear-space copies, of some * inputs known to be immutable. For some other immutable inputs, such as key * sets of an {@code ImmutableMap}, it still performs a copy in order to avoid * holding references to the values of the map. The heuristics used in this * decision are undocumented and subject to change except that: * <ul> * <li>A full copy will be done of any {@code ImmutableSortedSet}.</li> * <li>{@code ImmutableSet.copyOf()} is idempotent with respect to pointer * equality.</li> * </ul> * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if any of {@code elements} is null * @since 7.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { /* * TODO(user): consider checking for ImmutableAsList here * TODO(user): consider checking for Multiset here */ if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableSet<E> set = (ImmutableSet<E>) elements; if (!set.isPartialView()) { return set; } } else if (elements instanceof EnumSet) { return copyOfEnumSet((EnumSet) elements); } Object[] array = elements.toArray(); return construct(array.length, array); } private static <E extends Enum<E>> ImmutableSet<E> copyOfEnumSet( EnumSet<E> enumSet) { return ImmutableEnumSet.asImmutable(EnumSet.copyOf(enumSet)); } ImmutableSet() {} /** Returns {@code true} if the {@code hashCode()} method runs quickly. */ boolean isHashCodeFast() { return false; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } else if (object instanceof ImmutableSet && isHashCodeFast() && ((ImmutableSet<?>) object).isHashCodeFast() && hashCode() != object.hashCode()) { return false; } return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } // This declaration is needed to make Set.iterator() and // ImmutableCollection.iterator() consistent. @Override public abstract UnmodifiableIterator<E> iterator(); /* * This class is used to serialize all ImmutableSet instances, except for * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It * captures their "logical contents" and they are reconstructed using public * static factories. This is necessary to ensure that the existence of a * particular implementation type is an implementation detail. */ private static class SerializedForm implements Serializable { final Object[] elements; SerializedForm(Object[] elements) { this.elements = elements; } Object readResolve() { return copyOf(elements); } private static final long serialVersionUID = 0; } @Override Object writeReplace() { return new SerializedForm(toArray()); } /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <E> Builder<E> builder() { return new Builder<E>(); } /** * A builder for creating immutable set instances, especially {@code public * static final} sets ("constant sets"). Example: <pre> {@code * * public static final ImmutableSet<Color> GOOGLE_COLORS = * new ImmutableSet.Builder<Color>() * .addAll(WEBSAFE_COLORS) * .add(new Color(0, 191, 255)) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple sets in series. Each set is a superset of the set * created before it. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSet#builder}. */ public Builder() { this(DEFAULT_INITIAL_CAPACITY); } Builder(int capacity) { super(capacity); } /** * Adds {@code element} to the {@code ImmutableSet}. If the {@code * ImmutableSet} already contains {@code element}, then {@code add} has no * effect (only the previously added element is retained). * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { super.add(element); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> add(E... elements) { super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the {@code Iterable} to add to the {@code ImmutableSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add to the {@code ImmutableSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } /** * Returns a newly-created {@code ImmutableSet} based on the contents of * the {@code Builder}. */ @Override public ImmutableSet<E> build() { ImmutableSet<E> result = construct(size, contents); // construct has the side effect of deduping contents, so we update size // accordingly. size = result.size(); return result; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableSet.java
Java
asf20
19,921
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Map.Entry; import javax.annotation.Nullable; /** * {@code keySet()} implementation for {@link ImmutableMap}. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) final class ImmutableMapKeySet<K, V> extends ImmutableSet<K> { private final ImmutableMap<K, V> map; ImmutableMapKeySet(ImmutableMap<K, V> map) { this.map = map; } @Override public int size() { return map.size(); } @Override public UnmodifiableIterator<K> iterator() { return asList().iterator(); } @Override public boolean contains(@Nullable Object object) { return map.containsKey(object); } @Override ImmutableList<K> createAsList() { final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList(); return new ImmutableAsList<K>() { @Override public K get(int index) { return entryList.get(index).getKey(); } @Override ImmutableCollection<K> delegateCollection() { return ImmutableMapKeySet.this; } }; } @Override boolean isPartialView() { return true; } @GwtIncompatible("serialization") @Override Object writeReplace() { return new KeySetSerializedForm<K>(map); } @GwtIncompatible("serialization") private static class KeySetSerializedForm<K> implements Serializable { final ImmutableMap<K, ?> map; KeySetSerializedForm(ImmutableMap<K, ?> map) { this.map = map; } Object readResolve() { return map.keySet(); } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ImmutableMapKeySet.java
Java
asf20
2,351
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Workaround for * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6312706"> * EnumMap bug</a>. If you want to pass an {@code EnumMap}, with the * intention of using its {@code entrySet()} method, you should * wrap the {@code EnumMap} in this class instead. * * <p>This class is not thread-safe even if the underlying map is. * * @author Dimitris Andreou */ @GwtCompatible final class WellBehavedMap<K, V> extends ForwardingMap<K, V> { private final Map<K, V> delegate; private Set<Entry<K, V>> entrySet; private WellBehavedMap(Map<K, V> delegate) { this.delegate = delegate; } /** * Wraps the given map into a {@code WellBehavedEntriesMap}, which * intercepts its {@code entrySet()} method by taking the * {@code Set<K> keySet()} and transforming it to * {@code Set<Entry<K, V>>}. All other invocations are delegated as-is. */ static <K, V> WellBehavedMap<K, V> wrap(Map<K, V> delegate) { return new WellBehavedMap<K, V>(delegate); } @Override protected Map<K, V> delegate() { return delegate; } @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> es = entrySet; if (es != null) { return es; } return entrySet = new EntrySet(); } private final class EntrySet extends Maps.EntrySet<K, V> { @Override Map<K, V> map() { return WellBehavedMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new TransformedIterator<K, Entry<K, V>>(keySet().iterator()) { @Override Entry<K, V> transform(final K key) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return get(key); } @Override public V setValue(V value) { return put(key, value); } }; } }; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/WellBehavedMap.java
Java
asf20
2,749