KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > EnumSet


1 /*
2  * @(#)EnumSet.java 1.10 04/05/28
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util;
9
10 /**
11  * A specialized {@link Set} implementation for use with enum types. All of
12  * the elements in an enum set must come from a single enum type that is
13  * specified, explicitly or implicitly, when the set is created. Enum sets
14  * are represented internally as bit vectors. This representation is
15  * extremely compact and efficient. The space and time performance of this
16  * class should be good enough to allow its use as a high-quality, typesafe
17  * alternative to traditional <tt>int</tt>-based "bit flags." Even bulk
18  * operations (such as <tt>containsAll</tt> and <tt>retainAll</tt>) should
19  * run very quickly if the specified collection is also an enum set.
20  *
21  * <p>The iterator returned by the <tt>iterator</tt>method traverses the
22  * elements in their <i>natural order</i> (the order in which the enum
23  * constants are declared). The returned iterator is <i>weakly
24  * consistent</i>: it will never throw {@link ConcurrentModificationException}
25  * and it may or may not show the effects of any modifications to the set that
26  * occur while the iteration is in progress.
27  *
28  * <p>Null elements are not permitted. Attempts to insert a null element
29  * will throw {@link NullPointerException}. Attempts to test for the
30  * presence of a null element or to remove one will, however, function
31  * properly.
32  *
33  * <P>Like most collection implementations <tt>EnumSet</tt> is not
34  * synchronized. If multiple threads access an enum set concurrently, and at
35  * least one of the threads modifies the set, it should be synchronized
36  * externally. This is typically accomplished by synchronizing on some
37  * object that naturally encapsulates the enum set. If no such object exists,
38  * the set should be "wrapped" using the {@link Collections#synchronizedSet}
39  * method. This is best done at creation time, to prevent accidental
40  * unsynchronized access:
41  *
42  * <pre>
43  * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(Foo.class));
44  * </pre>
45  *
46  * <p>Implementation note: All basic operations execute in constant time.
47  * They are likely (though not guaranteed) to be much faster than their
48  * {@link HashSet} counterparts. Even bulk operations, such as {@link
49  * #addAll} and {@link #removeAll} execute in constant time if the
50  * parameter is another <tt>EnumSet</tt> instance.
51  *
52  * <p>This class is a member of the
53  * <a HREF="{@docRoot}/../guide/collections/index.html">
54  * Java Collections Framework</a>.
55  *
56  * @author Josh Bloch
57  * @version 1.10, 05/28/04
58  * @since 1.5
59  * @see EnumMap
60  * @serial exclude
61  */

