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