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))}
(Collection<? extends E> elements)
| 170 | * @since 7.0 (source-compatible since 2.0) |
| 171 | */ |
| 172 | public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { |
| 173 | /* |
| 174 | * TODO(lowasser): consider checking for ImmutableAsList here |
| 175 | * TODO(lowasser): consider checking for Multiset here |
| 176 | */ |
| 177 | // Don't refer to ImmutableSortedSet by name so it won't pull in all that code |
| 178 | if (elements instanceof ImmutableSet && !(elements instanceof SortedSet)) { |
| 179 | @SuppressWarnings("unchecked") // all supported methods are covariant |
| 180 | ImmutableSet<E> set = (ImmutableSet<E>) elements; |
| 181 | if (!set.isPartialView()) { |
| 182 | return set; |
| 183 | } |
| 184 | } else if (elements instanceof EnumSet) { |
| 185 | EnumSet<?> clone = ((EnumSet<?>) elements).clone(); |
| 186 | ImmutableSet<?> untypedResult = ImmutableEnumSet.asImmutable(clone); |
| 187 | /* |
| 188 | * The result has the same type argument we started with. We just couldn't express EnumSet<E> |
| 189 | * or ImmutableEnumSet<E> along the way because our own <E> isn't <E extends Enum<E>>. |
| 190 | * |
| 191 | * We are also performing a safe covariant cast to change <? extends E> to <E>. |
| 192 | */ |
| 193 | @SuppressWarnings("unchecked") |
| 194 | ImmutableSet<E> result = (ImmutableSet<E>) untypedResult; |
| 195 | return result; |
| 196 | } |
| 197 | |
| 198 | if (elements.isEmpty()) { |
| 199 | // We avoid allocating anything. |
| 200 | return of(); |
| 201 | } |
| 202 | // Collection<E>.toArray() is required to contain only E instances, and all we do is read them. |
| 203 | // TODO(cpovirk): Consider using Object[] anyway. |
| 204 | @SuppressWarnings("unchecked") |
| 205 | E[] array = (E[]) elements.toArray(); |
| 206 | /* |
| 207 | * For a Set, we guess that it contains no duplicates. That's just a guess for purpose of |
| 208 | * sizing; if the Set uses different equality semantics, it might contain duplicates according |
| 209 | * to equals(), and we will deduplicate those properly, albeit at some cost in allocations. |
| 210 | */ |
| 211 | int expectedSize = |
| 212 | elements instanceof Set ? array.length : estimatedSizeForUnknownDuplication(array.length); |
| 213 | return fromArrayWithExpectedSize(array, expectedSize); |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order |
no test coverage detected