1 /*
2  * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.util;
27 
28 import jdk.internal.misc.SharedSecrets;
29 
30 /**
31  * A specialized {@link Set} implementation for use with enum types.  All of
32  * the elements in an enum set must come from a single enum type that is
33  * specified, explicitly or implicitly, when the set is created.  Enum sets
34  * are represented internally as bit vectors.  This representation is
35  * extremely compact and efficient. The space and time performance of this
36  * class should be good enough to allow its use as a high-quality, typesafe
37  * alternative to traditional {@code int}-based "bit flags."  Even bulk
38  * operations (such as {@code containsAll} and {@code retainAll}) should
39  * run very quickly if their argument is also an enum set.
40  *
41  * <p>The iterator returned by the {@code iterator} method traverses the
42  * elements in their <i>natural order</i> (the order in which the enum
43  * constants are declared).  The returned iterator is <i>weakly
44  * consistent</i>: it will never throw {@link ConcurrentModificationException}
45  * and it may or may not show the effects of any modifications to the set that
46  * occur while the iteration is in progress.
47  *
48  * <p>Null elements are not permitted.  Attempts to insert a null element
49  * will throw {@link NullPointerException}.  Attempts to test for the
50  * presence of a null element or to remove one will, however, function
51  * properly.
52  *
53  * <P>Like most collection implementations, {@code EnumSet} is not
54  * synchronized.  If multiple threads access an enum set concurrently, and at
55  * least one of the threads modifies the set, it should be synchronized
56  * externally.  This is typically accomplished by synchronizing on some
57  * object that naturally encapsulates the enum set.  If no such object exists,
58  * the set should be "wrapped" using the {@link Collections#synchronizedSet}
59  * method.  This is best done at creation time, to prevent accidental
60  * unsynchronized access:
61  *
62  * <pre>
63  * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class));
64  * </pre>
65  *
66  * <p>Implementation note: All basic operations execute in constant time.
67  * They are likely (though not guaranteed) to be much faster than their
68  * {@link HashSet} counterparts.  Even bulk operations execute in
69  * constant time if their argument is also an enum set.
70  *
71  * <p>This class is a member of the
72  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
73  * Java Collections Framework</a>.
74  *
75  * @author Josh Bloch
76  * @since 1.5
77  * @see EnumMap
78  */
79 @SuppressWarnings("serial") // No serialVersionUID declared
80 public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
81     implements Cloneable, java.io.Serializable
82 {
83     // The following must be present in order to preserve the same computed
84     // serialVersionUID value as JDK 8, and to prevent the appearance of
85     // the fields in the Serialized Form documentation. See JDK-8227368.
access$000()86     static Enum<?>[] access$000() { return null; }
87     private static final java.io.ObjectStreamField[] serialPersistentFields
88         = new java.io.ObjectStreamField[0];
89 
90     /**
91      * The class of all the elements of this set.
92      */
93     final Class<E> elementType;
94 
95     /**
96      * All of the values comprising E.  (Cached for performance.)
97      */
98     final 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         return SharedSecrets.getJavaLangAccess()
412                                         .getEnumConstantsShared(elementType);
413     }
414 
415     /**
416      * This class is used to serialize all EnumSet instances, regardless of
417      * implementation type.  It captures their "logical contents" and they
418      * are reconstructed using public static factories.  This is necessary
419      * to ensure that the existence of a particular implementation type is
420      * an implementation detail.
421      *
422      * @serial include
423      */
424     private static class SerializationProxy<E extends Enum<E>>
425         implements java.io.Serializable
426     {
427 
428         private static final Enum<?>[] ZERO_LENGTH_ENUM_ARRAY = new Enum<?>[0];
429 
430         /**
431          * The element type of this enum set.
432          *
433          * @serial
434          */
435         private final Class<E> elementType;
436 
437         /**
438          * The elements contained in this enum set.
439          *
440          * @serial
441          */
442         private final Enum<?>[] elements;
443 
SerializationProxy(EnumSet<E> set)444         SerializationProxy(EnumSet<E> set) {
445             elementType = set.elementType;
446             elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY);
447         }
448 
449         /**
450          * Returns an {@code EnumSet} object with initial state
451          * held by this proxy.
452          *
453          * @return a {@code EnumSet} object with initial state
454          * held by this proxy
455          */
456         @SuppressWarnings("unchecked")
readResolve()457         private Object readResolve() {
458             // instead of cast to E, we should perhaps use elementType.cast()
459             // to avoid injection of forged stream, but it will slow the
460             // implementation
461             EnumSet<E> result = EnumSet.noneOf(elementType);
462             for (Enum<?> e : elements)
463                 result.add((E)e);
464             return result;
465         }
466 
467         private static final long serialVersionUID = 362491234563181265L;
468     }
469 
470     /**
471      * Returns a
472      * <a href="../../serialized-form.html#java.util.EnumSet.SerializationProxy">
473      * SerializationProxy</a>
474      * representing the state of this instance.
475      *
476      * @return a {@link SerializationProxy}
477      * representing the state of this instance
478      */
writeReplace()479     Object writeReplace() {
480         return new SerializationProxy<>(this);
481     }
482 
483     /**
484      * @param s the stream
485      * @throws java.io.InvalidObjectException always
486      */
readObject(java.io.ObjectInputStream s)487     private void readObject(java.io.ObjectInputStream s)
488         throws java.io.InvalidObjectException {
489         throw new java.io.InvalidObjectException("Proxy required");
490     }
491 }
492