EnumSet.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /* EnumSet.java - Set of enum objects
  2. Copyright (C) 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import java.io.Serializable;
  33. /**
  34. * <p>
  35. * Provides an efficient mechanism for recording a set of enumeration
  36. * constants. As enumerations have a known set of possible values, certain
  37. * assumptions can be made when creating a set of constants. The maximum
  38. * size of the set will always be equal to the number of constants, and each
  39. * value will always be one of these constants. As a result, the set only needs
  40. * to store whether a particular constant is present or not rather than the
  41. * values themselves. Each constant can thus be represented by a single bit.
  42. * </p>
  43. * <p>
  44. * This class is designed to provide an alternative to using integer bit flags
  45. * by providing a typesafe {@link Collection} interface with an underlying
  46. * implementation that utilises the assumptions above to give an equivalent level
  47. * of efficiency. The values in a {@link EnumSet} must all be from the same
  48. * {@link Enum} type, which allows the contents to be packed into a bit vector.
  49. * A containment test is then simply a matter of inspecting the appropriate bit, while
  50. * addition involves setting the same. Such basic operations take place in constant
  51. * time.
  52. * </p>
  53. * <p>
  54. * The {@link Iterator} implementation traverses the values in the natural order
  55. * of the enumeration provided by each constant's {@link Enum#ordinal()}. It is
  56. * <emph>weakly consistent</emph> and will not throw a {@link ConcurrentModificationException}.
  57. * This means that concurrent changes to the set may or may not be noticeable during
  58. * traversal.
  59. * </p>
  60. * <p>
  61. * As is usual with most collections, the set is not synchronized by default. This
  62. * can be remedied by using the {@link Collections#synchronizedSet(Set)} method. Null
  63. * elements are not supported and attempts to add one will throw a {@link NullPointerException}.
  64. * </p>
  65. *
  66. * @author Tom Tromey (tromey@redhat.com)
  67. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  68. * @author Dalibor Topic (robilad@kaffe.org)
  69. * @since 1.5
  70. */
  71. // FIXME: serialization is special, uses SerializationProxy.
  72. // of(E e) is the 'bottom' method that creates a real EnumSet.
  73. public abstract class EnumSet<T extends Enum<T>>
  74. extends AbstractSet<T>
  75. implements Cloneable, Serializable
  76. {
  77. private static final long serialVersionUID = 4782406773684236311L;
  78. // These fields could go into the anonymous inner class in of(E),
  79. // complementOf would need to be refactored then, though.
  80. /**
  81. * The store which maintains the bits used to represent
  82. * the enumeration constants.
  83. */
  84. BitSet store;
  85. /**
  86. * The cardinality of the set (the current number
  87. * of bits set).
  88. */
  89. int cardinality;
  90. /**
  91. * The enumeration used by this set.
  92. */
  93. Class<T> enumClass;
  94. /**
  95. * Empty package-private constructor
  96. */
  97. EnumSet()
  98. {
  99. }
  100. /**
  101. * Returns a clone of the set.
  102. *
  103. * @return a clone of the set.
  104. */
  105. public EnumSet<T> clone()
  106. {
  107. EnumSet<T> r;
  108. try
  109. {
  110. r = (EnumSet<T>) super.clone();
  111. }
  112. catch (CloneNotSupportedException _)
  113. {
  114. /* Can't happen */
  115. return null;
  116. }
  117. r.store = (BitSet) store.clone();
  118. return r;
  119. }
  120. /**
  121. * Returns a set for the given enumeration type where
  122. * all the constants are present.
  123. *
  124. * @param eltType the type of enumeration to use for the set.
  125. * @return an {@link EnumSet} with all the bits set.
  126. * @throws NullPointerException if the element type is <code>null</code>.
  127. */
  128. public static <T extends Enum<T>> EnumSet<T> allOf(Class<T> eltType)
  129. {
  130. // create an EnumSet from the list of values of the type
  131. return copyOf(Arrays.asList(eltType.getEnumConstants()));
  132. }
  133. /**
  134. * Returns a set for the given enumeration type where
  135. * none of the constants are present.
  136. *
  137. * @param eltType the type of enumeration to use for the set.
  138. * @return an {@link EnumSet} with none of the bits set.
  139. * @throws NullPointerException if the element type is <code>null</code>.
  140. */
  141. public static <T extends Enum<T>> EnumSet<T> noneOf(Class<T> eltType)
  142. {
  143. return complementOf(allOf(eltType));
  144. }
  145. /**
  146. * Returns a clone of the given set.
  147. *
  148. * @param other the set to clone.
  149. * @return an {@link EnumSet} that is a clone of the given set.
  150. * @throws NullPointerException if <code>other</code> is <code>null</code>.
  151. */
  152. public static <T extends Enum<T>> EnumSet<T> copyOf(EnumSet<T> other)
  153. {
  154. return other.clone();
  155. }
  156. /**
  157. * Creates an {@link EnumSet} using the contents of the given collection.
  158. * If the collection is also an {@link EnumSet}, this method works the
  159. * same as {@link #copyOf(EnumSet)}. Otherwise, the elements of the collection
  160. * are inspected and used to populate the new set.
  161. *
  162. * @param other the collection to use to populate the new set.
  163. * @return an {@link EnumSet} containing elements from the given collection.
  164. * @throws NullPointerException if <code>other</code> is <code>null</code>.
  165. * @throws IllegalArgumentException if the collection is empty.
  166. */
  167. public static <T extends Enum<T>> EnumSet<T> copyOf(Collection<T> other)
  168. {
  169. if (other instanceof EnumSet)
  170. return copyOf((EnumSet<T>) other);
  171. if (other.isEmpty())
  172. throw new IllegalArgumentException("Collection is empty");
  173. EnumSet<T> r = null;
  174. for (T val : other)
  175. {
  176. if (r == null)
  177. r = of(val);
  178. else
  179. r.add(val);
  180. }
  181. return r;
  182. }
  183. /**
  184. * Returns a set which is the inverse of the supplied set.
  185. * If a constant is present in the current set, it will not be
  186. * present in the new set and vice versa.
  187. *
  188. * @param other the set to provide the complement of.
  189. * @return an {@link EnumSet} which is the inverse of the current one.
  190. * @throws NullPointerException if <code>other</code> is <code>null</code>.
  191. */
  192. public static <T extends Enum<T>> EnumSet<T> complementOf(EnumSet<T> other)
  193. {
  194. EnumSet<T> r = other.clone();
  195. int numConstants = r.enumClass.getEnumConstants().length;
  196. r.store.flip(0, numConstants);
  197. r.cardinality = numConstants - other.cardinality;
  198. return r;
  199. }
  200. /**
  201. * Creates a new {@link EnumSet} populated with the given element.
  202. *
  203. * @param first the element to use to populate the new set.
  204. * @return an {@link EnumSet} containing the element.
  205. * @throws NullPointerException if <code>first</code> is <code>null</code>.
  206. */
  207. public static <T extends Enum<T>> EnumSet<T> of(T first)
  208. {
  209. EnumSet<T> r = new EnumSet<T>()
  210. {
  211. public boolean add(T val)
  212. {
  213. if (store.get(val.ordinal()))
  214. return false;
  215. store.set(val.ordinal());
  216. ++cardinality;
  217. return true;
  218. }
  219. public boolean addAll(Collection<? extends T> c)
  220. {
  221. boolean result = false;
  222. if (c instanceof EnumSet)
  223. {
  224. EnumSet<T> other = (EnumSet<T>) c;
  225. if (enumClass == other.enumClass)
  226. {
  227. store.or(other.store);
  228. int save = cardinality;
  229. cardinality = store.cardinality();
  230. result = save != cardinality;
  231. }
  232. }
  233. else
  234. {
  235. for (T val : c)
  236. {
  237. if (add (val))
  238. result = true;
  239. }
  240. }
  241. return result;
  242. }
  243. public void clear()
  244. {
  245. store.clear();
  246. cardinality = 0;
  247. }
  248. public boolean contains(Object o)
  249. {
  250. if (! (o instanceof Enum))
  251. return false;
  252. Enum<T> e = (Enum<T>) o;
  253. if (e.getDeclaringClass() != enumClass)
  254. return false;
  255. return store.get(e.ordinal());
  256. }
  257. public boolean containsAll(Collection<?> c)
  258. {
  259. if (c instanceof EnumSet)
  260. {
  261. EnumSet<T> other = (EnumSet<T>) c;
  262. if (enumClass == other.enumClass)
  263. return store.containsAll(other.store);
  264. return false;
  265. }
  266. return super.containsAll(c);
  267. }
  268. public Iterator<T> iterator()
  269. {
  270. return new Iterator<T>()
  271. {
  272. int next = -1;
  273. int count = 0;
  274. public boolean hasNext()
  275. {
  276. return count < cardinality;
  277. }
  278. public T next()
  279. {
  280. next = store.nextSetBit(next + 1);
  281. ++count;
  282. return enumClass.getEnumConstants()[next];
  283. }
  284. public void remove()
  285. {
  286. if (! store.get(next))
  287. {
  288. store.clear(next);
  289. --cardinality;
  290. }
  291. }
  292. };
  293. }
  294. public boolean remove(Object o)
  295. {
  296. if (! (o instanceof Enum))
  297. return false;
  298. Enum<T> e = (Enum<T>) o;
  299. if (e.getDeclaringClass() != enumClass)
  300. return false;
  301. store.clear(e.ordinal());
  302. --cardinality;
  303. return true;
  304. }
  305. public boolean removeAll(Collection<?> c)
  306. {
  307. if (c instanceof EnumSet)
  308. {
  309. EnumSet<T> other = (EnumSet<T>) c;
  310. if (enumClass != other.enumClass)
  311. return false;
  312. store.andNot(other.store);
  313. int save = cardinality;
  314. cardinality = store.cardinality();
  315. return save != cardinality;
  316. }
  317. return super.removeAll(c);
  318. }
  319. public boolean retainAll(Collection<?> c)
  320. {
  321. if (c instanceof EnumSet)
  322. {
  323. EnumSet<T> other = (EnumSet<T>) c;
  324. if (enumClass != other.enumClass)
  325. return false;
  326. store.and(other.store);
  327. int save = cardinality;
  328. cardinality = store.cardinality();
  329. return save != cardinality;
  330. }
  331. return super.retainAll(c);
  332. }
  333. public int size()
  334. {
  335. return cardinality;
  336. }
  337. };
  338. // initialize the class
  339. r.enumClass = first.getDeclaringClass();
  340. r.store = new BitSet(r.enumClass.getEnumConstants().length);
  341. r.add(first);
  342. return r;
  343. }
  344. /**
  345. * Creates a new {@link EnumSet} populated with the given two elements.
  346. *
  347. * @param first the first element to use to populate the new set.
  348. * @param second the second element to use.
  349. * @return an {@link EnumSet} containing the elements.
  350. * @throws NullPointerException if any of the parameters are <code>null</code>.
  351. */
  352. public static <T extends Enum<T>> EnumSet<T> of(T first, T second)
  353. {
  354. EnumSet<T> r = of(first);
  355. r.add(second);
  356. return r;
  357. }
  358. /**
  359. * Creates a new {@link EnumSet} populated with the given three elements.
  360. *
  361. * @param first the first element to use to populate the new set.
  362. * @param second the second element to use.
  363. * @param third the third element to use.
  364. * @return an {@link EnumSet} containing the elements.
  365. * @throws NullPointerException if any of the parameters are <code>null</code>.
  366. */
  367. public static <T extends Enum<T>> EnumSet<T> of(T first, T second, T third)
  368. {
  369. EnumSet<T> r = of(first, second);
  370. r.add(third);
  371. return r;
  372. }
  373. /**
  374. * Creates a new {@link EnumSet} populated with the given four elements.
  375. *
  376. * @param first the first element to use to populate the new set.
  377. * @param second the second element to use.
  378. * @param third the third element to use.
  379. * @param fourth the fourth element to use.
  380. * @return an {@link EnumSet} containing the elements.
  381. * @throws NullPointerException if any of the parameters are <code>null</code>.
  382. */
  383. public static <T extends Enum<T>> EnumSet<T> of(T first, T second, T third,
  384. T fourth)
  385. {
  386. EnumSet<T> r = of(first, second, third);
  387. r.add(fourth);
  388. return r;
  389. }
  390. /**
  391. * Creates a new {@link EnumSet} populated with the given five elements.
  392. *
  393. * @param first the first element to use to populate the new set.
  394. * @param second the second element to use.
  395. * @param third the third element to use.
  396. * @param fourth the fourth element to use.
  397. * @param fifth the fifth element to use.
  398. * @return an {@link EnumSet} containing the elements.
  399. * @throws NullPointerException if any of the parameters are <code>null</code>.
  400. */
  401. public static <T extends Enum<T>> EnumSet<T> of(T first, T second, T third,
  402. T fourth, T fifth)
  403. {
  404. EnumSet<T> r = of(first, second, third, fourth);
  405. r.add(fifth);
  406. return r;
  407. }
  408. /**
  409. * Creates a new {@link EnumSet} populated with the given elements.
  410. *
  411. * @param first the first element to use to populate the new set.
  412. * @param rest the other elements to use.
  413. * @return an {@link EnumSet} containing the elements.
  414. * @throws NullPointerException if any of the parameters are <code>null</code>.
  415. */
  416. public static <T extends Enum<T>> EnumSet<T> of(T first, T... rest)
  417. {
  418. EnumSet<T> r = noneOf(first.getDeclaringClass());
  419. r.add(first);
  420. for (T val : rest)
  421. r.add(val);
  422. return r;
  423. }
  424. /**
  425. * Creates a new {@link EnumSet} using the enumeration constants
  426. * starting from {@code from} and ending at {@code to} inclusive.
  427. * The two may be the same, but they must be in the correct order.
  428. * So giving the first constant twice would give a set with just that
  429. * constant set, while supplying the first and second constant will give
  430. * a set with those two elements. However, specifying the second as
  431. * the {@code from} element followed by an earlier element as the
  432. * {@code to} element will result in an error.
  433. *
  434. * @param from the element to start from.
  435. * @param to the element to end at (may be the same as {@code from}.
  436. * @return an {@link EnumSet} containing the specified range of elements.
  437. * @throws NullPointerException if any of the parameters are <code>null</code>.
  438. * @throws IllegalArgumentException if {@code first.compareTo(last) > 0}.
  439. */
  440. public static <T extends Enum<T>> EnumSet<T> range(T from, T to)
  441. {
  442. if (from.compareTo(to) > 0)
  443. throw new IllegalArgumentException();
  444. Class<T> type = from.getDeclaringClass();
  445. EnumSet<T> r = noneOf(type);
  446. T[] values = type.getEnumConstants();
  447. // skip over values until start of range is found
  448. int i = 0;
  449. while (from != values[i])
  450. i++;
  451. // add values until end of range is found
  452. while (to != values[i]) {
  453. r.add(values[i]);
  454. i++;
  455. }
  456. // add end of range
  457. r.add(to);
  458. return r;
  459. }
  460. }