62 public abstract class EnumSet<E extends Enum JavaDoc<E>> extends AbstractSet JavaDoc<E>
63     implements Cloneable JavaDoc, java.io.Serializable JavaDoc
64 {
65     /**
66      * The class of all the elements of this set.
67      */

68     final Class JavaDoc<E> elementType;
69
70     /**
71      * All of the values comprising T. (Cached for performance.)
72      */

73     final Enum JavaDoc[] universe;
74
75     private static Enum JavaDoc[] ZERO_LENGTH_ENUM_ARRAY = new Enum JavaDoc[0];
76
77     EnumSet(Class JavaDoc<E>elementType, Enum JavaDoc[] universe) {
78         this.elementType = elementType;
79         this.universe = universe;
80     }
81
82     /**
83      * Creates an empty enum set with the specified element type.
84      *
85      * @param elementType the class object of the element type for this enum
86      * set
87      * @throws NullPointerException if <tt>elementType</tt> is null
88      */

89     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> noneOf(Class JavaDoc<E> elementType) {
90         Enum JavaDoc[] universe = elementType.getEnumConstants();
91         if (universe == null)
92             throw new ClassCastException JavaDoc(elementType + " not an enum");
93
94         if (universe.length <= 64)
95             return new RegularEnumSet JavaDoc<E>(elementType, universe);
96         else
97             return new JumboEnumSet JavaDoc<E>(elementType, universe);
98     }
99
100     /**
101      * Creates an enum set containing all of the elements in the specified
102      * element type.
103      *
104      * @param elementType the class object of the element type for this enum
105      * set
106      * @throws NullPointerException if <tt>elementType</tt> is null
107      */

108     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> allOf(Class JavaDoc<E> elementType) {
109         EnumSet JavaDoc<E> result = noneOf(elementType);
110         result.addAll();
111         return result;
112     }
113
114     /**
115      * Adds all of the elements from the appropriate enum type to this enum
116      * set, which is empty prior to the call.
117      */

118     abstract void addAll();
119
120     /**
121      * Creates an enum set with the same element type as the specified enum
122      * set, initially containing the same elements (if any).
123      *
124      * @param s the enum set from which to initialize this enum set
125      * @throws NullPointerException if <tt>s</tt> is null
126      */

127     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> copyOf(EnumSet JavaDoc<E> s) {
128         return s.clone();
129     }
130
131     /**
132      * Creates an enum set initialized from the specified collection. If
133      * the specified collection is an <tt>EnumSet</tt> instance, this static
134      * factory method behaves identically to {@link #copyOf(EnumSet)}.
135      * Otherwise, the specified collection must contain at least one element
136      * (in order to determine the new enum set's element type).
137      *
138      * @param c the collection from which to initialize this enum set
139      * @throws IllegalArgumentException if <tt>c</tt> is not an
140      * <tt>EnumSet</tt> instance and contains no elements
141      * @throws NullPointerException if <tt>c</tt> is null
142      */

143     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> copyOf(Collection JavaDoc<E> c) {
144         if (c instanceof EnumSet JavaDoc) {
145             return ((EnumSet JavaDoc<E>)c).clone();
146         } else {
147             if (c.isEmpty())
148                 throw new IllegalArgumentException JavaDoc("Collection is empty");
149             Iterator JavaDoc<E> i = c.iterator();
150             E first = i.next();
151             EnumSet JavaDoc<E> result = EnumSet.of(first);
152             while (i.hasNext())
153                 result.add(i.next());
154             return result;
155         }
156     }
157
158     /**
159      * Creates an enum set with the same element type as the specified enum
160      * set, initially containing all the elements of this type that are
161      * <i>not</i> contained in the specified set.
162      *
163      * @param s the enum set from whose complement to initialize this enum set
164      * @throws NullPointerException if <tt>s</tt> is null
165      */

166     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> complementOf(EnumSet JavaDoc<E> s) {
167         EnumSet JavaDoc<E> result = copyOf(s);
168         result.complement();
169         return result;
170     }
171
172     /**
173      * Creates an enum set initially containing the specified element.
174      *
175      * Overloadings of this method exist to initialize an enum set with
176      * one through five elements. A sixth overloading is provided that
177      * uses the varargs feature. This overloading may be used to create an
178      * an enum set initially containing an arbitrary number of elements, but
179      * is likely to run slower than the overloadings that do not use varargs.
180      *
181      * @param e the element that this set is to contain initially
182      * @throws NullPointerException if <tt>e</tt> is null
183      * @return an enum set initially containing the specified element
184      */

185     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> of(E e) {
186         EnumSet JavaDoc<E> result = noneOf(e.getDeclaringClass());
187         result.add(e);
188         return result;
189     }
190
191     /**
192      * Creates an enum set initially containing the specified elements.
193      *
194      * Overloadings of this method exist to initialize an enum set with
195      * one through five elements. A sixth overloading is provided that
196      * uses the varargs feature. This overloading may be used to create an
197      * an enum set initially containing an arbitrary number of elements, but
198      * is likely to run slower than the overloadings that do not use varargs.
199      *
200      * @param e1 an element that this set is to contain initially
201      * @param e2 another element that this set is to contain initially
202      * @throws NullPointerException if any parameters are null
203      * @return an enum set initially containing the specified elements
204      */

205     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> of(E e1, E e2) {
206         EnumSet JavaDoc<E> result = noneOf(e1.getDeclaringClass());
207         result.add(e1);
208         result.add(e2);
209         return result;
210     }
211
212     /**
213      * Creates an enum set initially containing the specified elements.
214      *
215      * Overloadings of this method exist to initialize an enum set with
216      * one through five elements. A sixth overloading is provided that
217      * uses the varargs feature. This overloading may be used to create an
218      * an enum set initially containing an arbitrary number of elements, but
219      * is likely to run slower than the overloadings that do not use varargs.
220      *
221      * @param e1 an element that this set is to contain initially
222      * @param e2 another element that this set is to contain initially
223      * @param e3 another element that this set is to contain initially
224      * @throws NullPointerException if any parameters are null
225      * @return an enum set initially containing the specified elements
226      */

227     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> of(E e1, E e2, E e3) {
228         EnumSet JavaDoc<E> result = noneOf(e1.getDeclaringClass());
229         result.add(e1);
230         result.add(e2);
231         result.add(e3);
232         return result;
233     }
234
235     /**
236      * Creates an enum set initially containing the specified elements.
237      *
238      * Overloadings of this method exist to initialize an enum set with
239      * one through five elements. A sixth overloading is provided that
240      * uses the varargs feature. This overloading may be used to create an
241      * an enum set initially containing an arbitrary number of elements, but
242      * is likely to run slower than the overloadings that do not use varargs.
243      *
244      * @param e1 an element that this set is to contain initially
245      * @param e2 another element that this set is to contain initially
246      * @param e3 another element that this set is to contain initially
247      * @param e4 another element that this set is to contain initially
248      * @throws NullPointerException if any parameters are null
249      * @return an enum set initially containing the specified elements
250      */

251     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> of(E e1, E e2, E e3, E e4) {
252         EnumSet JavaDoc<E> result = noneOf(e1.getDeclaringClass());
253         result.add(e1);
254         result.add(e2);
255         result.add(e3);
256         result.add(e4);
257         return result;
258     }
259
260     /**
261      * Creates an enum set initially containing the specified elements.
262      *
263      * Overloadings of this method exist to initialize an enum set with
264      * one through five elements. A sixth overloading is provided that
265      * uses the varargs feature. This overloading may be used to create an
266      * an enum set initially containing an arbitrary number of elements, but
267      * is likely to run slower than the overloadings that do not use varargs.
268      *
269      * @param e1 an element that this set is to contain initially
270      * @param e2 another element that this set is to contain initially
271      * @param e3 another element that this set is to contain initially
272      * @param e4 another element that this set is to contain initially
273      * @param e5 another element that this set is to contain initially
274      * @throws NullPointerException if any parameters are null
275      * @return an enum set initially containing the specified elements
276      */

277     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> of(E e1, E e2, E e3, E e4,
278                                                     E e5)
279     {
280         EnumSet JavaDoc<E> result = noneOf(e1.getDeclaringClass());
281         result.add(e1);
282         result.add(e2);
283         result.add(e3);
284         result.add(e4);
285         result.add(e5);
286         return result;
287     }
288
289     /**
290      * Creates an enum set initially containing the specified elements.
291      * This factory, whose parameter list uses the varargs feature, may
292      * be used to create an enum set initially containing an arbitrary
293      * number of elements, but it is likely to run slower than the overloadings
294      * that do not use varargs.
295      *
296      * @param first an element that the set is to contain initially
297      * @param rest the remaining elements the set is to contain initially
298      * @throws NullPointerException if any of the specified elements are null,
299      * or if <tt>rest</tt> is null
300      * @return an enum set initially containing the specified elements
301      */

302     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> of(E first, E... rest) {
303         EnumSet JavaDoc<E> result = noneOf(first.getDeclaringClass());
304         result.add(first);
305         for (E e : rest)
306             result.add(e);
307         return result;
308     }
309
310     /**
311      * Creates an enum set initially containing all of the elements in the
312      * range defined by the two specified endpoints. The returned set will
313      * contain the endpoints themselves, which may be identical but must not
314      * be out of order.
315      *
316      * @param from the first element in the range
317      * @param to the last element in the range
318      * @throws NullPointerException if <tt>first</tt> or <tt>last</tt> are
319      * null
320      * @throws IllegalArgumentException if <tt>first.compareTo(last) &gt; 0</tt>
321      * @return an enum set initially containing all of the elements in the
322      * range defined by the two specified endpoints
323      */

324     public static <E extends Enum JavaDoc<E>> EnumSet JavaDoc<E> range(E from, E to) {
325         if (from.compareTo(to) > 0)
326             throw new IllegalArgumentException JavaDoc(from + " > " + to);
327         EnumSet JavaDoc<E> result = noneOf(from.getDeclaringClass());
328         result.addRange(from, to);
329         return result;
330     }
331
332     /**
333      * Adds the specified range to this enum set, which is empty prior
334      * to the call.
335      */

336     abstract void addRange(E from, E to);
337
338     /**
339      * Returns a copy of this set.
340      *
341      * @return a copy of this set.
342      */

343     public EnumSet JavaDoc<E> clone() {
344         try {
345             return (EnumSet JavaDoc<E>) super.clone();
346         } catch(CloneNotSupportedException JavaDoc e) {
347             throw new AssertionError JavaDoc(e);
348         }
349     }
350
351     /**
352      * Complements the contents of this enum set.
353      */

354     abstract void complement();
355
356     /**
357      * Throws an exception if e is not of the correct type for this enum set.
358      */

359     final void typeCheck(E e) {
360         Class JavaDoc eClass = e.getClass();
361         if (eClass != elementType && eClass.getSuperclass() != elementType)
362             throw new ClassCastException JavaDoc(eClass + " != " + elementType);
363     }
364
365     /**
366      * This class is used to serialize all EnumSet instances, regardless of
367      * implementation type. It captures their "logical contents" and they
368      * are reconstructed using public static factories. This is necessary
369      * to ensure that the existence of a particular implementation type is
370      * an implementation detail.
371      *
372      * @serial include
373      */

374     private static class SerializationProxy <E extends Enum JavaDoc<E>>
375         implements java.io.Serializable JavaDoc
376     {
377         /**
378          * The element type of this enum set.
379          *
380          * @serial
381          */

382         private final Class JavaDoc<E> elementType;
383
384         /**
385          * The elements contained in this enum set.
386          *
387          * @serial
388          */

389         private final Enum JavaDoc[] elements;
390
391         SerializationProxy(EnumSet JavaDoc<E> set) {
392             elementType = set.elementType;
393             elements = (Enum JavaDoc[]) set.toArray(ZERO_LENGTH_ENUM_ARRAY);
394         }
395
396         private Object JavaDoc readResolve() {
397             EnumSet JavaDoc<E> result = EnumSet.noneOf(elementType);
398             for (Enum JavaDoc e : elements)
399                 result.add((E)e);
400             return result;
401         }
402
403         private static final long serialVersionUID = 362491234563181265L;
404     }
405
406     Object JavaDoc writeReplace() {
407         return new SerializationProxy<E>(this);
408     }
409 }
410
Popular Tags