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    
017    package com.google.common.collect;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    
022    import com.google.common.annotations.GwtCompatible;
023    import com.google.common.annotations.GwtIncompatible;
024    import com.google.common.base.Predicate;
025    import com.google.common.base.Predicates;
026    import com.google.common.collect.Collections2.FilteredCollection;
027    import com.google.common.math.IntMath;
028    
029    import java.io.IOException;
030    import java.io.ObjectInputStream;
031    import java.io.Serializable;
032    import java.util.AbstractSet;
033    import java.util.Arrays;
034    import java.util.Collection;
035    import java.util.Collections;
036    import java.util.Comparator;
037    import java.util.EnumSet;
038    import java.util.HashSet;
039    import java.util.Iterator;
040    import java.util.LinkedHashSet;
041    import java.util.List;
042    import java.util.Map;
043    import java.util.NoSuchElementException;
044    import java.util.Set;
045    import java.util.SortedSet;
046    import java.util.TreeSet;
047    import java.util.concurrent.CopyOnWriteArraySet;
048    
049    import javax.annotation.Nullable;
050    
051    /**
052     * Static utility methods pertaining to {@link Set} instances. Also see this
053     * class's counterparts {@link Lists} and {@link Maps}.
054     *
055     * <p>See the Guava User Guide article on <a href=
056     * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets">
057     * {@code Sets}</a>.
058     *
059     * @author Kevin Bourrillion
060     * @author Jared Levy
061     * @author Chris Povirk
062     * @since 2.0 (imported from Google Collections Library)
063     */
064    @GwtCompatible(emulated = true)
065    public final class Sets {
066      private Sets() {}
067    
068      /**
069       * {@link AbstractSet} substitute without the potentially-quadratic
070       * {@code removeAll} implementation.
071       */
072      abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
073        @Override
074        public boolean removeAll(Collection<?> c) {
075          return removeAllImpl(this, c);
076        }
077    
078        @Override
079        public boolean retainAll(Collection<?> c) {
080          return super.retainAll(checkNotNull(c)); // GWT compatibility
081        }
082      }
083    
084      /**
085       * Returns an immutable set instance containing the given enum elements.
086       * Internally, the returned set will be backed by an {@link EnumSet}.
087       *
088       * <p>The iteration order of the returned set follows the enum's iteration
089       * order, not the order in which the elements are provided to the method.
090       *
091       * @param anElement one of the elements the set should contain
092       * @param otherElements the rest of the elements the set should contain
093       * @return an immutable set containing those elements, minus duplicates
094       */
095      // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
096      @GwtCompatible(serializable = true)
097      public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
098          E anElement, E... otherElements) {
099        return new ImmutableEnumSet<E>(EnumSet.of(anElement, otherElements));
100      }
101    
102      /**
103       * Returns an immutable set instance containing the given enum elements.
104       * Internally, the returned set will be backed by an {@link EnumSet}.
105       *
106       * <p>The iteration order of the returned set follows the enum's iteration
107       * order, not the order in which the elements appear in the given collection.
108       *
109       * @param elements the elements, all of the same {@code enum} type, that the
110       *     set should contain
111       * @return an immutable set containing those elements, minus duplicates
112       */
113      // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
114      @GwtCompatible(serializable = true)
115      public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
116          Iterable<E> elements) {
117        Iterator<E> iterator = elements.iterator();
118        if (!iterator.hasNext()) {
119          return ImmutableSet.of();
120        }
121        if (elements instanceof EnumSet) {
122          EnumSet<E> enumSetClone = EnumSet.copyOf((EnumSet<E>) elements);
123          return new ImmutableEnumSet<E>(enumSetClone);
124        }
125        E first = iterator.next();
126        EnumSet<E> set = EnumSet.of(first);
127        while (iterator.hasNext()) {
128          set.add(iterator.next());
129        }
130        return new ImmutableEnumSet<E>(set);
131      }
132    
133      /**
134       * Returns a new {@code EnumSet} instance containing the given elements.
135       * Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an
136       * exception on an empty collection, and it may be called on any iterable, not
137       * just a {@code Collection}.
138       */
139      public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable,
140          Class<E> elementType) {
141        /*
142         * TODO(cpovirk): noneOf() and addAll() will both throw
143         * NullPointerExceptions when appropriate. However, NullPointerTester will
144         * fail on this method because it passes in Class.class instead of an enum
145         * type. This means that, when iterable is null but elementType is not,
146         * noneOf() will throw a ClassCastException before addAll() has a chance to
147         * throw a NullPointerException. NullPointerTester considers this a failure.
148         * Ideally the test would be fixed, but it would require a special case for
149         * Class<E> where E extends Enum. Until that happens (if ever), leave
150         * checkNotNull() here. For now, contemplate the irony that checking
151         * elementType, the problem argument, is harmful, while checking iterable,
152         * the innocent bystander, is effective.
153         */
154        checkNotNull(iterable);
155        EnumSet<E> set = EnumSet.noneOf(elementType);
156        Iterables.addAll(set, iterable);
157        return set;
158      }
159    
160      // HashSet
161    
162      /**
163       * Creates a <i>mutable</i>, empty {@code HashSet} instance.
164       *
165       * <p><b>Note:</b> if mutability is not required, use {@link
166       * ImmutableSet#of()} instead.
167       *
168       * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
169       * EnumSet#noneOf} instead.
170       *
171       * @return a new, empty {@code HashSet}
172       */
173      public static <E> HashSet<E> newHashSet() {
174        return new HashSet<E>();
175      }
176    
177      /**
178       * Creates a <i>mutable</i> {@code HashSet} instance containing the given
179       * elements in unspecified order.
180       *
181       * <p><b>Note:</b> if mutability is not required and the elements are
182       * non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or
183       * {@link ImmutableSet#copyOf(Object[])} (for an array) instead.
184       *
185       * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
186       * EnumSet#of(Enum, Enum[])} instead.
187       *
188       * @param elements the elements that the set should contain
189       * @return a new {@code HashSet} containing those elements (minus duplicates)
190       */
191      public static <E> HashSet<E> newHashSet(E... elements) {
192        HashSet<E> set = newHashSetWithExpectedSize(elements.length);
193        Collections.addAll(set, elements);
194        return set;
195      }
196    
197      /**
198       * Creates a {@code HashSet} instance, with a high enough "initial capacity"
199       * that it <i>should</i> hold {@code expectedSize} elements without growth.
200       * This behavior cannot be broadly guaranteed, but it is observed to be true
201       * for OpenJDK 1.6. It also can't be guaranteed that the method isn't
202       * inadvertently <i>oversizing</i> the returned set.
203       *
204       * @param expectedSize the number of elements you expect to add to the
205       *        returned set
206       * @return a new, empty {@code HashSet} with enough capacity to hold {@code
207       *         expectedSize} elements without resizing
208       * @throws IllegalArgumentException if {@code expectedSize} is negative
209       */
210      public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
211        return new HashSet<E>(Maps.capacity(expectedSize));
212      }
213    
214      /**
215       * Creates a <i>mutable</i> {@code HashSet} instance containing the given
216       * elements in unspecified order.
217       *
218       * <p><b>Note:</b> if mutability is not required and the elements are
219       * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
220       *
221       * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use
222       * {@link #newEnumSet(Iterable, Class)} instead.
223       *
224       * @param elements the elements that the set should contain
225       * @return a new {@code HashSet} containing those elements (minus duplicates)
226       */
227      public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
228        return (elements instanceof Collection)
229            ? new HashSet<E>(Collections2.cast(elements))
230            : newHashSet(elements.iterator());
231      }
232    
233      /**
234       * Creates a <i>mutable</i> {@code HashSet} instance containing the given
235       * elements in unspecified order.
236       *
237       * <p><b>Note:</b> if mutability is not required and the elements are
238       * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
239       *
240       * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an
241       * {@link EnumSet} instead.
242       *
243       * @param elements the elements that the set should contain
244       * @return a new {@code HashSet} containing those elements (minus duplicates)
245       */
246      public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
247        HashSet<E> set = newHashSet();
248        while (elements.hasNext()) {
249          set.add(elements.next());
250        }
251        return set;
252      }
253    
254      // LinkedHashSet
255    
256      /**
257       * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
258       *
259       * <p><b>Note:</b> if mutability is not required, use {@link
260       * ImmutableSet#of()} instead.
261       *
262       * @return a new, empty {@code LinkedHashSet}
263       */
264      public static <E> LinkedHashSet<E> newLinkedHashSet() {
265        return new LinkedHashSet<E>();
266      }
267    
268      /**
269       * Creates a {@code LinkedHashSet} instance, with a high enough "initial
270       * capacity" that it <i>should</i> hold {@code expectedSize} elements without
271       * growth. This behavior cannot be broadly guaranteed, but it is observed to
272       * be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't
273       * inadvertently <i>oversizing</i> the returned set.
274       *
275       * @param expectedSize the number of elements you expect to add to the
276       *        returned set
277       * @return a new, empty {@code LinkedHashSet} with enough capacity to hold
278       *         {@code expectedSize} elements without resizing
279       * @throws IllegalArgumentException if {@code expectedSize} is negative
280       * @since 11.0
281       */
282      public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
283          int expectedSize) {
284        return new LinkedHashSet<E>(Maps.capacity(expectedSize));
285      }
286    
287      /**
288       * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the
289       * given elements in order.
290       *
291       * <p><b>Note:</b> if mutability is not required and the elements are
292       * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
293       *
294       * @param elements the elements that the set should contain, in order
295       * @return a new {@code LinkedHashSet} containing those elements (minus
296       *     duplicates)
297       */
298      public static <E> LinkedHashSet<E> newLinkedHashSet(
299          Iterable<? extends E> elements) {
300        if (elements instanceof Collection) {
301          return new LinkedHashSet<E>(Collections2.cast(elements));
302        }
303        LinkedHashSet<E> set = newLinkedHashSet();
304        for (E element : elements) {
305          set.add(element);
306        }
307        return set;
308      }
309    
310      // TreeSet
311    
312      /**
313       * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the
314       * natural sort ordering of its elements.
315       *
316       * <p><b>Note:</b> if mutability is not required, use {@link
317       * ImmutableSortedSet#of()} instead.
318       *
319       * @return a new, empty {@code TreeSet}
320       */
321      public static <E extends Comparable> TreeSet<E> newTreeSet() {
322        return new TreeSet<E>();
323      }
324    
325      /**
326       * Creates a <i>mutable</i> {@code TreeSet} instance containing the given
327       * elements sorted by their natural ordering.
328       *
329       * <p><b>Note:</b> if mutability is not required, use {@link
330       * ImmutableSortedSet#copyOf(Iterable)} instead.
331       *
332       * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit
333       * comparator, this method has different behavior than
334       * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with
335       * that comparator.
336       *
337       * @param elements the elements that the set should contain
338       * @return a new {@code TreeSet} containing those elements (minus duplicates)
339       */
340      public static <E extends Comparable> TreeSet<E> newTreeSet(
341          Iterable<? extends E> elements) {
342        TreeSet<E> set = newTreeSet();
343        for (E element : elements) {
344          set.add(element);
345        }
346        return set;
347      }
348    
349      /**
350       * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given
351       * comparator.
352       *
353       * <p><b>Note:</b> if mutability is not required, use {@code
354       * ImmutableSortedSet.orderedBy(comparator).build()} instead.
355       *
356       * @param comparator the comparator to use to sort the set
357       * @return a new, empty {@code TreeSet}
358       * @throws NullPointerException if {@code comparator} is null
359       */
360      public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
361        return new TreeSet<E>(checkNotNull(comparator));
362      }
363    
364      /**
365       * Creates an empty {@code Set} that uses identity to determine equality. It
366       * compares object references, instead of calling {@code equals}, to
367       * determine whether a provided object matches an element in the set. For
368       * example, {@code contains} returns {@code false} when passed an object that
369       * equals a set member, but isn't the same instance. This behavior is similar
370       * to the way {@code IdentityHashMap} handles key lookups.
371       *
372       * @since 8.0
373       */
374      public static <E> Set<E> newIdentityHashSet() {
375        return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
376      }
377    
378      /**
379       * Creates an empty {@code CopyOnWriteArraySet} instance.
380       *
381       * <p><b>Note:</b> if you need an immutable empty {@link Set}, use
382       * {@link Collections#emptySet} instead.
383       *
384       * @return a new, empty {@code CopyOnWriteArraySet}
385       * @since 12.0
386       */
387      @GwtIncompatible("CopyOnWriteArraySet")
388      public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
389        return new CopyOnWriteArraySet<E>();
390      }
391    
392      /**
393       * Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
394       *
395       * @param elements the elements that the set should contain, in order
396       * @return a new {@code CopyOnWriteArraySet} containing those elements
397       * @since 12.0
398       */
399      @GwtIncompatible("CopyOnWriteArraySet")
400      public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
401          Iterable<? extends E> elements) {
402        // We copy elements to an ArrayList first, rather than incurring the
403        // quadratic cost of adding them to the COWAS directly.
404        Collection<? extends E> elementsCollection = (elements instanceof Collection)
405            ? Collections2.cast(elements)
406            : Lists.newArrayList(elements);
407        return new CopyOnWriteArraySet<E>(elementsCollection);
408      }
409    
410      /**
411       * Creates an {@code EnumSet} consisting of all enum values that are not in
412       * the specified collection. If the collection is an {@link EnumSet}, this
413       * method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
414       * the specified collection must contain at least one element, in order to
415       * determine the element type. If the collection could be empty, use
416       * {@link #complementOf(Collection, Class)} instead of this method.
417       *
418       * @param collection the collection whose complement should be stored in the
419       *     enum set
420       * @return a new, modifiable {@code EnumSet} containing all values of the enum
421       *     that aren't present in the given collection
422       * @throws IllegalArgumentException if {@code collection} is not an
423       *     {@code EnumSet} instance and contains no elements
424       */
425      public static <E extends Enum<E>> EnumSet<E> complementOf(
426          Collection<E> collection) {
427        if (collection instanceof EnumSet) {
428          return EnumSet.complementOf((EnumSet<E>) collection);
429        }
430        checkArgument(!collection.isEmpty(),
431            "collection is empty; use the other version of this method");
432        Class<E> type = collection.iterator().next().getDeclaringClass();
433        return makeComplementByHand(collection, type);
434      }
435    
436      /**
437       * Creates an {@code EnumSet} consisting of all enum values that are not in
438       * the specified collection. This is equivalent to
439       * {@link EnumSet#complementOf}, but can act on any input collection, as long
440       * as the elements are of enum type.
441       *
442       * @param collection the collection whose complement should be stored in the
443       *     {@code EnumSet}
444       * @param type the type of the elements in the set
445       * @return a new, modifiable {@code EnumSet} initially containing all the
446       *     values of the enum not present in the given collection
447       */
448      public static <E extends Enum<E>> EnumSet<E> complementOf(
449          Collection<E> collection, Class<E> type) {
450        checkNotNull(collection);
451        return (collection instanceof EnumSet)
452            ? EnumSet.complementOf((EnumSet<E>) collection)
453            : makeComplementByHand(collection, type);
454      }
455    
456      private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
457          Collection<E> collection, Class<E> type) {
458        EnumSet<E> result = EnumSet.allOf(type);
459        result.removeAll(collection);
460        return result;
461      }
462    
463      /*
464       * Regarding newSetForMap() and SetFromMap:
465       *
466       * Written by Doug Lea with assistance from members of JCP JSR-166
467       * Expert Group and released to the public domain, as explained at
468       * http://creativecommons.org/licenses/publicdomain
469       */
470    
471      /**
472       * Returns a set backed by the specified map. The resulting set displays
473       * the same ordering, concurrency, and performance characteristics as the
474       * backing map. In essence, this factory method provides a {@link Set}
475       * implementation corresponding to any {@link Map} implementation. There is no
476       * need to use this method on a {@link Map} implementation that already has a
477       * corresponding {@link Set} implementation (such as {@link java.util.HashMap}
478       * or {@link java.util.TreeMap}).
479       *
480       * <p>Each method invocation on the set returned by this method results in
481       * exactly one method invocation on the backing map or its {@code keySet}
482       * view, with one exception. The {@code addAll} method is implemented as a
483       * sequence of {@code put} invocations on the backing map.
484       *
485       * <p>The specified map must be empty at the time this method is invoked,
486       * and should not be accessed directly after this method returns. These
487       * conditions are ensured if the map is created empty, passed directly
488       * to this method, and no reference to the map is retained, as illustrated
489       * in the following code fragment: <pre>  {@code
490       *
491       *   Set<Object> identityHashSet = Sets.newSetFromMap(
492       *       new IdentityHashMap<Object, Boolean>());}</pre>
493       *
494       * This method has the same behavior as the JDK 6 method
495       * {@code Collections.newSetFromMap()}. The returned set is serializable if
496       * the backing map is.
497       *
498       * @param map the backing map
499       * @return the set backed by the map
500       * @throws IllegalArgumentException if {@code map} is not empty
501       */
502      public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
503        return new SetFromMap<E>(map);
504      }
505    
506      private static class SetFromMap<E> extends AbstractSet<E>
507          implements Set<E>, Serializable {
508        private final Map<E, Boolean> m; // The backing map
509        private transient Set<E> s; // Its keySet
510    
511        SetFromMap(Map<E, Boolean> map) {
512          checkArgument(map.isEmpty(), "Map is non-empty");
513          m = map;
514          s = map.keySet();
515        }
516    
517        @Override
518        public void clear() {
519          m.clear();
520        }
521        @Override
522        public int size() {
523          return m.size();
524        }
525        @Override
526        public boolean isEmpty() {
527          return m.isEmpty();
528        }
529        @Override
530        public boolean contains(Object o) {
531          return m.containsKey(o);
532        }
533        @Override
534        public boolean remove(Object o) {
535          return m.remove(o) != null;
536        }
537        @Override
538        public boolean add(E e) {
539          return m.put(e, Boolean.TRUE) == null;
540        }
541        @Override
542        public Iterator<E> iterator() {
543          return s.iterator();
544        }
545        @Override
546        public Object[] toArray() {
547          return s.toArray();
548        }
549        @Override
550        public <T> T[] toArray(T[] a) {
551          return s.toArray(a);
552        }
553        @Override
554        public String toString() {
555          return s.toString();
556        }
557        @Override
558        public int hashCode() {
559          return s.hashCode();
560        }
561        @Override
562        public boolean equals(@Nullable Object object) {
563          return this == object || this.s.equals(object);
564        }
565        @Override
566        public boolean containsAll(Collection<?> c) {
567          return s.containsAll(c);
568        }
569        @Override
570        public boolean removeAll(Collection<?> c) {
571          return s.removeAll(c);
572        }
573        @Override
574        public boolean retainAll(Collection<?> c) {
575          return s.retainAll(c);
576        }
577    
578        // addAll is the only inherited implementation
579        @GwtIncompatible("not needed in emulated source")
580        private static final long serialVersionUID = 0;
581    
582        @GwtIncompatible("java.io.ObjectInputStream")
583        private void readObject(ObjectInputStream stream)
584            throws IOException, ClassNotFoundException {
585          stream.defaultReadObject();
586          s = m.keySet();
587        }
588      }
589    
590      /**
591       * An unmodifiable view of a set which may be backed by other sets; this view
592       * will change as the backing sets do. Contains methods to copy the data into
593       * a new set which will then remain stable. There is usually no reason to
594       * retain a reference of type {@code SetView}; typically, you either use it
595       * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
596       * {@link #copyInto} and forget the {@code SetView} itself.
597       *
598       * @since 2.0 (imported from Google Collections Library)
599       */
600      public abstract static class SetView<E> extends AbstractSet<E> {
601        private SetView() {} // no subclasses but our own
602    
603        /**
604         * Returns an immutable copy of the current contents of this set view.
605         * Does not support null elements.
606         *
607         * <p><b>Warning:</b> this may have unexpected results if a backing set of
608         * this view uses a nonstandard notion of equivalence, for example if it is
609         * a {@link TreeSet} using a comparator that is inconsistent with {@link
610         * Object#equals(Object)}.
611         */
612        public ImmutableSet<E> immutableCopy() {
613          return ImmutableSet.copyOf(this);
614        }
615    
616        /**
617         * Copies the current contents of this set view into an existing set. This
618         * method has equivalent behavior to {@code set.addAll(this)}, assuming that
619         * all the sets involved are based on the same notion of equivalence.
620         *
621         * @return a reference to {@code set}, for convenience
622         */
623        // Note: S should logically extend Set<? super E> but can't due to either
624        // some javac bug or some weirdness in the spec, not sure which.
625        public <S extends Set<E>> S copyInto(S set) {
626          set.addAll(this);
627          return set;
628        }
629      }
630    
631      /**
632       * Returns an unmodifiable <b>view</b> of the union of two sets. The returned
633       * set contains all elements that are contained in either backing set.
634       * Iterating over the returned set iterates first over all the elements of
635       * {@code set1}, then over each element of {@code set2}, in order, that is not
636       * contained in {@code set1}.
637       *
638       * <p>Results are undefined if {@code set1} and {@code set2} are sets based on
639       * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
640       * the {@link Map#keySet} of an {@code IdentityHashMap} all are).
641       *
642       * <p><b>Note:</b> The returned view performs better when {@code set1} is the
643       * smaller of the two sets. If you have reason to believe one of your sets
644       * will generally be smaller than the other, pass it first.
645       *
646       * <p>Further, note that the current implementation is not suitable for nested
647       * {@code union} views, i.e. the following should be avoided when in a loop:
648       * {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
649       * set has a cubic complexity to the depth of the nesting.
650       */
651      public static <E> SetView<E> union(
652          final Set<? extends E> set1, final Set<? extends E> set2) {
653        checkNotNull(set1, "set1");
654        checkNotNull(set2, "set2");
655    
656        final Set<? extends E> set2minus1 = difference(set2, set1);
657    
658        return new SetView<E>() {
659          @Override
660          public int size() {
661            return set1.size() + set2minus1.size();
662          }
663          @Override
664          public boolean isEmpty() {
665            return set1.isEmpty() && set2.isEmpty();
666          }
667          @Override
668          public Iterator<E> iterator() {
669            return Iterators.unmodifiableIterator(
670                Iterators.concat(set1.iterator(), set2minus1.iterator()));
671          }
672          @Override
673          public boolean contains(Object object) {
674            return set1.contains(object) || set2.contains(object);
675          }
676          @Override
677          public <S extends Set<E>> S copyInto(S set) {
678            set.addAll(set1);
679            set.addAll(set2);
680            return set;
681          }
682          @Override
683          public ImmutableSet<E> immutableCopy() {
684            return new ImmutableSet.Builder<E>()
685                .addAll(set1).addAll(set2).build();
686          }
687        };
688      }
689    
690      /**
691       * Returns an unmodifiable <b>view</b> of the intersection of two sets. The
692       * returned set contains all elements that are contained by both backing sets.
693       * The iteration order of the returned set matches that of {@code set1}.
694       *
695       * <p>Results are undefined if {@code set1} and {@code set2} are sets based
696       * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
697       * and the keySet of an {@code IdentityHashMap} all are).
698       *
699       * <p><b>Note:</b> The returned view performs slightly better when {@code
700       * set1} is the smaller of the two sets. If you have reason to believe one of
701       * your sets will generally be smaller than the other, pass it first.
702       * Unfortunately, since this method sets the generic type of the returned set
703       * based on the type of the first set passed, this could in rare cases force
704       * you to make a cast, for example: <pre>   {@code
705       *
706       *   Set<Object> aFewBadObjects = ...
707       *   Set<String> manyBadStrings = ...
708       *
709       *   // impossible for a non-String to be in the intersection
710       *   SuppressWarnings("unchecked")
711       *   Set<String> badStrings = (Set) Sets.intersection(
712       *       aFewBadObjects, manyBadStrings);}</pre>
713       *
714       * This is unfortunate, but should come up only very rarely.
715       */
716      public static <E> SetView<E> intersection(
717          final Set<E> set1, final Set<?> set2) {
718        checkNotNull(set1, "set1");
719        checkNotNull(set2, "set2");
720    
721        final Predicate<Object> inSet2 = Predicates.in(set2);
722        return new SetView<E>() {
723          @Override
724          public Iterator<E> iterator() {
725            return Iterators.filter(set1.iterator(), inSet2);
726          }
727          @Override
728          public int size() {
729            return Iterators.size(iterator());
730          }
731          @Override
732          public boolean isEmpty() {
733            return !iterator().hasNext();
734          }
735          @Override
736          public boolean contains(Object object) {
737            return set1.contains(object) && set2.contains(object);
738          }
739          @Override
740          public boolean containsAll(Collection<?> collection) {
741            return set1.containsAll(collection)
742                && set2.containsAll(collection);
743          }
744        };
745      }
746    
747      /**
748       * Returns an unmodifiable <b>view</b> of the difference of two sets. The
749       * returned set contains all elements that are contained by {@code set1} and
750       * not contained by {@code set2}. {@code set2} may also contain elements not
751       * present in {@code set1}; these are simply ignored. The iteration order of
752       * the returned set matches that of {@code set1}.
753       *
754       * <p>Results are undefined if {@code set1} and {@code set2} are sets based
755       * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
756       * and the keySet of an {@code IdentityHashMap} all are).
757       */
758      public static <E> SetView<E> difference(
759          final Set<E> set1, final Set<?> set2) {
760        checkNotNull(set1, "set1");
761        checkNotNull(set2, "set2");
762    
763        final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
764        return new SetView<E>() {
765          @Override
766          public Iterator<E> iterator() {
767            return Iterators.filter(set1.iterator(), notInSet2);
768          }
769          @Override
770          public int size() {
771            return Iterators.size(iterator());
772          }
773          @Override
774          public boolean isEmpty() {
775            return set2.containsAll(set1);
776          }
777          @Override
778          public boolean contains(Object element) {
779            return set1.contains(element) && !set2.contains(element);
780          }
781        };
782      }
783    
784      /**
785       * Returns an unmodifiable <b>view</b> of the symmetric difference of two
786       * sets. The returned set contains all elements that are contained in either
787       * {@code set1} or {@code set2} but not in both. The iteration order of the
788       * returned set is undefined.
789       *
790       * <p>Results are undefined if {@code set1} and {@code set2} are sets based
791       * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
792       * and the keySet of an {@code IdentityHashMap} all are).
793       *
794       * @since 3.0
795       */
796      public static <E> SetView<E> symmetricDifference(
797          Set<? extends E> set1, Set<? extends E> set2) {
798        checkNotNull(set1, "set1");
799        checkNotNull(set2, "set2");
800    
801        // TODO(kevinb): Replace this with a more efficient implementation
802        return difference(union(set1, set2), intersection(set1, set2));
803      }
804    
805      /**
806       * Returns the elements of {@code unfiltered} that satisfy a predicate. The
807       * returned set is a live view of {@code unfiltered}; changes to one affect
808       * the other.
809       *
810       * <p>The resulting set's iterator does not support {@code remove()}, but all
811       * other set methods are supported. When given an element that doesn't satisfy
812       * the predicate, the set's {@code add()} and {@code addAll()} methods throw
813       * an {@link IllegalArgumentException}. When methods such as {@code
814       * removeAll()} and {@code clear()} are called on the filtered set, only
815       * elements that satisfy the filter will be removed from the underlying set.
816       *
817       * <p>The returned set isn't threadsafe or serializable, even if
818       * {@code unfiltered} is.
819       *
820       * <p>Many of the filtered set's methods, such as {@code size()}, iterate
821       * across every element in the underlying set and determine which elements
822       * satisfy the filter. When a live view is <i>not</i> needed, it may be faster
823       * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
824       *
825       * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
826       * as documented at {@link Predicate#apply}. Do not provide a predicate such
827       * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
828       * with equals. (See {@link Iterables#filter(Iterable, Class)} for related
829       * functionality.)
830       */
831      // TODO(kevinb): how to omit that last sentence when building GWT javadoc?
832      public static <E> Set<E> filter(
833          Set<E> unfiltered, Predicate<? super E> predicate) {
834        if (unfiltered instanceof SortedSet) {
835          return filter((SortedSet<E>) unfiltered, predicate);
836        }
837        if (unfiltered instanceof FilteredSet) {
838          // Support clear(), removeAll(), and retainAll() when filtering a filtered
839          // collection.
840          FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
841          Predicate<E> combinedPredicate
842              = Predicates.<E>and(filtered.predicate, predicate);
843          return new FilteredSet<E>(
844              (Set<E>) filtered.unfiltered, combinedPredicate);
845        }
846    
847        return new FilteredSet<E>(
848            checkNotNull(unfiltered), checkNotNull(predicate));
849      }
850    
851      private static class FilteredSet<E> extends FilteredCollection<E>
852          implements Set<E> {
853        FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
854          super(unfiltered, predicate);
855        }
856    
857        @Override
858        public boolean equals(@Nullable Object object) {
859          return equalsImpl(this, object);
860        }
861    
862        @Override
863        public int hashCode() {
864          return hashCodeImpl(this);
865        }
866      }
867    
868      /**
869       * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
870       * satisfy a predicate. The returned set is a live view of {@code unfiltered};
871       * changes to one affect the other.
872       *
873       * <p>The resulting set's iterator does not support {@code remove()}, but all
874       * other set methods are supported. When given an element that doesn't satisfy
875       * the predicate, the set's {@code add()} and {@code addAll()} methods throw
876       * an {@link IllegalArgumentException}. When methods such as
877       * {@code removeAll()} and {@code clear()} are called on the filtered set,
878       * only elements that satisfy the filter will be removed from the underlying
879       * set.
880       *
881       * <p>The returned set isn't threadsafe or serializable, even if
882       * {@code unfiltered} is.
883       *
884       * <p>Many of the filtered set's methods, such as {@code size()}, iterate across
885       * every element in the underlying set and determine which elements satisfy
886       * the filter. When a live view is <i>not</i> needed, it may be faster to copy
887       * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
888       *
889       * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
890       * as documented at {@link Predicate#apply}. Do not provide a predicate such as
891       * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
892       * equals. (See {@link Iterables#filter(Iterable, Class)} for related
893       * functionality.)
894       *
895       * @since 11.0
896       */
897      @SuppressWarnings("unchecked")
898      public static <E> SortedSet<E> filter(
899          SortedSet<E> unfiltered, Predicate<? super E> predicate) {
900        if (unfiltered instanceof FilteredSet) {
901          // Support clear(), removeAll(), and retainAll() when filtering a filtered
902          // collection.
903          FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
904          Predicate<E> combinedPredicate
905              = Predicates.<E>and(filtered.predicate, predicate);
906          return new FilteredSortedSet<E>(
907              (SortedSet<E>) filtered.unfiltered, combinedPredicate);
908        }
909    
910        return new FilteredSortedSet<E>(
911            checkNotNull(unfiltered), checkNotNull(predicate));
912      }
913    
914      private static class FilteredSortedSet<E> extends FilteredCollection<E>
915          implements SortedSet<E> {
916    
917        FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
918          super(unfiltered, predicate);
919        }
920    
921        @Override
922        public boolean equals(@Nullable Object object) {
923          return equalsImpl(this, object);
924        }
925    
926        @Override
927        public int hashCode() {
928          return hashCodeImpl(this);
929        }
930    
931        public Comparator<? super E> comparator() {
932          return ((SortedSet<E>) unfiltered).comparator();
933        }
934    
935        public SortedSet<E> subSet(E fromElement, E toElement) {
936          return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement),
937              predicate);
938        }
939    
940        public SortedSet<E> headSet(E toElement) {
941          return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
942        }
943    
944        public SortedSet<E> tailSet(E fromElement) {
945          return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
946        }
947    
948        public E first() {
949          return iterator().next();
950        }
951    
952        public E last() {
953          SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
954          while (true) {
955            E element = sortedUnfiltered.last();
956            if (predicate.apply(element)) {
957              return element;
958            }
959            sortedUnfiltered = sortedUnfiltered.headSet(element);
960          }
961        }
962      }
963    
964      /**
965       * Returns every possible list that can be formed by choosing one element
966       * from each of the given sets in order; the "n-ary
967       * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
968       * product</a>" of the sets. For example: <pre>   {@code
969       *
970       *   Sets.cartesianProduct(ImmutableList.of(
971       *       ImmutableSet.of(1, 2),
972       *       ImmutableSet.of("A", "B", "C")))}</pre>
973       *
974       * returns a set containing six lists:
975       *
976       * <ul>
977       * <li>{@code ImmutableList.of(1, "A")}
978       * <li>{@code ImmutableList.of(1, "B")}
979       * <li>{@code ImmutableList.of(1, "C")}
980       * <li>{@code ImmutableList.of(2, "A")}
981       * <li>{@code ImmutableList.of(2, "B")}
982       * <li>{@code ImmutableList.of(2, "C")}
983       * </ul>
984       *
985       * The order in which these lists are returned is not guaranteed, however the
986       * position of an element inside a tuple always corresponds to the position of
987       * the set from which it came in the input list. Note that if any input set is
988       * empty, the Cartesian product will also be empty. If no sets at all are
989       * provided (an empty list), the resulting Cartesian product has one element,
990       * an empty list (counter-intuitive, but mathematically consistent).
991       *
992       * <p><i>Performance notes:</i> while the cartesian product of sets of size
993       * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
994       * consumption is much smaller. When the cartesian set is constructed, the
995       * input sets are merely copied. Only as the resulting set is iterated are the
996       * individual lists created, and these are not retained after iteration.
997       *
998       * @param sets the sets to choose elements from, in the order that
999       *     the elements chosen from those sets should appear in the resulting
1000       *     lists
1001       * @param <B> any common base class shared by all axes (often just {@link
1002       *     Object})
1003       * @return the Cartesian product, as an immutable set containing immutable
1004       *     lists
1005       * @throws NullPointerException if {@code sets}, any one of the {@code sets},
1006       *     or any element of a provided set is null
1007       * @since 2.0
1008       */
1009      public static <B> Set<List<B>> cartesianProduct(
1010          List<? extends Set<? extends B>> sets) {
1011        for (Set<? extends B> set : sets) {
1012          if (set.isEmpty()) {
1013            return ImmutableSet.of();
1014          }
1015        }
1016        CartesianSet<B> cartesianSet = new CartesianSet<B>(sets);
1017        return cartesianSet;
1018      }
1019    
1020      /**
1021       * Returns every possible list that can be formed by choosing one element
1022       * from each of the given sets in order; the "n-ary
1023       * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
1024       * product</a>" of the sets. For example: <pre>   {@code
1025       *
1026       *   Sets.cartesianProduct(
1027       *       ImmutableSet.of(1, 2),
1028       *       ImmutableSet.of("A", "B", "C"))}</pre>
1029       *
1030       * returns a set containing six lists:
1031       *
1032       * <ul>
1033       * <li>{@code ImmutableList.of(1, "A")}
1034       * <li>{@code ImmutableList.of(1, "B")}
1035       * <li>{@code ImmutableList.of(1, "C")}
1036       * <li>{@code ImmutableList.of(2, "A")}
1037       * <li>{@code ImmutableList.of(2, "B")}
1038       * <li>{@code ImmutableList.of(2, "C")}
1039       * </ul>
1040       *
1041       * The order in which these lists are returned is not guaranteed, however the
1042       * position of an element inside a tuple always corresponds to the position of
1043       * the set from which it came in the input list. Note that if any input set is
1044       * empty, the Cartesian product will also be empty. If no sets at all are
1045       * provided, the resulting Cartesian product has one element, an empty list
1046       * (counter-intuitive, but mathematically consistent).
1047       *
1048       * <p><i>Performance notes:</i> while the cartesian product of sets of size
1049       * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
1050       * consumption is much smaller. When the cartesian set is constructed, the
1051       * input sets are merely copied. Only as the resulting set is iterated are the
1052       * individual lists created, and these are not retained after iteration.
1053       *
1054       * @param sets the sets to choose elements from, in the order that
1055       *     the elements chosen from those sets should appear in the resulting
1056       *     lists
1057       * @param <B> any common base class shared by all axes (often just {@link
1058       *     Object})
1059       * @return the Cartesian product, as an immutable set containing immutable
1060       *     lists
1061       * @throws NullPointerException if {@code sets}, any one of the {@code sets},
1062       *     or any element of a provided set is null
1063       * @since 2.0
1064       */
1065      public static <B> Set<List<B>> cartesianProduct(
1066          Set<? extends B>... sets) {
1067        return cartesianProduct(Arrays.asList(sets));
1068      }
1069    
1070      private static class CartesianSet<B> extends AbstractSet<List<B>> {
1071        final ImmutableList<Axis> axes;
1072        final int size;
1073    
1074        CartesianSet(List<? extends Set<? extends B>> sets) {
1075          int dividend = 1;
1076          ImmutableList.Builder<Axis> builder = ImmutableList.builder();
1077          try {
1078            for (Set<? extends B> set : sets) {
1079              Axis axis = new Axis(set, dividend);
1080              builder.add(axis);
1081              dividend = IntMath.checkedMultiply(dividend, axis.size());
1082            }
1083          } catch (ArithmeticException overflow) {
1084            throw new IllegalArgumentException("cartesian product too big");
1085          }
1086          this.axes = builder.build();
1087          size = dividend;
1088        }
1089    
1090        @Override
1091        public int size() {
1092          return size;
1093        }
1094    
1095        @Override
1096        public UnmodifiableIterator<List<B>> iterator() {
1097          return new AbstractIndexedListIterator<List<B>>(size) {
1098            @Override
1099            protected List<B> get(int index) {
1100              Object[] tuple = new Object[axes.size()];
1101              for (int i = 0 ; i < tuple.length; i++) {
1102                tuple[i] = axes.get(i).getForIndex(index);
1103              }
1104    
1105              @SuppressWarnings("unchecked") // only B's are put in here
1106              List<B> result = (ImmutableList<B>) ImmutableList.copyOf(tuple);
1107              return result;
1108            }
1109          };
1110        }
1111    
1112        @Override public boolean contains(Object element) {
1113          if (!(element instanceof List)) {
1114            return false;
1115          }
1116          List<?> tuple = (List<?>) element;
1117          int dimensions = axes.size();
1118          if (tuple.size() != dimensions) {
1119            return false;
1120          }
1121          for (int i = 0; i < dimensions; i++) {
1122            if (!axes.get(i).contains(tuple.get(i))) {
1123              return false;
1124            }
1125          }
1126          return true;
1127        }
1128    
1129        @Override
1130        public boolean equals(@Nullable Object object) {
1131          // Warning: this is broken if size() == 0, so it is critical that we
1132          // substitute an empty ImmutableSet to the user in place of this
1133          if (object instanceof CartesianSet) {
1134            CartesianSet<?> that = (CartesianSet<?>) object;
1135            return this.axes.equals(that.axes);
1136          }
1137          return super.equals(object);
1138        }
1139    
1140        @Override
1141        public int hashCode() {
1142          // Warning: this is broken if size() == 0, so it is critical that we
1143          // substitute an empty ImmutableSet to the user in place of this
1144    
1145          // It's a weird formula, but tests prove it works.
1146          int adjust = size - 1;
1147          for (int i = 0; i < axes.size(); i++) {
1148            adjust *= 31;
1149          }
1150          return axes.hashCode() + adjust;
1151        }
1152    
1153        private class Axis {
1154          final ImmutableSet<? extends B> choices;
1155          final ImmutableList<? extends B> choicesList;
1156          final int dividend;
1157    
1158          Axis(Set<? extends B> set, int dividend) {
1159            choices = ImmutableSet.copyOf(set);
1160            choicesList = choices.asList();
1161            this.dividend = dividend;
1162          }
1163    
1164          int size() {
1165            return choices.size();
1166          }
1167    
1168          B getForIndex(int index) {
1169            return choicesList.get(index / dividend % size());
1170          }
1171    
1172          boolean contains(Object target) {
1173            return choices.contains(target);
1174          }
1175    
1176          @Override
1177          public boolean equals(Object obj) {
1178            if (obj instanceof CartesianSet.Axis) {
1179              CartesianSet.Axis that = (CartesianSet.Axis) obj;
1180              return this.choices.equals(that.choices);
1181              // dividends must be equal or we wouldn't have gotten this far
1182            }
1183            return false;
1184          }
1185    
1186          @Override
1187          public int hashCode() {
1188            // Because Axis instances are not exposed, we can
1189            // opportunistically choose whatever bizarre formula happens
1190            // to make CartesianSet.hashCode() as simple as possible.
1191            return size / choices.size() * choices.hashCode();
1192          }
1193        }
1194      }
1195    
1196      /**
1197       * Returns the set of all possible subsets of {@code set}. For example,
1198       * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
1199       * {1}, {2}, {1, 2}}}.
1200       *
1201       * <p>Elements appear in these subsets in the same iteration order as they
1202       * appeared in the input set. The order in which these subsets appear in the
1203       * outer set is undefined. Note that the power set of the empty set is not the
1204       * empty set, but a one-element set containing the empty set.
1205       *
1206       * <p>The returned set and its constituent sets use {@code equals} to decide
1207       * whether two elements are identical, even if the input set uses a different
1208       * concept of equivalence.
1209       *
1210       * <p><i>Performance notes:</i> while the power set of a set with size {@code
1211       * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
1212       * power set is constructed, the input set is merely copied. Only as the
1213       * power set is iterated are the individual subsets created, and these subsets
1214       * themselves occupy only a few bytes of memory regardless of their size.
1215       *
1216       * @param set the set of elements to construct a power set from
1217       * @return the power set, as an immutable set of immutable sets
1218       * @throws IllegalArgumentException if {@code set} has more than 30 unique
1219       *     elements (causing the power set size to exceed the {@code int} range)
1220       * @throws NullPointerException if {@code set} is or contains {@code null}
1221       * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
1222       *      Wikipedia</a>
1223       * @since 4.0
1224       */
1225      @GwtCompatible(serializable = false)
1226      public static <E> Set<Set<E>> powerSet(Set<E> set) {
1227        ImmutableSet<E> input = ImmutableSet.copyOf(set);
1228        checkArgument(input.size() <= 30,
1229            "Too many elements to create power set: %s > 30", input.size());
1230        return new PowerSet<E>(input);
1231      }
1232    
1233      private static final class PowerSet<E> extends AbstractSet<Set<E>> {
1234        final ImmutableSet<E> inputSet;
1235        final ImmutableList<E> inputList;
1236        final int powerSetSize;
1237    
1238        PowerSet(ImmutableSet<E> input) {
1239          this.inputSet = input;
1240          this.inputList = input.asList();
1241          this.powerSetSize = 1 << input.size();
1242        }
1243    
1244        @Override
1245        public int size() {
1246          return powerSetSize;
1247        }
1248    
1249        @Override
1250        public boolean isEmpty() {
1251          return false;
1252        }
1253    
1254        @Override
1255        public Iterator<Set<E>> iterator() {
1256          return new AbstractIndexedListIterator<Set<E>>(powerSetSize) {
1257            @Override
1258            protected Set<E> get(final int setBits) {
1259              return new AbstractSet<E>() {
1260                @Override
1261                public int size() {
1262                  return Integer.bitCount(setBits);
1263                }
1264                @Override
1265                public Iterator<E> iterator() {
1266                  return new BitFilteredSetIterator<E>(inputList, setBits);
1267                }
1268              };
1269            }
1270          };
1271        }
1272    
1273        private static final class BitFilteredSetIterator<E>
1274            extends UnmodifiableIterator<E> {
1275          final ImmutableList<E> input;
1276          int remainingSetBits;
1277    
1278          BitFilteredSetIterator(ImmutableList<E> input, int allSetBits) {
1279            this.input = input;
1280            this.remainingSetBits = allSetBits;
1281          }
1282    
1283          public boolean hasNext() {
1284            return remainingSetBits != 0;
1285          }
1286    
1287          public E next() {
1288            int index = Integer.numberOfTrailingZeros(remainingSetBits);
1289            if (index == 32) {
1290              throw new NoSuchElementException();
1291            }
1292    
1293            int currentElementMask = 1 << index;
1294            remainingSetBits &= ~currentElementMask;
1295            return input.get(index);
1296          }
1297        }
1298    
1299        @Override
1300        public boolean contains(@Nullable Object obj) {
1301          if (obj instanceof Set) {
1302            Set<?> set = (Set<?>) obj;
1303            return inputSet.containsAll(set);
1304          }
1305          return false;
1306        }
1307    
1308        @Override
1309        public boolean equals(@Nullable Object obj) {
1310          if (obj instanceof PowerSet) {
1311            PowerSet<?> that = (PowerSet<?>) obj;
1312            return inputSet.equals(that.inputSet);
1313          }
1314          return super.equals(obj);
1315        }
1316    
1317        @Override
1318        public int hashCode() {
1319          /*
1320           * The sum of the sums of the hash codes in each subset is just the sum of
1321           * each input element's hash code times the number of sets that element
1322           * appears in. Each element appears in exactly half of the 2^n sets, so:
1323           */
1324          return inputSet.hashCode() << (inputSet.size() - 1);
1325        }
1326    
1327        @Override
1328        public String toString() {
1329          return "powerSet(" + inputSet + ")";
1330        }
1331      }
1332    
1333      /**
1334       * An implementation for {@link Set#hashCode()}.
1335       */
1336      static int hashCodeImpl(Set<?> s) {
1337        int hashCode = 0;
1338        for (Object o : s) {
1339          hashCode += o != null ? o.hashCode() : 0;
1340        }
1341        return hashCode;
1342      }
1343    
1344      /**
1345       * An implementation for {@link Set#equals(Object)}.
1346       */
1347      static boolean equalsImpl(Set<?> s, @Nullable Object object){
1348        if (s == object) {
1349          return true;
1350        }
1351        if (object instanceof Set) {
1352          Set<?> o = (Set<?>) object;
1353    
1354          try {
1355            return s.size() == o.size() && s.containsAll(o);
1356          } catch (NullPointerException ignored) {
1357            return false;
1358          } catch (ClassCastException ignored) {
1359            return false;
1360          }
1361        }
1362        return false;
1363      }
1364    
1365      /**
1366       * Remove each element in an iterable from a set.
1367       */
1368      static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
1369        boolean changed = false;
1370        while (iterator.hasNext()) {
1371          changed |= set.remove(iterator.next());
1372        }
1373        return changed;
1374      }
1375    
1376      static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
1377        checkNotNull(collection); // for GWT
1378        if (collection instanceof Multiset) {
1379          collection = ((Multiset<?>) collection).elementSet();
1380        }
1381        /*
1382         * AbstractSet.removeAll(List) has quadratic behavior if the list size
1383         * is just less than the set's size.  We augment the test by
1384         * assuming that sets have fast contains() performance, and other
1385         * collections don't.  See
1386         * http://code.google.com/p/guava-libraries/issues/detail?id=1013
1387         */
1388        if (collection instanceof Set && collection.size() > set.size()) {
1389          Iterator<?> setIterator = set.iterator();
1390          boolean changed = false;
1391          while (setIterator.hasNext()) {
1392            if (collection.contains(setIterator.next())) {
1393              changed = true;
1394              setIterator.remove();
1395            }
1396          }
1397          return changed;
1398        } else {
1399          return removeAllImpl(set, collection.iterator());
1400        }
1401      }
1402    
1403      /**
1404       * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
1405       */
1406      static <T> SortedSet<T> cast(Iterable<T> iterable) {
1407        return (SortedSet<T>) iterable;
1408      }
1409    }