AbstractCollection.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /* AbstractCollection.java -- Abstract implementation of most of Collection
  2. Copyright (C) 1998, 2000, 2001, 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 gnu.java.lang.CPStringBuilder;
  33. import java.lang.reflect.Array;
  34. /**
  35. * A basic implementation of most of the methods in the Collection interface to
  36. * make it easier to create a collection. To create an unmodifiable Collection,
  37. * just subclass AbstractCollection and provide implementations of the
  38. * iterator() and size() methods. The Iterator returned by iterator() need only
  39. * provide implementations of hasNext() and next() (that is, it may throw an
  40. * UnsupportedOperationException if remove() is called). To create a modifiable
  41. * Collection, you must in addition provide an implementation of the
  42. * add(Object) method and the Iterator returned by iterator() must provide an
  43. * implementation of remove(). Other methods should be overridden if the
  44. * backing data structure allows for a more efficient implementation. The
  45. * precise implementation used by AbstractCollection is documented, so that
  46. * subclasses can tell which methods could be implemented more efficiently.
  47. * <p>
  48. *
  49. * The programmer should provide a no-argument constructor, and one that
  50. * accepts another Collection, as recommended by the Collection interface.
  51. * Unfortunately, there is no way to enforce this in Java.
  52. *
  53. * @author Original author unknown
  54. * @author Bryce McKinlay
  55. * @author Eric Blake (ebb9@email.byu.edu)
  56. * @author Tom Tromey (tromey@redhat.com)
  57. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  58. * @see Collection
  59. * @see AbstractSet
  60. * @see AbstractList
  61. * @since 1.2
  62. * @status updated to 1.4
  63. */
  64. public abstract class AbstractCollection<E>
  65. implements Collection<E>, Iterable<E>
  66. {
  67. /**
  68. * The main constructor, for use by subclasses.
  69. */
  70. protected AbstractCollection()
  71. {
  72. }
  73. /**
  74. * Return an Iterator over this collection. The iterator must provide the
  75. * hasNext and next methods and should in addition provide remove if the
  76. * collection is modifiable.
  77. *
  78. * @return an iterator
  79. */
  80. public abstract Iterator<E> iterator();
  81. /**
  82. * Return the number of elements in this collection. If there are more than
  83. * Integer.MAX_VALUE elements, return Integer.MAX_VALUE.
  84. *
  85. * @return the size
  86. */
  87. public abstract int size();
  88. /**
  89. * Add an object to the collection (optional operation). This implementation
  90. * always throws an UnsupportedOperationException - it should be
  91. * overridden if the collection is to be modifiable. If the collection
  92. * does not accept duplicates, simply return false. Collections may specify
  93. * limitations on what may be added.
  94. *
  95. * @param o the object to add
  96. * @return true if the add operation caused the Collection to change
  97. * @throws UnsupportedOperationException if the add operation is not
  98. * supported on this collection
  99. * @throws NullPointerException if the collection does not support null
  100. * @throws ClassCastException if the object is of the wrong type
  101. * @throws IllegalArgumentException if some aspect of the object prevents
  102. * it from being added
  103. */
  104. public boolean add(E o)
  105. {
  106. throw new UnsupportedOperationException();
  107. }
  108. /**
  109. * Add all the elements of a given collection to this collection (optional
  110. * operation). This implementation obtains an Iterator over the given
  111. * collection and iterates over it, adding each element with the
  112. * add(Object) method (thus this method will fail with an
  113. * UnsupportedOperationException if the add method does). The behavior is
  114. * unspecified if the specified collection is modified during the iteration,
  115. * including the special case of trying addAll(this) on a non-empty
  116. * collection.
  117. *
  118. * @param c the collection to add the elements of to this collection
  119. * @return true if the add operation caused the Collection to change
  120. * @throws UnsupportedOperationException if the add operation is not
  121. * supported on this collection
  122. * @throws NullPointerException if the specified collection is null
  123. * @throws ClassCastException if the type of any element in c is
  124. * not a valid type for addition.
  125. * @throws IllegalArgumentException if some aspect of any element
  126. * in c prevents it being added.
  127. * @throws NullPointerException if any element in c is null and this
  128. * collection doesn't allow null values.
  129. * @see #add(Object)
  130. */
  131. public boolean addAll(Collection<? extends E> c)
  132. {
  133. Iterator<? extends E> itr = c.iterator();
  134. boolean modified = false;
  135. int pos = c.size();
  136. while (--pos >= 0)
  137. modified |= add(itr.next());
  138. return modified;
  139. }
  140. /**
  141. * Remove all elements from the collection (optional operation). This
  142. * implementation obtains an iterator over the collection and calls next
  143. * and remove on it repeatedly (thus this method will fail with an
  144. * UnsupportedOperationException if the Iterator's remove method does)
  145. * until there are no more elements to remove.
  146. * Many implementations will have a faster way of doing this.
  147. *
  148. * @throws UnsupportedOperationException if the Iterator returned by
  149. * iterator does not provide an implementation of remove
  150. * @see Iterator#remove()
  151. */
  152. public void clear()
  153. {
  154. Iterator<E> itr = iterator();
  155. int pos = size();
  156. while (--pos >= 0)
  157. {
  158. itr.next();
  159. itr.remove();
  160. }
  161. }
  162. /**
  163. * Test whether this collection contains a given object. That is, if the
  164. * collection has an element e such that (o == null ? e == null :
  165. * o.equals(e)). This implementation obtains an iterator over the collection
  166. * and iterates over it, testing each element for equality with the given
  167. * object. If it is equal, true is returned. Otherwise false is returned when
  168. * the end of the collection is reached.
  169. *
  170. * @param o the object to remove from this collection
  171. * @return true if this collection contains an object equal to o
  172. */
  173. public boolean contains(Object o)
  174. {
  175. Iterator<E> itr = iterator();
  176. int pos = size();
  177. while (--pos >= 0)
  178. if (equals(o, itr.next()))
  179. return true;
  180. return false;
  181. }
  182. /**
  183. * Tests whether this collection contains all the elements in a given
  184. * collection. This implementation iterates over the given collection,
  185. * testing whether each element is contained in this collection. If any one
  186. * is not, false is returned. Otherwise true is returned.
  187. *
  188. * @param c the collection to test against
  189. * @return true if this collection contains all the elements in the given
  190. * collection
  191. * @throws NullPointerException if the given collection is null
  192. * @see #contains(Object)
  193. */
  194. public boolean containsAll(Collection<?> c)
  195. {
  196. Iterator<?> itr = c.iterator();
  197. int pos = c.size();
  198. while (--pos >= 0)
  199. if (!contains(itr.next()))
  200. return false;
  201. return true;
  202. }
  203. /**
  204. * Test whether this collection is empty. This implementation returns
  205. * size() == 0.
  206. *
  207. * @return true if this collection is empty.
  208. * @see #size()
  209. */
  210. public boolean isEmpty()
  211. {
  212. return size() == 0;
  213. }
  214. /**
  215. * Remove a single instance of an object from this collection (optional
  216. * operation). That is, remove one element e such that
  217. * <code>(o == null ? e == null : o.equals(e))</code>, if such an element
  218. * exists. This implementation obtains an iterator over the collection
  219. * and iterates over it, testing each element for equality with the given
  220. * object. If it is equal, it is removed by the iterator's remove method
  221. * (thus this method will fail with an UnsupportedOperationException if
  222. * the Iterator's remove method does). After the first element has been
  223. * removed, true is returned; if the end of the collection is reached, false
  224. * is returned.
  225. *
  226. * @param o the object to remove from this collection
  227. * @return true if the remove operation caused the Collection to change, or
  228. * equivalently if the collection did contain o.
  229. * @throws UnsupportedOperationException if this collection's Iterator
  230. * does not support the remove method
  231. * @see Iterator#remove()
  232. */
  233. public boolean remove(Object o)
  234. {
  235. Iterator<E> itr = iterator();
  236. int pos = size();
  237. while (--pos >= 0)
  238. if (equals(o, itr.next()))
  239. {
  240. itr.remove();
  241. return true;
  242. }
  243. return false;
  244. }
  245. /**
  246. * Remove from this collection all its elements that are contained in a given
  247. * collection (optional operation). This implementation iterates over this
  248. * collection, and for each element tests if it is contained in the given
  249. * collection. If so, it is removed by the Iterator's remove method (thus
  250. * this method will fail with an UnsupportedOperationException if the
  251. * Iterator's remove method does).
  252. *
  253. * @param c the collection to remove the elements of
  254. * @return true if the remove operation caused the Collection to change
  255. * @throws UnsupportedOperationException if this collection's Iterator
  256. * does not support the remove method
  257. * @throws NullPointerException if the collection, c, is null.
  258. * @see Iterator#remove()
  259. */
  260. public boolean removeAll(Collection<?> c)
  261. {
  262. return removeAllInternal(c);
  263. }
  264. /**
  265. * Remove from this collection all its elements that are contained in a given
  266. * collection (optional operation). This implementation iterates over this
  267. * collection, and for each element tests if it is contained in the given
  268. * collection. If so, it is removed by the Iterator's remove method (thus
  269. * this method will fail with an UnsupportedOperationException if the
  270. * Iterator's remove method does). This method is necessary for ArrayList,
  271. * which cannot publicly override removeAll but can optimize this call.
  272. *
  273. * @param c the collection to remove the elements of
  274. * @return true if the remove operation caused the Collection to change
  275. * @throws UnsupportedOperationException if this collection's Iterator
  276. * does not support the remove method
  277. * @throws NullPointerException if the collection, c, is null.
  278. * @see Iterator#remove()
  279. */
  280. // Package visible for use throughout java.util.
  281. boolean removeAllInternal(Collection<?> c)
  282. {
  283. Iterator<E> itr = iterator();
  284. boolean modified = false;
  285. int pos = size();
  286. while (--pos >= 0)
  287. if (c.contains(itr.next()))
  288. {
  289. itr.remove();
  290. modified = true;
  291. }
  292. return modified;
  293. }
  294. /**
  295. * Remove from this collection all its elements that are not contained in a
  296. * given collection (optional operation). This implementation iterates over
  297. * this collection, and for each element tests if it is contained in the
  298. * given collection. If not, it is removed by the Iterator's remove method
  299. * (thus this method will fail with an UnsupportedOperationException if
  300. * the Iterator's remove method does).
  301. *
  302. * @param c the collection to retain the elements of
  303. * @return true if the remove operation caused the Collection to change
  304. * @throws UnsupportedOperationException if this collection's Iterator
  305. * does not support the remove method
  306. * @throws NullPointerException if the collection, c, is null.
  307. * @see Iterator#remove()
  308. */
  309. public boolean retainAll(Collection<?> c)
  310. {
  311. return retainAllInternal(c);
  312. }
  313. /**
  314. * Remove from this collection all its elements that are not contained in a
  315. * given collection (optional operation). This implementation iterates over
  316. * this collection, and for each element tests if it is contained in the
  317. * given collection. If not, it is removed by the Iterator's remove method
  318. * (thus this method will fail with an UnsupportedOperationException if
  319. * the Iterator's remove method does). This method is necessary for
  320. * ArrayList, which cannot publicly override retainAll but can optimize
  321. * this call.
  322. *
  323. * @param c the collection to retain the elements of
  324. * @return true if the remove operation caused the Collection to change
  325. * @throws UnsupportedOperationException if this collection's Iterator
  326. * does not support the remove method
  327. * @throws NullPointerException if the collection, c, is null.
  328. * @see Iterator#remove()
  329. */
  330. // Package visible for use throughout java.util.
  331. boolean retainAllInternal(Collection<?> c)
  332. {
  333. Iterator<E> itr = iterator();
  334. boolean modified = false;
  335. int pos = size();
  336. while (--pos >= 0)
  337. if (!c.contains(itr.next()))
  338. {
  339. itr.remove();
  340. modified = true;
  341. }
  342. return modified;
  343. }
  344. /**
  345. * Return an array containing the elements of this collection. This
  346. * implementation creates an Object array of size size() and then iterates
  347. * over the collection, setting each element of the array from the value
  348. * returned by the iterator. The returned array is safe, and is not backed
  349. * by the collection.
  350. *
  351. * @return an array containing the elements of this collection
  352. */
  353. public Object[] toArray()
  354. {
  355. Iterator<E> itr = iterator();
  356. int size = size();
  357. Object[] a = new Object[size];
  358. for (int pos = 0; pos < size; pos++)
  359. a[pos] = itr.next();
  360. return a;
  361. }
  362. /**
  363. * Copy the collection into a given array if it will fit, or into a
  364. * dynamically created array of the same run-time type as the given array if
  365. * not. If there is space remaining in the array, the first element after the
  366. * end of the collection is set to null (this is only useful if the
  367. * collection is known to contain no null elements, however). This
  368. * implementation first tests whether the given array is large enough to hold
  369. * all the elements of the collection. If not, the reflection API is used to
  370. * allocate a new array of the same run-time type. Next an iterator is
  371. * obtained over the collection and the elements are placed in the array as
  372. * they are returned by the iterator. Finally the first spare element, if
  373. * any, of the array is set to null, and the created array is returned.
  374. * The returned array is safe; it is not backed by the collection. Note that
  375. * null may not mark the last element, if the collection allows null
  376. * elements.
  377. *
  378. * @param a the array to copy into, or of the correct run-time type
  379. * @return the array that was produced
  380. * @throws NullPointerException if the given array is null
  381. * @throws ArrayStoreException if the type of the array precludes holding
  382. * one of the elements of the Collection
  383. */
  384. public <T> T[] toArray(T[] a)
  385. {
  386. int size = size();
  387. if (a.length < size)
  388. a = (T[]) Array.newInstance(a.getClass().getComponentType(),
  389. size);
  390. else if (a.length > size)
  391. a[size] = null;
  392. Iterator<E> itr = iterator();
  393. for (int pos = 0; pos < size; pos++)
  394. a[pos] = (T) (itr.next());
  395. return a;
  396. }
  397. /**
  398. * Creates a String representation of the Collection. The string returned is
  399. * of the form "[a, b, ...]" where a and b etc are the results of calling
  400. * toString on the elements of the collection. This implementation obtains an
  401. * Iterator over the Collection and adds each element to a StringBuffer as it
  402. * is returned by the iterator. "<this>" is inserted when the collection
  403. * contains itself (only works for direct containment, not for collections
  404. * inside collections).
  405. *
  406. * @return a String representation of the Collection
  407. */
  408. public String toString()
  409. {
  410. Iterator itr = iterator();
  411. CPStringBuilder r = new CPStringBuilder("[");
  412. boolean hasNext = itr.hasNext();
  413. while (hasNext)
  414. {
  415. Object o = itr.next();
  416. if (o == this)
  417. r.append("<this>");
  418. else
  419. r.append(o);
  420. hasNext = itr.hasNext();
  421. if (hasNext)
  422. r.append(", ");
  423. }
  424. r.append("]");
  425. return r.toString();
  426. }
  427. /**
  428. * Compare two objects according to Collection semantics.
  429. *
  430. * @param o1 the first object
  431. * @param o2 the second object
  432. * @return o1 == null ? o2 == null : o1.equals(o2)
  433. */
  434. // Package visible for use throughout java.util.
  435. // It may be inlined since it is final.
  436. static final boolean equals(Object o1, Object o2)
  437. {
  438. return o1 == null ? o2 == null : o1.equals(o2);
  439. }
  440. /**
  441. * Hash an object according to Collection semantics.
  442. *
  443. * @param o the object to hash
  444. * @return o1 == null ? 0 : o1.hashCode()
  445. */
  446. // Package visible for use throughout java.util.
  447. // It may be inlined since it is final.
  448. static final int hashCode(Object o)
  449. {
  450. return o == null ? 0 : o.hashCode();
  451. }
  452. }