Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.Set;
 
 import  javax.annotation.Nullable;

A high-performance, immutable Set with reliable, user-specified iteration order. Does not permit null elements.

Unlike Collections.unmodifiableSet, which is a view of a separate collection that can still change, an instance of this class contains its own private data and will never change. This class is convenient for public static final sets ("constant sets") and also lets you easily make a "defensive copy" of a set provided to your class by a caller.

Warning: Like most sets, an ImmutableSet will not function correctly if an element is modified after being placed in the set. For this reason, and to avoid general confusion, it is strongly recommended to place only immutable objects into this collection.

This class has been observed to perform significantly better than HashSet for objects with very fast Object.hashCode implementations (as a well-behaved immutable object should). While this class's factory methods create hash-based instances, the ImmutableSortedSet subclass performs binary searches instead.

Note: Although this class is not final, it cannot be subclassed outside its package as it has no public or protected constructors. Thus, instances of this type are guaranteed to be immutable.

See the Guava User Guide article on immutable collections.

Author(s):
Kevin Bourrillion
Nick Kralevich
Since:
2.0 (imported from Google Collections Library)
See also:
ImmutableList
ImmutableMap
 
 @GwtCompatible(serializable = true, emulated = true)
 @SuppressWarnings("serial"// we're overriding default serialization
 public abstract class ImmutableSet<E> extends ImmutableCollection<E>
     implements Set<E> {
  
Returns the empty immutable set. This set behaves and performs comparably to Collections.emptySet, and is preferable mainly for consistency and maintainability of your code.
 
   // Casting to any type is safe because the set will never hold any elements.
   @SuppressWarnings({"unchecked"})
   public static <E> ImmutableSet<E> of() {
     return (ImmutableSet<E>) .;
   }

  
Returns an immutable set containing a single element. This set behaves and performs comparably to Collections.singleton, but will not accept a null element. It is preferable mainly for consistency and maintainability of your code.
 
   public static <E> ImmutableSet<E> of(E element) {
     return new SingletonImmutableSet<E>(element);
   }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableSet<E> of(E e1, E e2) {
    return construct(2, e1e2);
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3) {
    return construct(3, e1e2e3);
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) {
    return construct(4, e1e2e3e4);
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) {
    return construct(5, e1e2e3e4e5);
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any element is null
Since:
3.0 (source-compatible since 2.0)
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6,
      E... others) {
    final int paramCount = 6;
    Object[] elements = new Object[paramCount + others.length];
    elements[0] = e1;
    elements[1] = e2;
    elements[2] = e3;
    elements[3] = e4;
    elements[4] = e5;
    elements[5] = e6;
    System.arraycopy(others, 0, elementsparamCountothers.length);
    return construct(elements.lengthelements);
  }

  
Constructs an ImmutableSet from the first n elements of the specified array. If k is the size of the returned ImmutableSet, then the unique elements of elements will be in the first k positions, and elements[i] == null for k <= i < n.

This may modify elements. Additionally, if n == elements.length and elements contains no duplicates, elements may be used without copying in the returned ImmutableSet, in which case it may no longer be modified.

elements may contain only values of type E.

Throws:
NullPointerException if any of the first n elements of elements is null
  private static <E> ImmutableSet<E> construct(int nObject... elements) {
    switch (n) {
      case 0:
        return of();
      case 1: {
        @SuppressWarnings("unchecked"// safe; elements contains only E's
        E elem = (E) elements[0];
        return of(elem);
      }
    }
    int tableSize = chooseTableSize(n);
    Object[] table = new Object[tableSize];
    int mask = tableSize - 1;
    int hashCode = 0;
    int uniques = 0;
    for (int i = 0; i < ni++) {
      Object element = ObjectArrays.checkElementNotNull(elements[i], i);
      int hash = element.hashCode();
      for (int j = Hashing.smear(hash); ; j++) {
        int index = j & mask;
        Object value = table[index];
        if (value == null) {
          // Came to an empty slot. Put the element here.
          elements[uniques++] = element;
          table[index] = element;
          hashCode += hash;
          break;
        } else if (value.equals(element)) {
          break;
        }
      }
    }
    Arrays.fill(elementsuniquesnnull);
    if (uniques == 1) {
      // There is only one element or elements are all duplicates
      @SuppressWarnings("unchecked"// we are careful to only pass in E
      E element = (E) elements[0];
      return new SingletonImmutableSet<E>(elementhashCode);
    } else if (tableSize != chooseTableSize(uniques)) {
      // Resize the table when the array includes too many duplicates.
      // when this happens, we have already made a copy
      return construct(uniqueselements);
    } else {
      Object[] uniqueElements = (uniques < elements.length)
          ? ObjectArrays.arraysCopyOf(elementsuniques)
          : elements;
      return new RegularImmutableSet<E>(uniqueElementshashCodetablemask);
    }
  }
  // We use power-of-2 tables, and this is the highest int that's a power of 2
  static final int MAX_TABLE_SIZE = .;
  // Represents how tightly we can pack things, as a maximum.
  private static final double DESIRED_LOAD_FACTOR = 0.7;
  // If the set has this many elements, it will "max out" the table size
  private static final int CUTOFF =
      (int) Math.floor( * );

  
Returns an array size suitable for the backing array of a hash table that uses open addressing with linear probing in its implementation. The returned size is the smallest power of two that can hold setSize elements with the desired load factor.

Do not call this method with setSize < 2.

  @VisibleForTesting static int chooseTableSize(int setSize) {
    // Correct the size for open addressing to match desired load factor.
    if (setSize < ) {
      // Round up to the next highest power of 2.
      int tableSize = Integer.highestOneBit(setSize - 1) << 1;
      while (tableSize *  < setSize) {
        tableSize <<= 1;
      }
      return tableSize;
    }
    // The table can't be completely full or we'll get infinite reprobes
    checkArgument(setSize < "collection too large");
    return ;
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any of elements is null
Since:
3.0
  public static <E> ImmutableSet<E> copyOf(E[] elements) {
    // TODO(benyu): could we delegate to
    // copyFromCollection(Arrays.asList(elements))?
    switch (elements.length) {
      case 0:
        return of();
      case 1:
        return of(elements[0]);
      default:
        return construct(elements.lengthelements.clone());
    }
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored. This method iterates over elements at most once.

Note that if s is a Set<String>, then ImmutableSet.copyOf(s) returns an ImmutableSet<String> containing each of the strings in s, while ImmutableSet.of(s) returns a ImmutableSet<Set<String>> containing one element (the given set itself).

Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change.

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
    return (elements instanceof Collection)
        ? copyOf(Collections2.cast(elements))
        : copyOf(elements.iterator());
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored.

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) {
    // We special-case for 0 or 1 elements, but anything further is madness.
    if (!elements.hasNext()) {
      return of();
    }
    E first = elements.next();
    if (!elements.hasNext()) {
      return of(first);
    } else {
      return new ImmutableSet.Builder<E>()
          .add(first)
          .addAll(elements)
          .build();
    }
  }

  
Returns an immutable set containing the given elements, in order. Repeated occurrences of an element (according to Object.equals) after the first are ignored. This method iterates over elements at most once.

Note that if s is a Set<String>, then ImmutableSet.copyOf(s) returns an ImmutableSet<String> containing each of the strings in s, while ImmutableSet.of(s) returns a ImmutableSet<Set<String>> containing one element (the given set itself).

Note: Despite what the method name suggests, copyOf will return constant-space views, rather than linear-space copies, of some inputs known to be immutable. For some other immutable inputs, such as key sets of an ImmutableMap, it still performs a copy in order to avoid holding references to the values of the map. The heuristics used in this decision are undocumented and subject to change except that:

  • A full copy will be done of any ImmutableSortedSet.
  • ImmutableSet.copyOf() is idempotent with respect to pointer equality.

This method is safe to use even when elements is a synchronized or concurrent collection that is currently being modified by another thread.

Throws:
NullPointerException if any of elements is null
Since:
7.0 (source-compatible since 2.0)
  public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
    if (elements instanceof ImmutableSet
        && !(elements instanceof ImmutableSortedSet)) {
      @SuppressWarnings("unchecked"// all supported methods are covariant
      ImmutableSet<E> set = (ImmutableSet<E>) elements;
      if (!set.isPartialView()) {
        return set;
      }
    }
    return copyFromCollection(elements);
  }
  private static <E> ImmutableSet<E> copyFromCollection(
      Collection<? extends E> collection) {
    Object[] elements = collection.toArray();
    switch (elements.length) {
      case 0:
        return of();
      case 1:
        @SuppressWarnings("unchecked"// collection had only Es in it
        E onlyElement = (E) elements[0];
        return of(onlyElement);
      default:
        // safe to use the array without copying it
        // as specified by Collection.toArray().
        return construct(elements.lengthelements);
    }
  }
  ImmutableSet() {}

  
Returns true if the hashCode() method runs quickly.
  boolean isHashCodeFast() {
    return false;
  }
  @Override public boolean equals(@Nullable Object object) {
    if (object == this) {
      return true;
    }
    if (object instanceof ImmutableSet
        && isHashCodeFast()
        && ((ImmutableSet<?>) object).isHashCodeFast()
        && hashCode() != object.hashCode()) {
      return false;
    }
    return Sets.equalsImpl(thisobject);
  }
  @Override public int hashCode() {
    return Sets.hashCodeImpl(this);
  }
  // This declaration is needed to make Set.iterator() and
  // ImmutableCollection.iterator() consistent.
  @Override public abstract UnmodifiableIterator<E> iterator();
  abstract static class ArrayImmutableSet<E> extends ImmutableSet<E> {
    // the elements (two or more) in the desired order.
    final transient Object[] elements;
    ArrayImmutableSet(Object[] elements) {
      this. = elements;
    }
    @Override
    public int size() {
      return .;
    }
    @Override public boolean isEmpty() {
      return false;
    }
    @Override public UnmodifiableIterator<E> iterator() {
      return asList().iterator();
    }
    @Override public Object[] toArray() {
      return asList().toArray();
    }
    @Override public <T> T[] toArray(T[] array) {
      return asList().toArray(array);
    }
    @Override public boolean containsAll(Collection<?> targets) {
      if (targets == this) {
        return true;
      }
      if (!(targets instanceof ArrayImmutableSet)) {
        return super.containsAll(targets);
      }
      if (targets.size() > size()) {
        return false;
      }
      for (Object target : ((ArrayImmutableSet<?>) targets).) {
        if (!contains(target)) {
          return false;
        }
      }
      return true;
    }
    @Override boolean isPartialView() {
      return false;
    }
      return new RegularImmutableAsList<E>(this);
    }
  }
  /*
   * This class is used to serialize all ImmutableSet instances, except for
   * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It
   * captures their "logical contents" and they are reconstructed using public
   * static factories. This is necessary to ensure that the existence of a
   * particular implementation type is an implementation detail.
   */
  private static class SerializedForm implements Serializable {
    final Object[] elements;
    SerializedForm(Object[] elements) {
      this. = elements;
    }
    Object readResolve() {
      return copyOf();
    }
    private static final long serialVersionUID = 0;
  }
    return new SerializedForm(toArray());
  }

  
Returns a new builder. The generated builder is equivalent to the builder created by the Builder constructor.
  public static <E> Builder<E> builder() {
    return new Builder<E>();
  }

  
A builder for creating immutable set instances, especially public static final sets ("constant sets"). Example:
   public static final ImmutableSet<Color> GOOGLE_COLORS =
       new ImmutableSet.Builder<Color>()
           .addAll(WEBSAFE_COLORS)
           .add(new Color(0, 191, 255))
           .build();
Builder instances can be reused; it is safe to call build multiple times to build multiple sets in series. Each set is a superset of the set created before it.

Since:
2.0 (imported from Google Collections Library)
  public static class Builder<E> extends ImmutableCollection.Builder<E> {
    Object[] contents;
    int size;

    
Creates a new builder. The returned builder is equivalent to the builder generated by ImmutableSet.builder.
    public Builder() {
      this();
    }
    Builder(int capacity) {
      checkArgument(capacity >= 0, "capacity must be >= 0 but was %s"capacity);
      this. = new Object[capacity];
      this. = 0;
    }

    
Expand capacity to allow the specified number of elements to be added.
    Builder<E> expandFor(int count) {
      int minCapacity =  + count;
      if (. < minCapacity) {
         = ObjectArrays.arraysCopyOf(
            expandedCapacity(.minCapacity));
      }
      return this;
    }

    
Adds element to the ImmutableSet. If the ImmutableSet already contains element, then add has no effect (only the previously added element is retained).

Parameters:
element the element to add
Returns:
this Builder object
Throws:
NullPointerException if element is null
    @Override public Builder<E> add(E element) {
      expandFor(1);
      [++] = checkNotNull(element);
      return this;
    }

    
Adds each element of elements to the ImmutableSet, ignoring duplicate elements (only the first duplicate element is added).

Parameters:
elements the elements to add
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> add(E... elements) {
      for (int i = 0; i < elements.lengthi++) {
        ObjectArrays.checkElementNotNull(elements[i], i);
      }
      expandFor(elements.length);
      System.arraycopy(elements, 0, elements.length);
       += elements.length;
      return this;
    }

    
Adds each element of elements to the ImmutableSet, ignoring duplicate elements (only the first duplicate element is added).

Parameters:
elements the Iterable to add to the ImmutableSet
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> addAll(Iterable<? extends E> elements) {
      if (elements instanceof Collection) {
        Collection<?> collection = (Collection<?>) elements;
        expandFor(collection.size());
      }
      super.addAll(elements);
      return this;
    }

    
Adds each element of elements to the ImmutableSet, ignoring duplicate elements (only the first duplicate element is added).

Parameters:
elements the elements to add to the ImmutableSet
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    
Returns a newly-created ImmutableSet based on the contents of the Builder.
    @Override public ImmutableSet<E> build() {
      ImmutableSet<E> result = construct();
      // construct has the side effect of deduping contents, so we update size
      // accordingly.
       = result.size();
      return result;
    }
  }
New to GrepCode? Check out our FAQ X