/** * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order * each appears first in the source collection. * * <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation * is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} will copy the data only once. * This reduces the expense of habitually making defensive copies at API boundaries. However, the * precise conditions for skipping the copy operation are undefined. * * @throws NullPointerException if any of {@code elements} is null * @since 7.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { /* * TODO(lowasser): consider checking for ImmutableAsList here * TODO(lowasser): consider checking for Multiset here */ // Don't refer to ImmutableSortedSet by name so it won't pull in all that code if (elements instanceof ImmutableSet && !(elements instanceof SortedSet)) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableSet<E> set = (ImmutableSet<E>) elements; if (!set.isPartialView()) { return set; } } else if (elements instanceof EnumSet) { return copyOfEnumSet((EnumSet) elements); } Object[] array = elements.toArray(); return construct(array.length, array); }