001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.Predicate;
025import com.google.common.base.Predicates;
026import com.google.common.collect.Collections2.FilteredCollection;
027
028import java.io.Serializable;
029import java.util.AbstractSet;
030import java.util.Arrays;
031import java.util.Collection;
032import java.util.Collections;
033import java.util.Comparator;
034import java.util.EnumSet;
035import java.util.HashSet;
036import java.util.Iterator;
037import java.util.LinkedHashSet;
038import java.util.List;
039import java.util.Map;
040import java.util.NavigableSet;
041import java.util.NoSuchElementException;
042import java.util.Set;
043import java.util.SortedSet;
044import java.util.TreeSet;
045import java.util.concurrent.ConcurrentHashMap;
046import java.util.concurrent.CopyOnWriteArraySet;
047
048import javax.annotation.Nullable;
049
050/**
051 * Static utility methods pertaining to {@link Set} instances. Also see this
052 * class's counterparts {@link Lists}, {@link Maps} and {@link Queues}.
053 *
054 * <p>See the Guava User Guide article on <a href=
055 * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets">
056 * {@code Sets}</a>.
057 *
058 * @author Kevin Bourrillion
059 * @author Jared Levy
060 * @author Chris Povirk
061 * @since 2.0 (imported from Google Collections Library)
062 */
063@GwtCompatible(emulated = true)
064public final class Sets {
065  private Sets() {}
066
067  /**
068   * {@link AbstractSet} substitute without the potentially-quadratic
069   * {@code removeAll} implementation.
070   */
071  abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
072    @Override
073    public boolean removeAll(Collection<?> c) {
074      return removeAllImpl(this, c);
075    }
076
077    @Override
078    public boolean retainAll(Collection<?> c) {
079      return super.retainAll(checkNotNull(c)); // GWT compatibility
080    }
081  }
082
083  /**
084   * Returns an immutable set instance containing the given enum elements.
085   * Internally, the returned set will be backed by an {@link EnumSet}.
086   *
087   * <p>The iteration order of the returned set follows the enum's iteration
088   * order, not the order in which the elements are provided to the method.
089   *
090   * @param anElement one of the elements the set should contain
091   * @param otherElements the rest of the elements the set should contain
092   * @return an immutable set containing those elements, minus duplicates
093   */
094  // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
095  @GwtCompatible(serializable = true)
096  public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
097      E anElement, E... otherElements) {
098    return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
099  }
100
101  /**
102   * Returns an immutable set instance containing the given enum elements.
103   * Internally, the returned set will be backed by an {@link EnumSet}.
104   *
105   * <p>The iteration order of the returned set follows the enum's iteration
106   * order, not the order in which the elements appear in the given collection.
107   *
108   * @param elements the elements, all of the same {@code enum} type, that the
109   *     set should contain
110   * @return an immutable set containing those elements, minus duplicates
111   */
112  // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
113  @GwtCompatible(serializable = true)
114  public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
115      Iterable<E> elements) {
116    if (elements instanceof ImmutableEnumSet) {
117      return (ImmutableEnumSet<E>) elements;
118    } else if (elements instanceof Collection) {
119      Collection<E> collection = (Collection<E>) elements;
120      if (collection.isEmpty()) {
121        return ImmutableSet.of();
122      } else {
123        return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
124      }
125    } else {
126      Iterator<E> itr = elements.iterator();
127      if (itr.hasNext()) {
128        EnumSet<E> enumSet = EnumSet.of(itr.next());
129        Iterators.addAll(enumSet, itr);
130        return ImmutableEnumSet.asImmutable(enumSet);
131      } else {
132        return ImmutableSet.of();
133      }
134    }
135  }
136
137  /**
138   * Returns a new {@code EnumSet} instance containing the given elements.
139   * Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an
140   * exception on an empty collection, and it may be called on any iterable, not
141   * just a {@code Collection}.
142   */
143  public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable,
144      Class<E> elementType) {
145    EnumSet<E> set = EnumSet.noneOf(elementType);
146    Iterables.addAll(set, iterable);
147    return set;
148  }
149
150  // HashSet
151
152  /**
153   * Creates a <i>mutable</i>, empty {@code HashSet} instance.
154   *
155   * <p><b>Note:</b> if mutability is not required, use {@link
156   * ImmutableSet#of()} instead.
157   *
158   * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
159   * EnumSet#noneOf} instead.
160   *
161   * @return a new, empty {@code HashSet}
162   */
163  public static <E> HashSet<E> newHashSet() {
164    return new HashSet<E>();
165  }
166
167  /**
168   * Creates a <i>mutable</i> {@code HashSet} instance containing the given
169   * elements in unspecified order.
170   *
171   * <p><b>Note:</b> if mutability is not required and the elements are
172   * non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or
173   * {@link ImmutableSet#copyOf(Object[])} (for an array) instead.
174   *
175   * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
176   * EnumSet#of(Enum, Enum[])} instead.
177   *
178   * @param elements the elements that the set should contain
179   * @return a new {@code HashSet} containing those elements (minus duplicates)
180   */
181  public static <E> HashSet<E> newHashSet(E... elements) {
182    HashSet<E> set = newHashSetWithExpectedSize(elements.length);
183    Collections.addAll(set, elements);
184    return set;
185  }
186
187  /**
188   * Creates a {@code HashSet} instance, with a high enough "initial capacity"
189   * that it <i>should</i> hold {@code expectedSize} elements without growth.
190   * This behavior cannot be broadly guaranteed, but it is observed to be true
191   * for OpenJDK 1.6. It also can't be guaranteed that the method isn't
192   * inadvertently <i>oversizing</i> the returned set.
193   *
194   * @param expectedSize the number of elements you expect to add to the
195   *        returned set
196   * @return a new, empty {@code HashSet} with enough capacity to hold {@code
197   *         expectedSize} elements without resizing
198   * @throws IllegalArgumentException if {@code expectedSize} is negative
199   */
200  public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
201    return new HashSet<E>(Maps.capacity(expectedSize));
202  }
203
204  /**
205   * Creates a <i>mutable</i> {@code HashSet} instance containing the given
206   * elements in unspecified order.
207   *
208   * <p><b>Note:</b> if mutability is not required and the elements are
209   * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
210   *
211   * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use
212   * {@link #newEnumSet(Iterable, Class)} instead.
213   *
214   * @param elements the elements that the set should contain
215   * @return a new {@code HashSet} containing those elements (minus duplicates)
216   */
217  public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
218    return (elements instanceof Collection)
219        ? new HashSet<E>(Collections2.cast(elements))
220        : newHashSet(elements.iterator());
221  }
222
223  /**
224   * Creates a <i>mutable</i> {@code HashSet} instance containing the given
225   * elements in unspecified order.
226   *
227   * <p><b>Note:</b> if mutability is not required and the elements are
228   * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
229   *
230   * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an
231   * {@link EnumSet} instead.
232   *
233   * @param elements the elements that the set should contain
234   * @return a new {@code HashSet} containing those elements (minus duplicates)
235   */
236  public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
237    HashSet<E> set = newHashSet();
238    Iterators.addAll(set, elements);
239    return set;
240  }
241
242  /**
243   * Creates a thread-safe set backed by a hash map. The set is backed by a
244   * {@link ConcurrentHashMap} instance, and thus carries the same concurrency
245   * guarantees.
246   *
247   * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
248   * used as an element. The set is serializable.
249   *
250   * @return a new, empty thread-safe {@code Set}
251   * @since 15.0
252   */
253  public static <E> Set<E> newConcurrentHashSet() {
254    return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
255  }
256
257  /**
258   * Creates a thread-safe set backed by a hash map and containing the given
259   * elements. The set is backed by a {@link ConcurrentHashMap} instance, and
260   * thus carries the same concurrency guarantees.
261   *
262   * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
263   * used as an element. The set is serializable.
264   *
265   * @param elements the elements that the set should contain
266   * @return a new thread-safe set containing those elements (minus duplicates)
267   * @throws NullPointerException if {@code elements} or any of its contents is
268   *      null
269   * @since 15.0
270   */
271  public static <E> Set<E> newConcurrentHashSet(
272      Iterable<? extends E> elements) {
273    Set<E> set = newConcurrentHashSet();
274    Iterables.addAll(set, elements);
275    return set;
276  }
277
278  // LinkedHashSet
279
280  /**
281   * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
282   *
283   * <p><b>Note:</b> if mutability is not required, use {@link
284   * ImmutableSet#of()} instead.
285   *
286   * @return a new, empty {@code LinkedHashSet}
287   */
288  public static <E> LinkedHashSet<E> newLinkedHashSet() {
289    return new LinkedHashSet<E>();
290  }
291
292  /**
293   * Creates a {@code LinkedHashSet} instance, with a high enough "initial
294   * capacity" that it <i>should</i> hold {@code expectedSize} elements without
295   * growth. This behavior cannot be broadly guaranteed, but it is observed to
296   * be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't
297   * inadvertently <i>oversizing</i> the returned set.
298   *
299   * @param expectedSize the number of elements you expect to add to the
300   *        returned set
301   * @return a new, empty {@code LinkedHashSet} with enough capacity to hold
302   *         {@code expectedSize} elements without resizing
303   * @throws IllegalArgumentException if {@code expectedSize} is negative
304   * @since 11.0
305   */
306  public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
307      int expectedSize) {
308    return new LinkedHashSet<E>(Maps.capacity(expectedSize));
309  }
310
311  /**
312   * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the
313   * given elements in order.
314   *
315   * <p><b>Note:</b> if mutability is not required and the elements are
316   * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
317   *
318   * @param elements the elements that the set should contain, in order
319   * @return a new {@code LinkedHashSet} containing those elements (minus
320   *     duplicates)
321   */
322  public static <E> LinkedHashSet<E> newLinkedHashSet(
323      Iterable<? extends E> elements) {
324    if (elements instanceof Collection) {
325      return new LinkedHashSet<E>(Collections2.cast(elements));
326    }
327    LinkedHashSet<E> set = newLinkedHashSet();
328    Iterables.addAll(set, elements);
329    return set;
330  }
331
332  // TreeSet
333
334  /**
335   * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the
336   * natural sort ordering of its elements.
337   *
338   * <p><b>Note:</b> if mutability is not required, use {@link
339   * ImmutableSortedSet#of()} instead.
340   *
341   * @return a new, empty {@code TreeSet}
342   */
343  public static <E extends Comparable> TreeSet<E> newTreeSet() {
344    return new TreeSet<E>();
345  }
346
347  /**
348   * Creates a <i>mutable</i> {@code TreeSet} instance containing the given
349   * elements sorted by their natural ordering.
350   *
351   * <p><b>Note:</b> if mutability is not required, use {@link
352   * ImmutableSortedSet#copyOf(Iterable)} instead.
353   *
354   * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit
355   * comparator, this method has different behavior than
356   * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with
357   * that comparator.
358   *
359   * @param elements the elements that the set should contain
360   * @return a new {@code TreeSet} containing those elements (minus duplicates)
361   */
362  public static <E extends Comparable> TreeSet<E> newTreeSet(
363      Iterable<? extends E> elements) {
364    TreeSet<E> set = newTreeSet();
365    Iterables.addAll(set, elements);
366    return set;
367  }
368
369  /**
370   * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given
371   * comparator.
372   *
373   * <p><b>Note:</b> if mutability is not required, use {@code
374   * ImmutableSortedSet.orderedBy(comparator).build()} instead.
375   *
376   * @param comparator the comparator to use to sort the set
377   * @return a new, empty {@code TreeSet}
378   * @throws NullPointerException if {@code comparator} is null
379   */
380  public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
381    return new TreeSet<E>(checkNotNull(comparator));
382  }
383
384  /**
385   * Creates an empty {@code Set} that uses identity to determine equality. It
386   * compares object references, instead of calling {@code equals}, to
387   * determine whether a provided object matches an element in the set. For
388   * example, {@code contains} returns {@code false} when passed an object that
389   * equals a set member, but isn't the same instance. This behavior is similar
390   * to the way {@code IdentityHashMap} handles key lookups.
391   *
392   * @since 8.0
393   */
394  public static <E> Set<E> newIdentityHashSet() {
395    return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
396  }
397
398  /**
399   * Creates an empty {@code CopyOnWriteArraySet} instance.
400   *
401   * <p><b>Note:</b> if you need an immutable empty {@link Set}, use
402   * {@link Collections#emptySet} instead.
403   *
404   * @return a new, empty {@code CopyOnWriteArraySet}
405   * @since 12.0
406   */
407  @GwtIncompatible("CopyOnWriteArraySet")
408  public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
409    return new CopyOnWriteArraySet<E>();
410  }
411
412  /**
413   * Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
414   *
415   * @param elements the elements that the set should contain, in order
416   * @return a new {@code CopyOnWriteArraySet} containing those elements
417   * @since 12.0
418   */
419  @GwtIncompatible("CopyOnWriteArraySet")
420  public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
421      Iterable<? extends E> elements) {
422    // We copy elements to an ArrayList first, rather than incurring the
423    // quadratic cost of adding them to the COWAS directly.
424    Collection<? extends E> elementsCollection = (elements instanceof Collection)
425        ? Collections2.cast(elements)
426        : Lists.newArrayList(elements);
427    return new CopyOnWriteArraySet<E>(elementsCollection);
428  }
429
430  /**
431   * Creates an {@code EnumSet} consisting of all enum values that are not in
432   * the specified collection. If the collection is an {@link EnumSet}, this
433   * method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
434   * the specified collection must contain at least one element, in order to
435   * determine the element type. If the collection could be empty, use
436   * {@link #complementOf(Collection, Class)} instead of this method.
437   *
438   * @param collection the collection whose complement should be stored in the
439   *     enum set
440   * @return a new, modifiable {@code EnumSet} containing all values of the enum
441   *     that aren't present in the given collection
442   * @throws IllegalArgumentException if {@code collection} is not an
443   *     {@code EnumSet} instance and contains no elements
444   */
445  public static <E extends Enum<E>> EnumSet<E> complementOf(
446      Collection<E> collection) {
447    if (collection instanceof EnumSet) {
448      return EnumSet.complementOf((EnumSet<E>) collection);
449    }
450    checkArgument(!collection.isEmpty(),
451        "collection is empty; use the other version of this method");
452    Class<E> type = collection.iterator().next().getDeclaringClass();
453    return makeComplementByHand(collection, type);
454  }
455
456  /**
457   * Creates an {@code EnumSet} consisting of all enum values that are not in
458   * the specified collection. This is equivalent to
459   * {@link EnumSet#complementOf}, but can act on any input collection, as long
460   * as the elements are of enum type.
461   *
462   * @param collection the collection whose complement should be stored in the
463   *     {@code EnumSet}
464   * @param type the type of the elements in the set
465   * @return a new, modifiable {@code EnumSet} initially containing all the
466   *     values of the enum not present in the given collection
467   */
468  public static <E extends Enum<E>> EnumSet<E> complementOf(
469      Collection<E> collection, Class<E> type) {
470    checkNotNull(collection);
471    return (collection instanceof EnumSet)
472        ? EnumSet.complementOf((EnumSet<E>) collection)
473        : makeComplementByHand(collection, type);
474  }
475
476  private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
477      Collection<E> collection, Class<E> type) {
478    EnumSet<E> result = EnumSet.allOf(type);
479    result.removeAll(collection);
480    return result;
481  }
482
483  /**
484   * Returns a set backed by the specified map. The resulting set displays
485   * the same ordering, concurrency, and performance characteristics as the
486   * backing map. In essence, this factory method provides a {@link Set}
487   * implementation corresponding to any {@link Map} implementation. There is no
488   * need to use this method on a {@link Map} implementation that already has a
489   * corresponding {@link Set} implementation (such as {@link java.util.HashMap}
490   * or {@link java.util.TreeMap}).
491   *
492   * <p>Each method invocation on the set returned by this method results in
493   * exactly one method invocation on the backing map or its {@code keySet}
494   * view, with one exception. The {@code addAll} method is implemented as a
495   * sequence of {@code put} invocations on the backing map.
496   *
497   * <p>The specified map must be empty at the time this method is invoked,
498   * and should not be accessed directly after this method returns. These
499   * conditions are ensured if the map is created empty, passed directly
500   * to this method, and no reference to the map is retained, as illustrated
501   * in the following code fragment: <pre>  {@code
502   *
503   *   Set<Object> identityHashSet = Sets.newSetFromMap(
504   *       new IdentityHashMap<Object, Boolean>());}</pre>
505   *
506   * <p>This method has the same behavior as the JDK 6 method
507   * {@code Collections.newSetFromMap()}. The returned set is serializable if
508   * the backing map is.
509   *
510   * @param map the backing map
511   * @return the set backed by the map
512   * @throws IllegalArgumentException if {@code map} is not empty
513   */
514  public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
515    return Platform.newSetFromMap(map);
516  }
517
518  /**
519   * An unmodifiable view of a set which may be backed by other sets; this view
520   * will change as the backing sets do. Contains methods to copy the data into
521   * a new set which will then remain stable. There is usually no reason to
522   * retain a reference of type {@code SetView}; typically, you either use it
523   * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
524   * {@link #copyInto} and forget the {@code SetView} itself.
525   *
526   * @since 2.0 (imported from Google Collections Library)
527   */
528  public abstract static class SetView<E> extends AbstractSet<E> {
529    private SetView() {} // no subclasses but our own
530
531    /**
532     * Returns an immutable copy of the current contents of this set view.
533     * Does not support null elements.
534     *
535     * <p><b>Warning:</b> this may have unexpected results if a backing set of
536     * this view uses a nonstandard notion of equivalence, for example if it is
537     * a {@link TreeSet} using a comparator that is inconsistent with {@link
538     * Object#equals(Object)}.
539     */
540    public ImmutableSet<E> immutableCopy() {
541      return ImmutableSet.copyOf(this);
542    }
543
544    /**
545     * Copies the current contents of this set view into an existing set. This
546     * method has equivalent behavior to {@code set.addAll(this)}, assuming that
547     * all the sets involved are based on the same notion of equivalence.
548     *
549     * @return a reference to {@code set}, for convenience
550     */
551    // Note: S should logically extend Set<? super E> but can't due to either
552    // some javac bug or some weirdness in the spec, not sure which.
553    public <S extends Set<E>> S copyInto(S set) {
554      set.addAll(this);
555      return set;
556    }
557  }
558
559  /**
560   * Returns an unmodifiable <b>view</b> of the union of two sets. The returned
561   * set contains all elements that are contained in either backing set.
562   * Iterating over the returned set iterates first over all the elements of
563   * {@code set1}, then over each element of {@code set2}, in order, that is not
564   * contained in {@code set1}.
565   *
566   * <p>Results are undefined if {@code set1} and {@code set2} are sets based on
567   * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
568   * the {@link Map#keySet} of an {@code IdentityHashMap} all are).
569   *
570   * <p><b>Note:</b> The returned view performs better when {@code set1} is the
571   * smaller of the two sets. If you have reason to believe one of your sets
572   * will generally be smaller than the other, pass it first.
573   *
574   * <p>Further, note that the current implementation is not suitable for nested
575   * {@code union} views, i.e. the following should be avoided when in a loop:
576   * {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
577   * set has a cubic complexity to the depth of the nesting.
578   */
579  public static <E> SetView<E> union(
580      final Set<? extends E> set1, final Set<? extends E> set2) {
581    checkNotNull(set1, "set1");
582    checkNotNull(set2, "set2");
583
584    final Set<? extends E> set2minus1 = difference(set2, set1);
585
586    return new SetView<E>() {
587      @Override public int size() {
588        return set1.size() + set2minus1.size();
589      }
590      @Override public boolean isEmpty() {
591        return set1.isEmpty() && set2.isEmpty();
592      }
593      @Override public Iterator<E> iterator() {
594        return Iterators.unmodifiableIterator(
595            Iterators.concat(set1.iterator(), set2minus1.iterator()));
596      }
597      @Override public boolean contains(Object object) {
598        return set1.contains(object) || set2.contains(object);
599      }
600      @Override public <S extends Set<E>> S copyInto(S set) {
601        set.addAll(set1);
602        set.addAll(set2);
603        return set;
604      }
605      @Override public ImmutableSet<E> immutableCopy() {
606        return new ImmutableSet.Builder<E>()
607            .addAll(set1).addAll(set2).build();
608      }
609    };
610  }
611
612  /**
613   * Returns an unmodifiable <b>view</b> of the intersection of two sets. The
614   * returned set contains all elements that are contained by both backing sets.
615   * The iteration order of the returned set matches that of {@code set1}.
616   *
617   * <p>Results are undefined if {@code set1} and {@code set2} are sets based
618   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
619   * and the keySet of an {@code IdentityHashMap} all are).
620   *
621   * <p><b>Note:</b> The returned view performs slightly better when {@code
622   * set1} is the smaller of the two sets. If you have reason to believe one of
623   * your sets will generally be smaller than the other, pass it first.
624   * Unfortunately, since this method sets the generic type of the returned set
625   * based on the type of the first set passed, this could in rare cases force
626   * you to make a cast, for example: <pre>   {@code
627   *
628   *   Set<Object> aFewBadObjects = ...
629   *   Set<String> manyBadStrings = ...
630   *
631   *   // impossible for a non-String to be in the intersection
632   *   SuppressWarnings("unchecked")
633   *   Set<String> badStrings = (Set) Sets.intersection(
634   *       aFewBadObjects, manyBadStrings);}</pre>
635   *
636   * <p>This is unfortunate, but should come up only very rarely.
637   */
638  public static <E> SetView<E> intersection(
639      final Set<E> set1, final Set<?> set2) {
640    checkNotNull(set1, "set1");
641    checkNotNull(set2, "set2");
642
643    final Predicate<Object> inSet2 = Predicates.in(set2);
644    return new SetView<E>() {
645      @Override public Iterator<E> iterator() {
646        return Iterators.filter(set1.iterator(), inSet2);
647      }
648      @Override public int size() {
649        return Iterators.size(iterator());
650      }
651      @Override public boolean isEmpty() {
652        return !iterator().hasNext();
653      }
654      @Override public boolean contains(Object object) {
655        return set1.contains(object) && set2.contains(object);
656      }
657      @Override public boolean containsAll(Collection<?> collection) {
658        return set1.containsAll(collection)
659            && set2.containsAll(collection);
660      }
661    };
662  }
663
664  /**
665   * Returns an unmodifiable <b>view</b> of the difference of two sets. The
666   * returned set contains all elements that are contained by {@code set1} and
667   * not contained by {@code set2}. {@code set2} may also contain elements not
668   * present in {@code set1}; these are simply ignored. The iteration order of
669   * the returned set matches that of {@code set1}.
670   *
671   * <p>Results are undefined if {@code set1} and {@code set2} are sets based
672   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
673   * and the keySet of an {@code IdentityHashMap} all are).
674   */
675  public static <E> SetView<E> difference(
676      final Set<E> set1, final Set<?> set2) {
677    checkNotNull(set1, "set1");
678    checkNotNull(set2, "set2");
679
680    final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
681    return new SetView<E>() {
682      @Override public Iterator<E> iterator() {
683        return Iterators.filter(set1.iterator(), notInSet2);
684      }
685      @Override public int size() {
686        return Iterators.size(iterator());
687      }
688      @Override public boolean isEmpty() {
689        return set2.containsAll(set1);
690      }
691      @Override public boolean contains(Object element) {
692        return set1.contains(element) && !set2.contains(element);
693      }
694    };
695  }
696
697  /**
698   * Returns an unmodifiable <b>view</b> of the symmetric difference of two
699   * sets. The returned set contains all elements that are contained in either
700   * {@code set1} or {@code set2} but not in both. The iteration order of the
701   * returned set is undefined.
702   *
703   * <p>Results are undefined if {@code set1} and {@code set2} are sets based
704   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
705   * and the keySet of an {@code IdentityHashMap} all are).
706   *
707   * @since 3.0
708   */
709  public static <E> SetView<E> symmetricDifference(
710      Set<? extends E> set1, Set<? extends E> set2) {
711    checkNotNull(set1, "set1");
712    checkNotNull(set2, "set2");
713
714    // TODO(kevinb): Replace this with a more efficient implementation
715    return difference(union(set1, set2), intersection(set1, set2));
716  }
717
718  /**
719   * Returns the elements of {@code unfiltered} that satisfy a predicate. The
720   * returned set is a live view of {@code unfiltered}; changes to one affect
721   * the other.
722   *
723   * <p>The resulting set's iterator does not support {@code remove()}, but all
724   * other set methods are supported. When given an element that doesn't satisfy
725   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
726   * an {@link IllegalArgumentException}. When methods such as {@code
727   * removeAll()} and {@code clear()} are called on the filtered set, only
728   * elements that satisfy the filter will be removed from the underlying set.
729   *
730   * <p>The returned set isn't threadsafe or serializable, even if
731   * {@code unfiltered} is.
732   *
733   * <p>Many of the filtered set's methods, such as {@code size()}, iterate
734   * across every element in the underlying set and determine which elements
735   * satisfy the filter. When a live view is <i>not</i> needed, it may be faster
736   * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
737   *
738   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
739   * as documented at {@link Predicate#apply}. Do not provide a predicate such
740   * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
741   * with equals. (See {@link Iterables#filter(Iterable, Class)} for related
742   * functionality.)
743   */
744  // TODO(kevinb): how to omit that last sentence when building GWT javadoc?
745  public static <E> Set<E> filter(
746      Set<E> unfiltered, Predicate<? super E> predicate) {
747    if (unfiltered instanceof SortedSet) {
748      return filter((SortedSet<E>) unfiltered, predicate);
749    }
750    if (unfiltered instanceof FilteredSet) {
751      // Support clear(), removeAll(), and retainAll() when filtering a filtered
752      // collection.
753      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
754      Predicate<E> combinedPredicate
755          = Predicates.<E>and(filtered.predicate, predicate);
756      return new FilteredSet<E>(
757          (Set<E>) filtered.unfiltered, combinedPredicate);
758    }
759
760    return new FilteredSet<E>(
761        checkNotNull(unfiltered), checkNotNull(predicate));
762  }
763
764  private static class FilteredSet<E> extends FilteredCollection<E>
765      implements Set<E> {
766    FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
767      super(unfiltered, predicate);
768    }
769
770    @Override public boolean equals(@Nullable Object object) {
771      return equalsImpl(this, object);
772    }
773
774    @Override public int hashCode() {
775      return hashCodeImpl(this);
776    }
777  }
778
779  /**
780   * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
781   * satisfy a predicate. The returned set is a live view of {@code unfiltered};
782   * changes to one affect the other.
783   *
784   * <p>The resulting set's iterator does not support {@code remove()}, but all
785   * other set methods are supported. When given an element that doesn't satisfy
786   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
787   * an {@link IllegalArgumentException}. When methods such as
788   * {@code removeAll()} and {@code clear()} are called on the filtered set,
789   * only elements that satisfy the filter will be removed from the underlying
790   * set.
791   *
792   * <p>The returned set isn't threadsafe or serializable, even if
793   * {@code unfiltered} is.
794   *
795   * <p>Many of the filtered set's methods, such as {@code size()}, iterate across
796   * every element in the underlying set and determine which elements satisfy
797   * the filter. When a live view is <i>not</i> needed, it may be faster to copy
798   * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
799   *
800   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
801   * as documented at {@link Predicate#apply}. Do not provide a predicate such as
802   * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
803   * equals. (See {@link Iterables#filter(Iterable, Class)} for related
804   * functionality.)
805   *
806   * @since 11.0
807   */
808  public static <E> SortedSet<E> filter(
809      SortedSet<E> unfiltered, Predicate<? super E> predicate) {
810    return Platform.setsFilterSortedSet(unfiltered, predicate);
811  }
812
813  static <E> SortedSet<E> filterSortedIgnoreNavigable(
814      SortedSet<E> unfiltered, Predicate<? super E> predicate) {
815    if (unfiltered instanceof FilteredSet) {
816      // Support clear(), removeAll(), and retainAll() when filtering a filtered
817      // collection.
818      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
819      Predicate<E> combinedPredicate
820          = Predicates.<E>and(filtered.predicate, predicate);
821      return new FilteredSortedSet<E>(
822          (SortedSet<E>) filtered.unfiltered, combinedPredicate);
823    }
824
825    return new FilteredSortedSet<E>(
826        checkNotNull(unfiltered), checkNotNull(predicate));
827  }
828
829  private static class FilteredSortedSet<E> extends FilteredSet<E>
830      implements SortedSet<E> {
831
832    FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
833      super(unfiltered, predicate);
834    }
835
836    @Override
837    public Comparator<? super E> comparator() {
838      return ((SortedSet<E>) unfiltered).comparator();
839    }
840
841    @Override
842    public SortedSet<E> subSet(E fromElement, E toElement) {
843      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement),
844          predicate);
845    }
846
847    @Override
848    public SortedSet<E> headSet(E toElement) {
849      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
850    }
851
852    @Override
853    public SortedSet<E> tailSet(E fromElement) {
854      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
855    }
856
857    @Override
858    public E first() {
859      return iterator().next();
860    }
861
862    @Override
863    public E last() {
864      SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
865      while (true) {
866        E element = sortedUnfiltered.last();
867        if (predicate.apply(element)) {
868          return element;
869        }
870        sortedUnfiltered = sortedUnfiltered.headSet(element);
871      }
872    }
873  }
874
875  /**
876   * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that
877   * satisfy a predicate. The returned set is a live view of {@code unfiltered};
878   * changes to one affect the other.
879   *
880   * <p>The resulting set's iterator does not support {@code remove()}, but all
881   * other set methods are supported. When given an element that doesn't satisfy
882   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
883   * an {@link IllegalArgumentException}. When methods such as
884   * {@code removeAll()} and {@code clear()} are called on the filtered set,
885   * only elements that satisfy the filter will be removed from the underlying
886   * set.
887   *
888   * <p>The returned set isn't threadsafe or serializable, even if
889   * {@code unfiltered} is.
890   *
891   * <p>Many of the filtered set's methods, such as {@code size()}, iterate across
892   * every element in the underlying set and determine which elements satisfy
893   * the filter. When a live view is <i>not</i> needed, it may be faster to copy
894   * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
895   *
896   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
897   * as documented at {@link Predicate#apply}. Do not provide a predicate such as
898   * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
899   * equals. (See {@link Iterables#filter(Iterable, Class)} for related
900   * functionality.)
901   *
902   * @since 14.0
903   */
904  @GwtIncompatible("NavigableSet")
905  @SuppressWarnings("unchecked")
906  public static <E> NavigableSet<E> filter(
907      NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
908    if (unfiltered instanceof FilteredSet) {
909      // Support clear(), removeAll(), and retainAll() when filtering a filtered
910      // collection.
911      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
912      Predicate<E> combinedPredicate
913          = Predicates.<E>and(filtered.predicate, predicate);
914      return new FilteredNavigableSet<E>(
915          (NavigableSet<E>) filtered.unfiltered, combinedPredicate);
916    }
917
918    return new FilteredNavigableSet<E>(
919        checkNotNull(unfiltered), checkNotNull(predicate));
920  }
921
922  @GwtIncompatible("NavigableSet")
923  private static class FilteredNavigableSet<E> extends FilteredSortedSet<E>
924      implements NavigableSet<E> {
925    FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
926      super(unfiltered, predicate);
927    }
928
929    NavigableSet<E> unfiltered() {
930      return (NavigableSet<E>) unfiltered;
931    }
932
933    @Override
934    @Nullable
935    public E lower(E e) {
936      return Iterators.getNext(headSet(e, false).descendingIterator(), null);
937    }
938
939    @Override
940    @Nullable
941    public E floor(E e) {
942      return Iterators.getNext(headSet(e, true).descendingIterator(), null);
943    }
944
945    @Override
946    public E ceiling(E e) {
947      return Iterables.getFirst(tailSet(e, true), null);
948    }
949
950    @Override
951    public E higher(E e) {
952      return Iterables.getFirst(tailSet(e, false), null);
953    }
954
955    @Override
956    public E pollFirst() {
957      return Iterables.removeFirstMatching(unfiltered(), predicate);
958    }
959
960    @Override
961    public E pollLast() {
962      return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate);
963    }
964
965    @Override
966    public NavigableSet<E> descendingSet() {
967      return Sets.filter(unfiltered().descendingSet(), predicate);
968    }
969
970    @Override
971    public Iterator<E> descendingIterator() {
972      return Iterators.filter(unfiltered().descendingIterator(), predicate);
973    }
974
975    @Override
976    public E last() {
977      return descendingIterator().next();
978    }
979
980    @Override
981    public NavigableSet<E> subSet(
982        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
983      return filter(
984          unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate);
985    }
986
987    @Override
988    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
989      return filter(unfiltered().headSet(toElement, inclusive), predicate);
990    }
991
992    @Override
993    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
994      return filter(unfiltered().tailSet(fromElement, inclusive), predicate);
995    }
996  }
997
998  /**
999   * Returns every possible list that can be formed by choosing one element
1000   * from each of the given sets in order; the "n-ary
1001   * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
1002   * product</a>" of the sets. For example: <pre>   {@code
1003   *
1004   *   Sets.cartesianProduct(ImmutableList.of(
1005   *       ImmutableSet.of(1, 2),
1006   *       ImmutableSet.of("A", "B", "C")))}</pre>
1007   *
1008   * <p>returns a set containing six lists:
1009   *
1010   * <ul>
1011   * <li>{@code ImmutableList.of(1, "A")}
1012   * <li>{@code ImmutableList.of(1, "B")}
1013   * <li>{@code ImmutableList.of(1, "C")}
1014   * <li>{@code ImmutableList.of(2, "A")}
1015   * <li>{@code ImmutableList.of(2, "B")}
1016   * <li>{@code ImmutableList.of(2, "C")}
1017   * </ul>
1018   *
1019   * <p>The result is guaranteed to be in the "traditional", lexicographical
1020   * order for Cartesian products that you would get from nesting for loops:
1021   * <pre>   {@code
1022   *
1023   *   for (B b0 : sets.get(0)) {
1024   *     for (B b1 : sets.get(1)) {
1025   *       ...
1026   *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
1027   *       // operate on tuple
1028   *     }
1029   *   }}</pre>
1030   *
1031   * <p>Note that if any input set is empty, the Cartesian product will also be
1032   * empty. If no sets at all are provided (an empty list), the resulting
1033   * Cartesian product has one element, an empty list (counter-intuitive, but
1034   * mathematically consistent).
1035   *
1036   * <p><i>Performance notes:</i> while the cartesian product of sets of size
1037   * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
1038   * consumption is much smaller. When the cartesian set is constructed, the
1039   * input sets are merely copied. Only as the resulting set is iterated are the
1040   * individual lists created, and these are not retained after iteration.
1041   *
1042   * @param sets the sets to choose elements from, in the order that
1043   *     the elements chosen from those sets should appear in the resulting
1044   *     lists
1045   * @param <B> any common base class shared by all axes (often just {@link
1046   *     Object})
1047   * @return the Cartesian product, as an immutable set containing immutable
1048   *     lists
1049   * @throws NullPointerException if {@code sets}, any one of the {@code sets},
1050   *     or any element of a provided set is null
1051   * @since 2.0
1052   */
1053  public static <B> Set<List<B>> cartesianProduct(
1054      List<? extends Set<? extends B>> sets) {
1055    return CartesianSet.create(sets);
1056  }
1057
1058  /**
1059   * Returns every possible list that can be formed by choosing one element
1060   * from each of the given sets in order; the "n-ary
1061   * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
1062   * product</a>" of the sets. For example: <pre>   {@code
1063   *
1064   *   Sets.cartesianProduct(
1065   *       ImmutableSet.of(1, 2),
1066   *       ImmutableSet.of("A", "B", "C"))}</pre>
1067   *
1068   * <p>returns a set containing six lists:
1069   *
1070   * <ul>
1071   * <li>{@code ImmutableList.of(1, "A")}
1072   * <li>{@code ImmutableList.of(1, "B")}
1073   * <li>{@code ImmutableList.of(1, "C")}
1074   * <li>{@code ImmutableList.of(2, "A")}
1075   * <li>{@code ImmutableList.of(2, "B")}
1076   * <li>{@code ImmutableList.of(2, "C")}
1077   * </ul>
1078   *
1079   * <p>The result is guaranteed to be in the "traditional", lexicographical
1080   * order for Cartesian products that you would get from nesting for loops:
1081   * <pre>   {@code
1082   *
1083   *   for (B b0 : sets.get(0)) {
1084   *     for (B b1 : sets.get(1)) {
1085   *       ...
1086   *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
1087   *       // operate on tuple
1088   *     }
1089   *   }}</pre>
1090   *
1091   * <p>Note that if any input set is empty, the Cartesian product will also be
1092   * empty. If no sets at all are provided (an empty list), the resulting
1093   * Cartesian product has one element, an empty list (counter-intuitive, but
1094   * mathematically consistent).
1095   *
1096   * <p><i>Performance notes:</i> while the cartesian product of sets of size
1097   * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
1098   * consumption is much smaller. When the cartesian set is constructed, the
1099   * input sets are merely copied. Only as the resulting set is iterated are the
1100   * individual lists created, and these are not retained after iteration.
1101   *
1102   * @param sets the sets to choose elements from, in the order that
1103   *     the elements chosen from those sets should appear in the resulting
1104   *     lists
1105   * @param <B> any common base class shared by all axes (often just {@link
1106   *     Object})
1107   * @return the Cartesian product, as an immutable set containing immutable
1108   *     lists
1109   * @throws NullPointerException if {@code sets}, any one of the {@code sets},
1110   *     or any element of a provided set is null
1111   * @since 2.0
1112   */
1113  public static <B> Set<List<B>> cartesianProduct(
1114      Set<? extends B>... sets) {
1115    return cartesianProduct(Arrays.asList(sets));
1116  }
1117
1118  private static final class CartesianSet<E>
1119      extends ForwardingCollection<List<E>> implements Set<List<E>> {
1120    private transient final ImmutableList<ImmutableSet<E>> axes;
1121    private transient final CartesianList<E> delegate;
1122
1123    static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
1124      ImmutableList.Builder<ImmutableSet<E>> axesBuilder =
1125          new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
1126      for (Set<? extends E> set : sets) {
1127        ImmutableSet<E> copy = ImmutableSet.copyOf(set);
1128        if (copy.isEmpty()) {
1129          return ImmutableSet.of();
1130        }
1131        axesBuilder.add(copy);
1132      }
1133      final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
1134      ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() {
1135
1136        @Override
1137        public int size() {
1138          return axes.size();
1139        }
1140
1141        @Override
1142        public List<E> get(int index) {
1143          return axes.get(index).asList();
1144        }
1145
1146        @Override
1147        boolean isPartialView() {
1148          return true;
1149        }
1150      };
1151      return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
1152    }
1153
1154    private CartesianSet(
1155        ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
1156      this.axes = axes;
1157      this.delegate = delegate;
1158    }
1159
1160    @Override
1161    protected Collection<List<E>> delegate() {
1162      return delegate;
1163    }
1164
1165    @Override public boolean equals(@Nullable Object object) {
1166      // Warning: this is broken if size() == 0, so it is critical that we
1167      // substitute an empty ImmutableSet to the user in place of this
1168      if (object instanceof CartesianSet) {
1169        CartesianSet<?> that = (CartesianSet<?>) object;
1170        return this.axes.equals(that.axes);
1171      }
1172      return super.equals(object);
1173    }
1174
1175    @Override
1176    public int hashCode() {
1177      // Warning: this is broken if size() == 0, so it is critical that we
1178      // substitute an empty ImmutableSet to the user in place of this
1179
1180      // It's a weird formula, but tests prove it works.
1181      int adjust = size() - 1;
1182      for (int i = 0; i < axes.size(); i++) {
1183        adjust *= 31;
1184        adjust = ~~adjust;
1185        // in GWT, we have to deal with integer overflow carefully
1186      }
1187      int hash = 1;
1188      for (Set<E> axis : axes) {
1189        hash = 31 * hash + (size() / axis.size() * axis.hashCode());
1190
1191        hash = ~~hash;
1192      }
1193      hash += adjust;
1194      return ~~hash;
1195    }
1196  }
1197
1198  /**
1199   * Returns the set of all possible subsets of {@code set}. For example,
1200   * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
1201   * {1}, {2}, {1, 2}}}.
1202   *
1203   * <p>Elements appear in these subsets in the same iteration order as they
1204   * appeared in the input set. The order in which these subsets appear in the
1205   * outer set is undefined. Note that the power set of the empty set is not the
1206   * empty set, but a one-element set containing the empty set.
1207   *
1208   * <p>The returned set and its constituent sets use {@code equals} to decide
1209   * whether two elements are identical, even if the input set uses a different
1210   * concept of equivalence.
1211   *
1212   * <p><i>Performance notes:</i> while the power set of a set with size {@code
1213   * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
1214   * power set is constructed, the input set is merely copied. Only as the
1215   * power set is iterated are the individual subsets created, and these subsets
1216   * themselves occupy only a small constant amount of memory.
1217   *
1218   * @param set the set of elements to construct a power set from
1219   * @return the power set, as an immutable set of immutable sets
1220   * @throws IllegalArgumentException if {@code set} has more than 30 unique
1221   *     elements (causing the power set size to exceed the {@code int} range)
1222   * @throws NullPointerException if {@code set} is or contains {@code null}
1223   * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
1224   *      Wikipedia</a>
1225   * @since 4.0
1226   */
1227  @GwtCompatible(serializable = false)
1228  public static <E> Set<Set<E>> powerSet(Set<E> set) {
1229    return new PowerSet<E>(set);
1230  }
1231
1232  private static final class SubSet<E> extends AbstractSet<E> {
1233    private final ImmutableMap<E, Integer> inputSet;
1234    private final int mask;
1235
1236    SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
1237      this.inputSet = inputSet;
1238      this.mask = mask;
1239    }
1240
1241    @Override
1242    public Iterator<E> iterator() {
1243      return new UnmodifiableIterator<E>() {
1244        final ImmutableList<E> elements = inputSet.keySet().asList();
1245        int remainingSetBits = mask;
1246
1247        @Override
1248        public boolean hasNext() {
1249          return remainingSetBits != 0;
1250        }
1251
1252        @Override
1253        public E next() {
1254          int index = Integer.numberOfTrailingZeros(remainingSetBits);
1255          if (index == 32) {
1256            throw new NoSuchElementException();
1257          }
1258          remainingSetBits &= ~(1 << index);
1259          return elements.get(index);
1260        }
1261      };
1262    }
1263
1264    @Override
1265    public int size() {
1266      return Integer.bitCount(mask);
1267    }
1268
1269    @Override
1270    public boolean contains(@Nullable Object o) {
1271      Integer index = inputSet.get(o);
1272      return index != null && (mask & (1 << index)) != 0;
1273    }
1274  }
1275
1276  private static final class PowerSet<E> extends AbstractSet<Set<E>> {
1277    final ImmutableMap<E, Integer> inputSet;
1278
1279    PowerSet(Set<E> input) {
1280      ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
1281      int i = 0;
1282      for (E e : checkNotNull(input)) {
1283        builder.put(e, i++);
1284      }
1285      this.inputSet = builder.build();
1286      checkArgument(inputSet.size() <= 30,
1287          "Too many elements to create power set: %s > 30", inputSet.size());
1288    }
1289
1290    @Override public int size() {
1291      return 1 << inputSet.size();
1292    }
1293
1294    @Override public boolean isEmpty() {
1295      return false;
1296    }
1297
1298    @Override public Iterator<Set<E>> iterator() {
1299      return new AbstractIndexedListIterator<Set<E>>(size()) {
1300        @Override protected Set<E> get(final int setBits) {
1301          return new SubSet<E>(inputSet, setBits);
1302        }
1303      };
1304    }
1305
1306    @Override public boolean contains(@Nullable Object obj) {
1307      if (obj instanceof Set) {
1308        Set<?> set = (Set<?>) obj;
1309        return inputSet.keySet().containsAll(set);
1310      }
1311      return false;
1312    }
1313
1314    @Override public boolean equals(@Nullable Object obj) {
1315      if (obj instanceof PowerSet) {
1316        PowerSet<?> that = (PowerSet<?>) obj;
1317        return inputSet.equals(that.inputSet);
1318      }
1319      return super.equals(obj);
1320    }
1321
1322    @Override public int hashCode() {
1323      /*
1324       * The sum of the sums of the hash codes in each subset is just the sum of
1325       * each input element's hash code times the number of sets that element
1326       * appears in. Each element appears in exactly half of the 2^n sets, so:
1327       */
1328      return inputSet.keySet().hashCode() << (inputSet.size() - 1);
1329    }
1330
1331    @Override public String toString() {
1332      return "powerSet(" + inputSet + ")";
1333    }
1334  }
1335
1336  /**
1337   * An implementation for {@link Set#hashCode()}.
1338   */
1339  static int hashCodeImpl(Set<?> s) {
1340    int hashCode = 0;
1341    for (Object o : s) {
1342      hashCode += o != null ? o.hashCode() : 0;
1343
1344      hashCode = ~~hashCode;
1345      // Needed to deal with unusual integer overflow in GWT.
1346    }
1347    return hashCode;
1348  }
1349
1350  /**
1351   * An implementation for {@link Set#equals(Object)}.
1352   */
1353  static boolean equalsImpl(Set<?> s, @Nullable Object object) {
1354    if (s == object) {
1355      return true;
1356    }
1357    if (object instanceof Set) {
1358      Set<?> o = (Set<?>) object;
1359
1360      try {
1361        return s.size() == o.size() && s.containsAll(o);
1362      } catch (NullPointerException ignored) {
1363        return false;
1364      } catch (ClassCastException ignored) {
1365        return false;
1366      }
1367    }
1368    return false;
1369  }
1370
1371  /**
1372   * Returns an unmodifiable view of the specified navigable set. This method
1373   * allows modules to provide users with "read-only" access to internal
1374   * navigable sets. Query operations on the returned set "read through" to the
1375   * specified set, and attempts to modify the returned set, whether direct or
1376   * via its collection views, result in an
1377   * {@code UnsupportedOperationException}.
1378   *
1379   * <p>The returned navigable set will be serializable if the specified
1380   * navigable set is serializable.
1381   *
1382   * @param set the navigable set for which an unmodifiable view is to be
1383   *        returned
1384   * @return an unmodifiable view of the specified navigable set
1385   * @since 12.0
1386   */
1387  @GwtIncompatible("NavigableSet")
1388  public static <E> NavigableSet<E> unmodifiableNavigableSet(
1389      NavigableSet<E> set) {
1390    if (set instanceof ImmutableSortedSet
1391        || set instanceof UnmodifiableNavigableSet) {
1392      return set;
1393    }
1394    return new UnmodifiableNavigableSet<E>(set);
1395  }
1396
1397  @GwtIncompatible("NavigableSet")
1398  static final class UnmodifiableNavigableSet<E>
1399      extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable {
1400    private final NavigableSet<E> delegate;
1401
1402    UnmodifiableNavigableSet(NavigableSet<E> delegate) {
1403      this.delegate = checkNotNull(delegate);
1404    }
1405
1406    @Override
1407    protected SortedSet<E> delegate() {
1408      return Collections.unmodifiableSortedSet(delegate);
1409    }
1410
1411    @Override
1412    public E lower(E e) {
1413      return delegate.lower(e);
1414    }
1415
1416    @Override
1417    public E floor(E e) {
1418      return delegate.floor(e);
1419    }
1420
1421    @Override
1422    public E ceiling(E e) {
1423      return delegate.ceiling(e);
1424    }
1425
1426    @Override
1427    public E higher(E e) {
1428      return delegate.higher(e);
1429    }
1430
1431    @Override
1432    public E pollFirst() {
1433      throw new UnsupportedOperationException();
1434    }
1435
1436    @Override
1437    public E pollLast() {
1438      throw new UnsupportedOperationException();
1439    }
1440
1441    private transient UnmodifiableNavigableSet<E> descendingSet;
1442
1443    @Override
1444    public NavigableSet<E> descendingSet() {
1445      UnmodifiableNavigableSet<E> result = descendingSet;
1446      if (result == null) {
1447        result = descendingSet = new UnmodifiableNavigableSet<E>(
1448            delegate.descendingSet());
1449        result.descendingSet = this;
1450      }
1451      return result;
1452    }
1453
1454    @Override
1455    public Iterator<E> descendingIterator() {
1456      return Iterators.unmodifiableIterator(delegate.descendingIterator());
1457    }
1458
1459    @Override
1460    public NavigableSet<E> subSet(
1461        E fromElement,
1462        boolean fromInclusive,
1463        E toElement,
1464        boolean toInclusive) {
1465      return unmodifiableNavigableSet(delegate.subSet(
1466          fromElement,
1467          fromInclusive,
1468          toElement,
1469          toInclusive));
1470    }
1471
1472    @Override
1473    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1474      return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
1475    }
1476
1477    @Override
1478    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1479      return unmodifiableNavigableSet(
1480          delegate.tailSet(fromElement, inclusive));
1481    }
1482
1483    private static final long serialVersionUID = 0;
1484  }
1485
1486  /**
1487   * Returns a synchronized (thread-safe) navigable set backed by the specified
1488   * navigable set.  In order to guarantee serial access, it is critical that
1489   * <b>all</b> access to the backing navigable set is accomplished
1490   * through the returned navigable set (or its views).
1491   *
1492   * <p>It is imperative that the user manually synchronize on the returned
1493   * sorted set when iterating over it or any of its {@code descendingSet},
1494   * {@code subSet}, {@code headSet}, or {@code tailSet} views. <pre>   {@code
1495   *
1496   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1497   *    ...
1498   *   synchronized (set) {
1499   *     // Must be in the synchronized block
1500   *     Iterator<E> it = set.iterator();
1501   *     while (it.hasNext()) {
1502   *       foo(it.next());
1503   *     }
1504   *   }}</pre>
1505   *
1506   * <p>or: <pre>   {@code
1507   *
1508   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1509   *   NavigableSet<E> set2 = set.descendingSet().headSet(foo);
1510   *    ...
1511   *   synchronized (set) { // Note: set, not set2!!!
1512   *     // Must be in the synchronized block
1513   *     Iterator<E> it = set2.descendingIterator();
1514   *     while (it.hasNext())
1515   *       foo(it.next());
1516   *     }
1517   *   }}</pre>
1518   *
1519   * <p>Failure to follow this advice may result in non-deterministic behavior.
1520   *
1521   * <p>The returned navigable set will be serializable if the specified
1522   * navigable set is serializable.
1523   *
1524   * @param navigableSet the navigable set to be "wrapped" in a synchronized
1525   *    navigable set.
1526   * @return a synchronized view of the specified navigable set.
1527   * @since 13.0
1528   */
1529  @GwtIncompatible("NavigableSet")
1530  public static <E> NavigableSet<E> synchronizedNavigableSet(
1531      NavigableSet<E> navigableSet) {
1532    return Synchronized.navigableSet(navigableSet);
1533  }
1534
1535  /**
1536   * Remove each element in an iterable from a set.
1537   */
1538  static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
1539    boolean changed = false;
1540    while (iterator.hasNext()) {
1541      changed |= set.remove(iterator.next());
1542    }
1543    return changed;
1544  }
1545
1546  static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
1547    checkNotNull(collection); // for GWT
1548    if (collection instanceof Multiset) {
1549      collection = ((Multiset<?>) collection).elementSet();
1550    }
1551    /*
1552     * AbstractSet.removeAll(List) has quadratic behavior if the list size
1553     * is just less than the set's size.  We augment the test by
1554     * assuming that sets have fast contains() performance, and other
1555     * collections don't.  See
1556     * http://code.google.com/p/guava-libraries/issues/detail?id=1013
1557     */
1558    if (collection instanceof Set && collection.size() > set.size()) {
1559      return Iterators.removeAll(set.iterator(), collection);
1560    } else {
1561      return removeAllImpl(set, collection.iterator());
1562    }
1563  }
1564
1565  @GwtIncompatible("NavigableSet")
1566  static class DescendingSet<E> extends ForwardingNavigableSet<E> {
1567    private final NavigableSet<E> forward;
1568
1569    DescendingSet(NavigableSet<E> forward) {
1570      this.forward = forward;
1571    }
1572
1573    @Override
1574    protected NavigableSet<E> delegate() {
1575      return forward;
1576    }
1577
1578    @Override
1579    public E lower(E e) {
1580      return forward.higher(e);
1581    }
1582
1583    @Override
1584    public E floor(E e) {
1585      return forward.ceiling(e);
1586    }
1587
1588    @Override
1589    public E ceiling(E e) {
1590      return forward.floor(e);
1591    }
1592
1593    @Override
1594    public E higher(E e) {
1595      return forward.lower(e);
1596    }
1597
1598    @Override
1599    public E pollFirst() {
1600      return forward.pollLast();
1601    }
1602
1603    @Override
1604    public E pollLast() {
1605      return forward.pollFirst();
1606    }
1607
1608    @Override
1609    public NavigableSet<E> descendingSet() {
1610      return forward;
1611    }
1612
1613    @Override
1614    public Iterator<E> descendingIterator() {
1615      return forward.iterator();
1616    }
1617
1618    @Override
1619    public NavigableSet<E> subSet(
1620        E fromElement,
1621        boolean fromInclusive,
1622        E toElement,
1623        boolean toInclusive) {
1624      return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
1625    }
1626
1627    @Override
1628    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1629      return forward.tailSet(toElement, inclusive).descendingSet();
1630    }
1631
1632    @Override
1633    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1634      return forward.headSet(fromElement, inclusive).descendingSet();
1635    }
1636
1637    @SuppressWarnings("unchecked")
1638    @Override
1639    public Comparator<? super E> comparator() {
1640      Comparator<? super E> forwardComparator = forward.comparator();
1641      if (forwardComparator == null) {
1642        return (Comparator) Ordering.natural().reverse();
1643      } else {
1644        return reverse(forwardComparator);
1645      }
1646    }
1647
1648    // If we inline this, we get a javac error.
1649    private static <T> Ordering<T> reverse(Comparator<T> forward) {
1650      return Ordering.from(forward).reverse();
1651    }
1652
1653    @Override
1654    public E first() {
1655      return forward.last();
1656    }
1657
1658    @Override
1659    public SortedSet<E> headSet(E toElement) {
1660      return standardHeadSet(toElement);
1661    }
1662
1663    @Override
1664    public E last() {
1665      return forward.first();
1666    }
1667
1668    @Override
1669    public SortedSet<E> subSet(E fromElement, E toElement) {
1670      return standardSubSet(fromElement, toElement);
1671    }
1672
1673    @Override
1674    public SortedSet<E> tailSet(E fromElement) {
1675      return standardTailSet(fromElement);
1676    }
1677
1678    @Override
1679    public Iterator<E> iterator() {
1680      return forward.descendingIterator();
1681    }
1682
1683    @Override
1684    public Object[] toArray() {
1685      return standardToArray();
1686    }
1687
1688    @Override
1689    public <T> T[] toArray(T[] array) {
1690      return standardToArray(array);
1691    }
1692
1693    @Override
1694    public String toString() {
1695      return standardToString();
1696    }
1697  }
1698}