EnumSet.java revision d2449bb576ad1e3a3877364e5e1ae28625f69e35
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 2003, 2011, 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
27package 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 <tt>int</tt>-based "bit flags."  Even bulk
37 * operations (such as <tt>containsAll</tt> and <tt>retainAll</tt>) should
38 * run very quickly if their argument is also an enum set.
39 *
40 * <p>The iterator returned by the <tt>iterator</tt> 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, <tt>EnumSet</tt> 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}openjdk-redirect.html?v=8&path=/technotes/guides/collections/index.html">
72 * Java Collections Framework</a>.
73 *
74 * @author Josh Bloch
75 * @since 1.5
76 * @see EnumMap
77 * @serial exclude
78 */
79public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
80    implements Cloneable, java.io.Serializable
81{
82    /**
83     * The class of all the elements of this set.
84     */
85    final Class<E> elementType;
86
87    /**
88     * All of the values comprising T.  (Cached for performance.)
89     */
90    final Enum[] universe;
91
92    private static Enum[] ZERO_LENGTH_ENUM_ARRAY = new Enum[0];
93
94    EnumSet(Class<E>elementType, Enum[] universe) {
95        this.elementType = elementType;
96        this.universe    = universe;
97    }
98
99    /**
100     * Creates an empty enum set with the specified element type.
101     *
102     * @param elementType the class object of the element type for this enum
103     *     set
104     * @throws NullPointerException if <tt>elementType</tt> is null
105     */
106    public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
107        Enum[] universe = getUniverse(elementType);
108        if (universe == null)
109            throw new ClassCastException(elementType + " not an enum");
110
111        if (universe.length <= 64)
112            return new RegularEnumSet<>(elementType, universe);
113        else
114            return new JumboEnumSet<>(elementType, universe);
115    }
116
117    /**
118     * Creates an enum set containing all of the elements in the specified
119     * element type.
120     *
121     * @param elementType the class object of the element type for this enum
122     *     set
123     * @throws NullPointerException if <tt>elementType</tt> is null
124     */
125    public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) {
126        EnumSet<E> result = noneOf(elementType);
127        result.addAll();
128        return result;
129    }
130
131    /**
132     * Adds all of the elements from the appropriate enum type to this enum
133     * set, which is empty prior to the call.
134     */
135    abstract void addAll();
136
137    /**
138     * Creates an enum set with the same element type as the specified enum
139     * set, initially containing the same elements (if any).
140     *
141     * @param s the enum set from which to initialize this enum set
142     * @throws NullPointerException if <tt>s</tt> is null
143     */
144    public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) {
145        return s.clone();
146    }
147
148    /**
149     * Creates an enum set initialized from the specified collection.  If
150     * the specified collection is an <tt>EnumSet</tt> instance, this static
151     * factory method behaves identically to {@link #copyOf(EnumSet)}.
152     * Otherwise, the specified collection must contain at least one element
153     * (in order to determine the new enum set's element type).
154     *
155     * @param c the collection from which to initialize this enum set
156     * @throws IllegalArgumentException if <tt>c</tt> is not an
157     *     <tt>EnumSet</tt> instance and contains no elements
158     * @throws NullPointerException if <tt>c</tt> is null
159     */
160    public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) {
161        if (c instanceof EnumSet) {
162            return ((EnumSet<E>)c).clone();
163        } else {
164            if (c.isEmpty())
165                throw new IllegalArgumentException("Collection is empty");
166            Iterator<E> i = c.iterator();
167            E first = i.next();
168            EnumSet<E> result = EnumSet.of(first);
169            while (i.hasNext())
170                result.add(i.next());
171            return result;
172        }
173    }
174
175    /**
176     * Creates an enum set with the same element type as the specified enum
177     * set, initially containing all the elements of this type that are
178     * <i>not</i> contained in the specified set.
179     *
180     * @param s the enum set from whose complement to initialize this enum set
181     * @throws NullPointerException if <tt>s</tt> is null
182     */
183    public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) {
184        EnumSet<E> result = copyOf(s);
185        result.complement();
186        return result;
187    }
188
189    /**
190     * Creates an enum set initially containing the specified element.
191     *
192     * Overloadings of this method exist to initialize an enum set with
193     * one through five elements.  A sixth overloading is provided that
194     * uses the varargs feature.  This overloading may be used to create
195     * an enum set initially containing an arbitrary number of elements, but
196     * is likely to run slower than the overloadings that do not use varargs.
197     *
198     * @param e the element that this set is to contain initially
199     * @throws NullPointerException if <tt>e</tt> is null
200     * @return an enum set initially containing the specified element
201     */
202    public static <E extends Enum<E>> EnumSet<E> of(E e) {
203        EnumSet<E> result = noneOf(e.getDeclaringClass());
204        result.add(e);
205        return result;
206    }
207
208    /**
209     * Creates an enum set initially containing the specified elements.
210     *
211     * Overloadings of this method exist to initialize an enum set with
212     * one through five elements.  A sixth overloading is provided that
213     * uses the varargs feature.  This overloading may be used to create
214     * an enum set initially containing an arbitrary number of elements, but
215     * is likely to run slower than the overloadings that do not use varargs.
216     *
217     * @param e1 an element that this set is to contain initially
218     * @param e2 another element that this set is to contain initially
219     * @throws NullPointerException if any parameters are null
220     * @return an enum set initially containing the specified elements
221     */
222    public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) {
223        EnumSet<E> result = noneOf(e1.getDeclaringClass());
224        result.add(e1);
225        result.add(e2);
226        return result;
227    }
228
229    /**
230     * Creates an enum set initially containing the specified elements.
231     *
232     * Overloadings of this method exist to initialize an enum set with
233     * one through five elements.  A sixth overloading is provided that
234     * uses the varargs feature.  This overloading may be used to create
235     * an enum set initially containing an arbitrary number of elements, but
236     * is likely to run slower than the overloadings that do not use varargs.
237     *
238     * @param e1 an element that this set is to contain initially
239     * @param e2 another element that this set is to contain initially
240     * @param e3 another element that this set is to contain initially
241     * @throws NullPointerException if any parameters are null
242     * @return an enum set initially containing the specified elements
243     */
244    public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) {
245        EnumSet<E> result = noneOf(e1.getDeclaringClass());
246        result.add(e1);
247        result.add(e2);
248        result.add(e3);
249        return result;
250    }
251
252    /**
253     * Creates an enum set initially containing the specified elements.
254     *
255     * Overloadings of this method exist to initialize an enum set with
256     * one through five elements.  A sixth overloading is provided that
257     * uses the varargs feature.  This overloading may be used to create
258     * an enum set initially containing an arbitrary number of elements, but
259     * is likely to run slower than the overloadings that do not use varargs.
260     *
261     * @param e1 an element that this set is to contain initially
262     * @param e2 another element that this set is to contain initially
263     * @param e3 another element that this set is to contain initially
264     * @param e4 another element that this set is to contain initially
265     * @throws NullPointerException if any parameters are null
266     * @return an enum set initially containing the specified elements
267     */
268    public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) {
269        EnumSet<E> result = noneOf(e1.getDeclaringClass());
270        result.add(e1);
271        result.add(e2);
272        result.add(e3);
273        result.add(e4);
274        return result;
275    }
276
277    /**
278     * Creates an enum set initially containing the specified elements.
279     *
280     * Overloadings of this method exist to initialize an enum set with
281     * one through five elements.  A sixth overloading is provided that
282     * uses the varargs feature.  This overloading may be used to create
283     * an enum set initially containing an arbitrary number of elements, but
284     * is likely to run slower than the overloadings that do not use varargs.
285     *
286     * @param e1 an element that this set is to contain initially
287     * @param e2 another element that this set is to contain initially
288     * @param e3 another element that this set is to contain initially
289     * @param e4 another element that this set is to contain initially
290     * @param e5 another element that this set is to contain initially
291     * @throws NullPointerException if any parameters are null
292     * @return an enum set initially containing the specified elements
293     */
294    public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4,
295                                                    E e5)
296    {
297        EnumSet<E> result = noneOf(e1.getDeclaringClass());
298        result.add(e1);
299        result.add(e2);
300        result.add(e3);
301        result.add(e4);
302        result.add(e5);
303        return result;
304    }
305
306    /**
307     * Creates an enum set initially containing the specified elements.
308     * This factory, whose parameter list uses the varargs feature, may
309     * be used to create an enum set initially containing an arbitrary
310     * number of elements, but it is likely to run slower than the overloadings
311     * that do not use varargs.
312     *
313     * @param first an element that the set is to contain initially
314     * @param rest the remaining elements the set is to contain initially
315     * @throws NullPointerException if any of the specified elements are null,
316     *     or if <tt>rest</tt> is null
317     * @return an enum set initially containing the specified elements
318     */
319    @SafeVarargs
320    public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) {
321        EnumSet<E> result = noneOf(first.getDeclaringClass());
322        result.add(first);
323        for (E e : rest)
324            result.add(e);
325        return result;
326    }
327
328    /**
329     * Creates an enum set initially containing all of the elements in the
330     * range defined by the two specified endpoints.  The returned set will
331     * contain the endpoints themselves, which may be identical but must not
332     * be out of order.
333     *
334     * @param from the first element in the range
335     * @param to the last element in the range
336     * @throws NullPointerException if {@code from} or {@code to} are null
337     * @throws IllegalArgumentException if {@code from.compareTo(to) > 0}
338     * @return an enum set initially containing all of the elements in the
339     *         range defined by the two specified endpoints
340     */
341    public static <E extends Enum<E>> EnumSet<E> range(E from, E to) {
342        if (from.compareTo(to) > 0)
343            throw new IllegalArgumentException(from + " > " + to);
344        EnumSet<E> result = noneOf(from.getDeclaringClass());
345        result.addRange(from, to);
346        return result;
347    }
348
349    /**
350     * Adds the specified range to this enum set, which is empty prior
351     * to the call.
352     */
353    abstract void addRange(E from, E to);
354
355    /**
356     * Returns a copy of this set.
357     *
358     * @return a copy of this set
359     */
360    public EnumSet<E> clone() {
361        try {
362            return (EnumSet<E>) super.clone();
363        } catch(CloneNotSupportedException e) {
364            throw new AssertionError(e);
365        }
366    }
367
368    /**
369     * Complements the contents of this enum set.
370     */
371    abstract void complement();
372
373    /**
374     * Throws an exception if e is not of the correct type for this enum set.
375     */
376    final void typeCheck(E e) {
377        Class eClass = e.getClass();
378        if (eClass != elementType && eClass.getSuperclass() != elementType)
379            throw new ClassCastException(eClass + " != " + elementType);
380    }
381
382    /**
383     * Returns all of the values comprising E.
384     * The result is uncloned, cached, and shared by all callers.
385     */
386    private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) {
387        // Android-changed: Use JavaLangAccess directly instead of going via
388        // SharedSecrets.
389        return java.lang.JavaLangAccess.getEnumConstantsShared(elementType);
390    }
391
392    /**
393     * This class is used to serialize all EnumSet instances, regardless of
394     * implementation type.  It captures their "logical contents" and they
395     * are reconstructed using public static factories.  This is necessary
396     * to ensure that the existence of a particular implementation type is
397     * an implementation detail.
398     *
399     * @serial include
400     */
401    private static class SerializationProxy <E extends Enum<E>>
402        implements java.io.Serializable
403    {
404        /**
405         * The element type of this enum set.
406         *
407         * @serial
408         */
409        private final Class<E> elementType;
410
411        /**
412         * The elements contained in this enum set.
413         *
414         * @serial
415         */
416        private final Enum[] elements;
417
418        SerializationProxy(EnumSet<E> set) {
419            elementType = set.elementType;
420            elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY);
421        }
422
423        private Object readResolve() {
424            EnumSet<E> result = EnumSet.noneOf(elementType);
425            for (Enum e : elements)
426                result.add((E)e);
427            return result;
428        }
429
430        private static final long serialVersionUID = 362491234563181265L;
431    }
432
433    Object writeReplace() {
434        return new SerializationProxy<>(this);
435    }
436
437    // readObject method for the serialization proxy pattern
438    // See Effective Java, Second Ed., Item 78.
439    private void readObject(java.io.ObjectInputStream stream)
440        throws java.io.InvalidObjectException {
441        throw new java.io.InvalidObjectException("Proxy required");
442    }
443}
444