• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2003, 2019, 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 /**
30  * A specialized {@link Set} implementation for use with enum types.  All of
31  * the elements in an enum set must come from a single enum type that is
32  * specified, explicitly or implicitly, when the set is created.  Enum sets
33  * are represented internally as bit vectors.  This representation is
34  * extremely compact and efficient. The space and time performance of this
35  * class should be good enough to allow its use as a high-quality, typesafe
36  * alternative to traditional {@code int}-based "bit flags."  Even bulk
37  * operations (such as {@code containsAll} and {@code retainAll}) should
38  * run very quickly if their argument is also an enum set.
39  *
40  * <p>The iterator returned by the {@code iterator} method traverses the
41  * elements in their <i>natural order</i> (the order in which the enum
42  * constants are declared).  The returned iterator is <i>weakly
43  * consistent</i>: it will never throw {@link ConcurrentModificationException}
44  * and it may or may not show the effects of any modifications to the set that
45  * occur while the iteration is in progress.
46  *
47  * <p>Null elements are not permitted.  Attempts to insert a null element
48  * will throw {@link NullPointerException}.  Attempts to test for the
49  * presence of a null element or to remove one will, however, function
50  * properly.
51  *
52  * <P>Like most collection implementations, {@code EnumSet} is not
53  * synchronized.  If multiple threads access an enum set concurrently, and at
54  * least one of the threads modifies the set, it should be synchronized
55  * externally.  This is typically accomplished by synchronizing on some
56  * object that naturally encapsulates the enum set.  If no such object exists,
57  * the set should be "wrapped" using the {@link Collections#synchronizedSet}
58  * method.  This is best done at creation time, to prevent accidental
59  * unsynchronized access:
60  *
61  * <pre>
62  * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class));
63  * </pre>
64  *
65  * <p>Implementation note: All basic operations execute in constant time.
66  * They are likely (though not guaranteed) to be much faster than their
67  * {@link HashSet} counterparts.  Even bulk operations execute in
68  * constant time if their argument is also an enum set.
69  *
70  * <p>This class is a member of the
71  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
72  * Java Collections Framework</a>.
73  *
74  * @author Josh Bloch
75  * @since 1.5
76  * @see EnumMap
77  */
78 @SuppressWarnings("serial") // No serialVersionUID declared
79 public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
80     implements Cloneable, java.io.Serializable
81 {
82     // The following must be present in order to preserve the same computed
83     // serialVersionUID value as JDK 8, and to prevent the appearance of
84     // the fields in the Serialized Form documentation. See JDK-8227368.
access$000()85     static Enum<?>[] access$000() { return null; }
86     private static final java.io.ObjectStreamField[] serialPersistentFields
87         = new java.io.ObjectStreamField[0];
88 
89     /**
90      * The class of all the elements of this set.
91      */
92     final Class<E> elementType;
93 
94     /**
95      * All of the values comprising E.  (Cached for performance.)
96      */
97     final Enum<?>[] universe;
98 
EnumSet(Class<E>elementType, Enum<?>[] universe)99     EnumSet(Class<E>elementType, Enum<?>[] universe) {
100         this.elementType = elementType;
101         this.universe    = universe;
102     }
103 
104     /**
105      * Creates an empty enum set with the specified element type.
106      *
107      * @param <E> The class of the elements in the set
108      * @param elementType the class object of the element type for this enum
109      *     set
110      * @return An empty enum set of the specified type.
111      * @throws NullPointerException if {@code elementType} is null
112      */
noneOf(Class<E> elementType)113     public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
114         Enum<?>[] universe = getUniverse(elementType);
115         if (universe == null)
116             throw new ClassCastException(elementType + " not an enum");
117 
118         if (universe.length <= 64)
119             return new RegularEnumSet<>(elementType, universe);
120         else
121             return new JumboEnumSet<>(elementType, universe);
122     }
123 
124     /**
125      * Creates an enum set containing all of the elements in the specified
126      * element type.
127      *
128      * @param <E> The class of the elements in the set
129      * @param elementType the class object of the element type for this enum
130      *     set
131      * @return An enum set containing all the elements in the specified type.
132      * @throws NullPointerException if {@code elementType} is null
133      */
allOf(Class<E> elementType)134     public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) {
135         EnumSet<E> result = noneOf(elementType);
136         result.addAll();
137         return result;
138     }
139 
140     /**
141      * Adds all of the elements from the appropriate enum type to this enum
142      * set, which is empty prior to the call.
143      */
addAll()144     abstract void addAll();
145 
146     /**
147      * Creates an enum set with the same element type as the specified enum
148      * set, initially containing the same elements (if any).
149      *
150      * @param <E> The class of the elements in the set
151      * @param s the enum set from which to initialize this enum set
152      * @return A copy of the specified enum set.
153      * @throws NullPointerException if {@code s} is null
154      */
copyOf(EnumSet<E> s)155     public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) {
156         return s.clone();
157     }
158 
159     /**
160      * Creates an enum set initialized from the specified collection.  If
161      * the specified collection is an {@code EnumSet} instance, this static
162      * factory method behaves identically to {@link #copyOf(EnumSet)}.
163      * Otherwise, the specified collection must contain at least one element
164      * (in order to determine the new enum set's element type).
165      *
166      * @param <E> The class of the elements in the collection
167      * @param c the collection from which to initialize this enum set
168      * @return An enum set initialized from the given collection.
169      * @throws IllegalArgumentException if {@code c} is not an
170      *     {@code EnumSet} instance and contains no elements
171      * @throws NullPointerException if {@code c} is null
172      */
copyOf(Collection<E> c)173     public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) {
174         if (c instanceof EnumSet) {
175             return ((EnumSet<E>)c).clone();
176         } else {
177             if (c.isEmpty())
178                 throw new IllegalArgumentException("Collection is empty");
179             Iterator<E> i = c.iterator();
180             E first = i.next();
181             EnumSet<E> result = EnumSet.of(first);
182             while (i.hasNext())
183                 result.add(i.next());
184             return result;
185         }
186     }
187 
188     /**
189      * Creates an enum set with the same element type as the specified enum
190      * set, initially containing all the elements of this type that are
191      * <i>not</i> contained in the specified set.
192      *
193      * @param <E> The class of the elements in the enum set
194      * @param s the enum set from whose complement to initialize this enum set
195      * @return The complement of the specified set in this set
196      * @throws NullPointerException if {@code s} is null
197      */
complementOf(EnumSet<E> s)198     public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) {
199         EnumSet<E> result = copyOf(s);
200         result.complement();
201         return result;
202     }
203 
204     /**
205      * Creates an enum set initially containing the specified element.
206      *
207      * Overloadings of this method exist to initialize an enum set with
208      * one through five elements.  A sixth overloading is provided that
209      * uses the varargs feature.  This overloading may be used to create
210      * an enum set initially containing an arbitrary number of elements, but
211      * is likely to run slower than the overloadings that do not use varargs.
212      *
213      * @param <E> The class of the specified element and of the set
214      * @param e the element that this set is to contain initially
215      * @throws NullPointerException if {@code e} is null
216      * @return an enum set initially containing the specified element
217      */
of(E e)218     public static <E extends Enum<E>> EnumSet<E> of(E e) {
219         EnumSet<E> result = noneOf(e.getDeclaringClass());
220         result.add(e);
221         return result;
222     }
223 
224     /**
225      * Creates an enum set initially containing the specified elements.
226      *
227      * Overloadings of this method exist to initialize an enum set with
228      * one through five elements.  A sixth overloading is provided that
229      * uses the varargs feature.  This overloading may be used to create
230      * an enum set initially containing an arbitrary number of elements, but
231      * is likely to run slower than the overloadings that do not use varargs.
232      *
233      * @param <E> The class of the parameter elements and of the set
234      * @param e1 an element that this set is to contain initially
235      * @param e2 another element that this set is to contain initially
236      * @throws NullPointerException if any parameters are null
237      * @return an enum set initially containing the specified elements
238      */
of(E e1, E e2)239     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) {
240         EnumSet<E> result = noneOf(e1.getDeclaringClass());
241         result.add(e1);
242         result.add(e2);
243         return result;
244     }
245 
246     /**
247      * Creates an enum set initially containing the specified elements.
248      *
249      * Overloadings of this method exist to initialize an enum set with
250      * one through five elements.  A sixth overloading is provided that
251      * uses the varargs feature.  This overloading may be used to create
252      * an enum set initially containing an arbitrary number of elements, but
253      * is likely to run slower than the overloadings that do not use varargs.
254      *
255      * @param <E> The class of the parameter elements and of the set
256      * @param e1 an element that this set is to contain initially
257      * @param e2 another element that this set is to contain initially
258      * @param e3 another element that this set is to contain initially
259      * @throws NullPointerException if any parameters are null
260      * @return an enum set initially containing the specified elements
261      */
of(E e1, E e2, E e3)262     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) {
263         EnumSet<E> result = noneOf(e1.getDeclaringClass());
264         result.add(e1);
265         result.add(e2);
266         result.add(e3);
267         return result;
268     }
269 
270     /**
271      * Creates an enum set initially containing the specified elements.
272      *
273      * Overloadings of this method exist to initialize an enum set with
274      * one through five elements.  A sixth overloading is provided that
275      * uses the varargs feature.  This overloading may be used to create
276      * an enum set initially containing an arbitrary number of elements, but
277      * is likely to run slower than the overloadings that do not use varargs.
278      *
279      * @param <E> The class of the parameter elements and of the set
280      * @param e1 an element that this set is to contain initially
281      * @param e2 another element that this set is to contain initially
282      * @param e3 another element that this set is to contain initially
283      * @param e4 another element that this set is to contain initially
284      * @throws NullPointerException if any parameters are null
285      * @return an enum set initially containing the specified elements
286      */
of(E e1, E e2, E e3, E e4)287     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) {
288         EnumSet<E> result = noneOf(e1.getDeclaringClass());
289         result.add(e1);
290         result.add(e2);
291         result.add(e3);
292         result.add(e4);
293         return result;
294     }
295 
296     /**
297      * Creates an enum set initially containing the specified elements.
298      *
299      * Overloadings of this method exist to initialize an enum set with
300      * one through five elements.  A sixth overloading is provided that
301      * uses the varargs feature.  This overloading may be used to create
302      * an enum set initially containing an arbitrary number of elements, but
303      * is likely to run slower than the overloadings that do not use varargs.
304      *
305      * @param <E> The class of the parameter elements and of the set
306      * @param e1 an element that this set is to contain initially
307      * @param e2 another element that this set is to contain initially
308      * @param e3 another element that this set is to contain initially
309      * @param e4 another element that this set is to contain initially
310      * @param e5 another element that this set is to contain initially
311      * @throws NullPointerException if any parameters are null
312      * @return an enum set initially containing the specified elements
313      */
of(E e1, E e2, E e3, E e4, E e5)314     public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4,
315                                                     E e5)
316     {
317         EnumSet<E> result = noneOf(e1.getDeclaringClass());
318         result.add(e1);
319         result.add(e2);
320         result.add(e3);
321         result.add(e4);
322         result.add(e5);
323         return result;
324     }
325 
326     /**
327      * Creates an enum set initially containing the specified elements.
328      * This factory, whose parameter list uses the varargs feature, may
329      * be used to create an enum set initially containing an arbitrary
330      * number of elements, but it is likely to run slower than the overloadings
331      * that do not use varargs.
332      *
333      * @param <E> The class of the parameter elements and of the set
334      * @param first an element that the set is to contain initially
335      * @param rest the remaining elements the set is to contain initially
336      * @throws NullPointerException if any of the specified elements are null,
337      *     or if {@code rest} is null
338      * @return an enum set initially containing the specified elements
339      */
340     @SafeVarargs
of(E first, E... rest)341     public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) {
342         EnumSet<E> result = noneOf(first.getDeclaringClass());
343         result.add(first);
344         for (E e : rest)
345             result.add(e);
346         return result;
347     }
348 
349     /**
350      * Creates an enum set initially containing all of the elements in the
351      * range defined by the two specified endpoints.  The returned set will
352      * contain the endpoints themselves, which may be identical but must not
353      * be out of order.
354      *
355      * @param <E> The class of the parameter elements and of the set
356      * @param from the first element in the range
357      * @param to the last element in the range
358      * @throws NullPointerException if {@code from} or {@code to} are null
359      * @throws IllegalArgumentException if {@code from.compareTo(to) > 0}
360      * @return an enum set initially containing all of the elements in the
361      *         range defined by the two specified endpoints
362      */
range(E from, E to)363     public static <E extends Enum<E>> EnumSet<E> range(E from, E to) {
364         if (from.compareTo(to) > 0)
365             throw new IllegalArgumentException(from + " > " + to);
366         EnumSet<E> result = noneOf(from.getDeclaringClass());
367         result.addRange(from, to);
368         return result;
369     }
370 
371     /**
372      * Adds the specified range to this enum set, which is empty prior
373      * to the call.
374      */
addRange(E from, E to)375     abstract void addRange(E from, E to);
376 
377     /**
378      * Returns a copy of this set.
379      *
380      * @return a copy of this set
381      */
382     @SuppressWarnings("unchecked")
clone()383     public EnumSet<E> clone() {
384         try {
385             return (EnumSet<E>) super.clone();
386         } catch(CloneNotSupportedException e) {
387             throw new AssertionError(e);
388         }
389     }
390 
391     /**
392      * Complements the contents of this enum set.
393      */
complement()394     abstract void complement();
395 
396     /**
397      * Throws an exception if e is not of the correct type for this enum set.
398      */
typeCheck(E e)399     final void typeCheck(E e) {
400         Class<?> eClass = e.getClass();
401         if (eClass != elementType && eClass.getSuperclass() != elementType)
402             throw new ClassCastException(eClass + " != " + elementType);
403     }
404 
405     /**
406      * Returns all of the values comprising E.
407      * The result is uncloned, cached, and shared by all callers.
408      */
getUniverse(Class<E> elementType)409     private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) {
410         // Android-changed: Use getEnumConstantsShared directly instead of going
411         // through SharedSecrets.
412         return elementType.getEnumConstantsShared();
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