• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.util;
28 
29 import jdk.internal.access.SharedSecrets;
30 
31 /**
32  * A specialized {@link Set} implementation for use with enum types.  All of
33  * the elements in an enum set must come from a single enum type that is
34  * specified, explicitly or implicitly, when the set is created.  Enum sets
35  * are represented internally as bit vectors.  This representation is
36  * extremely compact and efficient. The space and time performance of this
37  * class should be good enough to allow its use as a high-quality, typesafe
38  * alternative to traditional {@code int}-based "bit flags."  Even bulk
39  * operations (such as {@code containsAll} and {@code retainAll}) should
40  * run very quickly if their argument is also an enum set.
41  *
42  * <p>The iterator returned by the {@code iterator} method traverses the
43  * elements in their <i>natural order</i> (the order in which the enum
44  * constants are declared).  The returned iterator is <i>weakly
45  * consistent</i>: it will never throw {@link ConcurrentModificationException}
46  * and it may or may not show the effects of any modifications to the set that
47  * occur while the iteration is in progress.
48  *
49  * <p>Null elements are not permitted.  Attempts to insert a null element
50  * will throw {@link NullPointerException}.  Attempts to test for the
51  * presence of a null element or to remove one will, however, function
52  * properly.
53  *
54  * <P>Like most collection implementations, {@code EnumSet} is not
55  * synchronized.  If multiple threads access an enum set concurrently, and at
56  * least one of the threads modifies the set, it should be synchronized
57  * externally.  This is typically accomplished by synchronizing on some
58  * object that naturally encapsulates the enum set.  If no such object exists,
59  * the set should be "wrapped" using the {@link Collections#synchronizedSet}
60  * method.  This is best done at creation time, to prevent accidental
61  * unsynchronized access:
62  *
63  * <pre>
64  * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class));
65  * </pre>
66  *
67  * <p>Implementation note: All basic operations execute in constant time.
68  * They are likely (though not guaranteed) to be much faster than their
69  * {@link HashSet} counterparts.  Even bulk operations execute in
70  * constant time if their argument is also an enum set.
71  *
72  * <p>This class is a member of the
73  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
74  * Java Collections Framework</a>.
75  *
76  * @param <E> the enum type of elements maintained by this set
77  *
78  * @author Josh Bloch
79  * @since 1.5
80  * @see EnumMap
81  */
82 // Android-changed: remove sealed marker (there is no metalava support b/355648520).
83 public abstract /*sealed*/ class EnumSet<E extends Enum<E>> extends AbstractSet<E>
84     implements Cloneable, java.io.Serializable // permits JumboEnumSet, RegularEnumSet
85 {
86     // declare EnumSet.class serialization compatibility with JDK 8
87     @java.io.Serial
88     private static final long serialVersionUID = 1009687484059888093L;
89 
90     /**
91      * The class of all the elements of this set.
92      */
93     final transient Class<E> elementType;
94 
95     /**
96      * All of the values comprising E.  (Cached for performance.)
97      */
98     final transient Enum<?>[] universe;
99 
EnumSet(Class<E>elementType, Enum<?>[] universe)100     EnumSet(Class<E>elementType, Enum<?>[] universe) {
101         this.elementType = elementType;
102         this.universe    = universe;
103     }
104 
105     /**
106      * Creates an empty enum set with the specified element type.
107      *
108      * @param <E> The class of the elements in the set
109      * @param elementType the class object of the element type for this enum
110      *     set
111      * @return An empty enum set of the specified type.
112      * @throws NullPointerException if {@code elementType} is null
113      */
noneOf(Class<E> elementType)114     public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
115         Enum<?>[] universe = getUniverse(elementType);
116         if (universe == null)
117             throw new ClassCastException(elementType + " not an enum");
118 
119         if (universe.length <= 64)
120             return new RegularEnumSet<>(elementType, universe);
121         else
122             return new JumboEnumSet<>(elementType, universe);
123     }
124 
125     /**
126      * Creates an enum set containing all of the elements in the specified
127      * element type.
128      *
129      * @param <E> The class of the elements in the set
130      * @param elementType the class object of the element type for this enum
131      *     set
132      * @return An enum set containing all the elements in the specified type.
133      * @throws NullPointerException if {@code elementType} is null
134      */
allOf(Class<E> elementType)135     public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) {
136         EnumSet<E> result = noneOf(elementType);
137         result.addAll();
138         return result;
139     }
140 
141     /**
142      * Adds all of the elements from the appropriate enum type to this enum
143      * set, which is empty prior to the call.
144      */
addAll()145     abstract void addAll();
146 
147     /**
148      * Creates an enum set with the same element type as the specified enum
149      * set, initially containing the same elements (if any).
150      *
151      * @param <E> The class of the elements in the set
152      * @param s the enum set from which to initialize this enum set
153      * @return A copy of the specified enum set.
154      * @throws NullPointerException if {@code s} is null
155      */
copyOf(EnumSet<E> s)156     public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) {
157         return s.clone();
158     }
159 
160     /**
161      * Creates an enum set initialized from the specified collection.  If
162      * the specified collection is an {@code EnumSet} instance, this static
163      * factory method behaves identically to {@link #copyOf(EnumSet)}.
164      * Otherwise, the specified collection must contain at least one element
165      * (in order to determine the new enum set's element type).
166      *
167      * @param <E> The class of the elements in the collection
168      * @param c the collection from which to initialize this enum set
169      * @return An enum set initialized from the given collection.
170      * @throws IllegalArgumentException if {@code c} is not an
171      *     {@code EnumSet} instance and contains no elements
172      * @throws NullPointerException if {@code c} is null
173      */
copyOf(Collection<E> c)174     public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) {
175         if (c instanceof EnumSet) {
176             return ((EnumSet<E>)c).clone();
177         } else {
178             if (c.isEmpty())
179                 throw new IllegalArgumentException("Collection is empty");
180             Iterator<E> i = c.iterator();
181             E first = i.next();
182             EnumSet<E> result = EnumSet.of(first);
183             while (i.hasNext())
184                 result.add(i.next());
185             return result;
186         }
187     }
188 
189     /**
190      * Creates an enum set with the same element type as the specified enum
191      * set, initially containing all the elements of this type that are
192      * <i>not</i> contained in the specified set.
193      *
194      * @param <E> The class of the elements in the enum set
195      * @param s the enum set from whose complement to initialize this enum set
196      * @return The complement of the specified set in this set
197      * @throws NullPointerException if {@code s} is null
198      */
complementOf(EnumSet<E> s)199     public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) {
200         EnumSet<E> result = copyOf(s);
201         result.complement();
202         return result;
203     }
204 
205     /**
206      * Creates an enum set initially containing the specified element.
207      *
208      * Overloadings of this method exist to initialize an enum set with
209      * one through five elements.  A sixth overloading is provided that
210      * uses the varargs feature.  This overloading may be used to create
211      * an enum set initially containing an arbitrary number of elements, but
212      * is likely to run slower than the overloadings that do not use varargs.
213      *
214      * @param <E> The class of the specified element and of the set
215      * @param e the element that this set is to contain initially
216      * @throws NullPointerException if {@code e} is null
217      * @return an enum set initially containing the specified element
218      */
of(E e)219     public static <E extends Enum<E>> EnumSet<E> of(E e) {
220         EnumSet<E> result = noneOf(e.getDeclaringClass());
221         result.add(e);
222         return result;
223     }
224 
225     /**
226      * Creates an enum set initially containing the specified elements.
227      *
228      * Overloadings of this method exist to initialize an enum set with
229      * one through five elements.  A sixth overloading is provided that
230      * uses the varargs feature.  This overloading may be used to create
231      * an enum set initially containing an arbitrary number of elements, but
232      * is likely to run slower than the overloadings that do not use varargs.
233      *
234      * @param <E> The class of the parameter elements and of the set
235      * @param e1 an element that this set is to contain initially
236      * @param e2 another element that this set is to contain initially
237      * @throws NullPointerException if any parameters are null
238      * @return an enum set initially containing the specified elements
239      */
of(E e1, E e2)240     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) {
241         EnumSet<E> result = noneOf(e1.getDeclaringClass());
242         result.add(e1);
243         result.add(e2);
244         return result;
245     }
246 
247     /**
248      * Creates an enum set initially containing the specified elements.
249      *
250      * Overloadings of this method exist to initialize an enum set with
251      * one through five elements.  A sixth overloading is provided that
252      * uses the varargs feature.  This overloading may be used to create
253      * an enum set initially containing an arbitrary number of elements, but
254      * is likely to run slower than the overloadings that do not use varargs.
255      *
256      * @param <E> The class of the parameter elements and of the set
257      * @param e1 an element that this set is to contain initially
258      * @param e2 another element that this set is to contain initially
259      * @param e3 another element that this set is to contain initially
260      * @throws NullPointerException if any parameters are null
261      * @return an enum set initially containing the specified elements
262      */
of(E e1, E e2, E e3)263     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) {
264         EnumSet<E> result = noneOf(e1.getDeclaringClass());
265         result.add(e1);
266         result.add(e2);
267         result.add(e3);
268         return result;
269     }
270 
271     /**
272      * Creates an enum set initially containing the specified elements.
273      *
274      * Overloadings of this method exist to initialize an enum set with
275      * one through five elements.  A sixth overloading is provided that
276      * uses the varargs feature.  This overloading may be used to create
277      * an enum set initially containing an arbitrary number of elements, but
278      * is likely to run slower than the overloadings that do not use varargs.
279      *
280      * @param <E> The class of the parameter elements and of the set
281      * @param e1 an element that this set is to contain initially
282      * @param e2 another element that this set is to contain initially
283      * @param e3 another element that this set is to contain initially
284      * @param e4 another element that this set is to contain initially
285      * @throws NullPointerException if any parameters are null
286      * @return an enum set initially containing the specified elements
287      */
of(E e1, E e2, E e3, E e4)288     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) {
289         EnumSet<E> result = noneOf(e1.getDeclaringClass());
290         result.add(e1);
291         result.add(e2);
292         result.add(e3);
293         result.add(e4);
294         return result;
295     }
296 
297     /**
298      * Creates an enum set initially containing the specified elements.
299      *
300      * Overloadings of this method exist to initialize an enum set with
301      * one through five elements.  A sixth overloading is provided that
302      * uses the varargs feature.  This overloading may be used to create
303      * an enum set initially containing an arbitrary number of elements, but
304      * is likely to run slower than the overloadings that do not use varargs.
305      *
306      * @param <E> The class of the parameter elements and of the set
307      * @param e1 an element that this set is to contain initially
308      * @param e2 another element that this set is to contain initially
309      * @param e3 another element that this set is to contain initially
310      * @param e4 another element that this set is to contain initially
311      * @param e5 another element that this set is to contain initially
312      * @throws NullPointerException if any parameters are null
313      * @return an enum set initially containing the specified elements
314      */
of(E e1, E e2, E e3, E e4, E e5)315     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4,
316                                                     E e5)
317     {
318         EnumSet<E> result = noneOf(e1.getDeclaringClass());
319         result.add(e1);
320         result.add(e2);
321         result.add(e3);
322         result.add(e4);
323         result.add(e5);
324         return result;
325     }
326 
327     /**
328      * Creates an enum set initially containing the specified elements.
329      * This factory, whose parameter list uses the varargs feature, may
330      * be used to create an enum set initially containing an arbitrary
331      * number of elements, but it is likely to run slower than the overloadings
332      * that do not use varargs.
333      *
334      * @param <E> The class of the parameter elements and of the set
335      * @param first an element that the set is to contain initially
336      * @param rest the remaining elements the set is to contain initially
337      * @throws NullPointerException if any of the specified elements are null,
338      *     or if {@code rest} is null
339      * @return an enum set initially containing the specified elements
340      */
341     @SafeVarargs
of(E first, E... rest)342     public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) {
343         EnumSet<E> result = noneOf(first.getDeclaringClass());
344         result.add(first);
345         for (E e : rest)
346             result.add(e);
347         return result;
348     }
349 
350     /**
351      * Creates an enum set initially containing all of the elements in the
352      * range defined by the two specified endpoints.  The returned set will
353      * contain the endpoints themselves, which may be identical but must not
354      * be out of order.
355      *
356      * @param <E> The class of the parameter elements and of the set
357      * @param from the first element in the range
358      * @param to the last element in the range
359      * @throws NullPointerException if {@code from} or {@code to} are null
360      * @throws IllegalArgumentException if {@code from.compareTo(to) > 0}
361      * @return an enum set initially containing all of the elements in the
362      *         range defined by the two specified endpoints
363      */
range(E from, E to)364     public static <E extends Enum<E>> EnumSet<E> range(E from, E to) {
365         if (from.compareTo(to) > 0)
366             throw new IllegalArgumentException(from + " > " + to);
367         EnumSet<E> result = noneOf(from.getDeclaringClass());
368         result.addRange(from, to);
369         return result;
370     }
371 
372     /**
373      * Adds the specified range to this enum set, which is empty prior
374      * to the call.
375      */
addRange(E from, E to)376     abstract void addRange(E from, E to);
377 
378     /**
379      * Returns a copy of this set.
380      *
381      * @return a copy of this set
382      */
383     @SuppressWarnings("unchecked")
clone()384     public EnumSet<E> clone() {
385         try {
386             return (EnumSet<E>) super.clone();
387         } catch(CloneNotSupportedException e) {
388             throw new AssertionError(e);
389         }
390     }
391 
392     /**
393      * Complements the contents of this enum set.
394      */
complement()395     abstract void complement();
396 
397     /**
398      * Throws an exception if e is not of the correct type for this enum set.
399      */
typeCheck(E e)400     final void typeCheck(E e) {
401         Class<?> eClass = e.getClass();
402         if (eClass != elementType && eClass.getSuperclass() != elementType)
403             throw new ClassCastException(eClass + " != " + elementType);
404     }
405 
406     /**
407      * Returns all of the values comprising E.
408      * The result is uncloned, cached, and shared by all callers.
409      */
getUniverse(Class<E> elementType)410     private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) {
411         // Android-changed: Use getEnumConstantsShared directly instead of going
412         // through SharedSecrets.
413         return elementType.getEnumConstantsShared();
414     }
415 
416     /**
417      * This class is used to serialize all EnumSet instances, regardless of
418      * implementation type.  It captures their "logical contents" and they
419      * are reconstructed using public static factories.  This is necessary
420      * to ensure that the existence of a particular implementation type is
421      * an implementation detail.
422      *
423      * @serial include
424      */
425     private static class SerializationProxy<E extends Enum<E>>
426         implements java.io.Serializable
427     {
428 
429         private static final Enum<?>[] ZERO_LENGTH_ENUM_ARRAY = new Enum<?>[0];
430 
431         /**
432          * The element type of this enum set.
433          *
434          * @serial
435          */
436         private final Class<E> elementType;
437 
438         /**
439          * The elements contained in this enum set.
440          *
441          * @serial
442          */
443         private final Enum<?>[] elements;
444 
SerializationProxy(EnumSet<E> set)445         SerializationProxy(EnumSet<E> set) {
446             elementType = set.elementType;
447             elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY);
448         }
449 
450         /**
451          * Returns an {@code EnumSet} object with initial state
452          * held by this proxy.
453          *
454          * @return a {@code EnumSet} object with initial state
455          * held by this proxy
456          */
457         @SuppressWarnings("unchecked")
458         @java.io.Serial
readResolve()459         private Object readResolve() {
460             // instead of cast to E, we should perhaps use elementType.cast()
461             // to avoid injection of forged stream, but it will slow the
462             // implementation
463             EnumSet<E> result = EnumSet.noneOf(elementType);
464             for (Enum<?> e : elements)
465                 result.add((E)e);
466             return result;
467         }
468 
469         @java.io.Serial
470         private static final long serialVersionUID = 362491234563181265L;
471     }
472 
473     /**
474      * Returns a
475      * <a href="{@docRoot}/serialized-form.html#java.util.EnumSet.SerializationProxy">
476      * SerializationProxy</a>
477      * representing the state of this instance.
478      *
479      * @return a {@link SerializationProxy}
480      * representing the state of this instance
481      */
482     @java.io.Serial
writeReplace()483     Object writeReplace() {
484         return new SerializationProxy<>(this);
485     }
486 
487     /**
488      * Throws {@code InvalidObjectException}.
489      * @param s the stream
490      * @throws java.io.InvalidObjectException always
491      */
492     @java.io.Serial
readObject(java.io.ObjectInputStream s)493     private void readObject(java.io.ObjectInputStream s)
494         throws java.io.InvalidObjectException {
495         throw new java.io.InvalidObjectException("Proxy required");
496     }
497 
498     /**
499      * Throws {@code InvalidObjectException}.
500      * @throws java.io.InvalidObjectException always
501      */
502     @java.io.Serial
readObjectNoData()503     private void readObjectNoData()
504         throws java.io.InvalidObjectException {
505         throw new java.io.InvalidObjectException("Proxy required");
506     }
507 }
508