LinkedList.java 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. /* LinkedList.java -- Linked list implementation of the List interface
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006 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.IOException;
  33. import java.io.ObjectInputStream;
  34. import java.io.ObjectOutputStream;
  35. import java.io.Serializable;
  36. import java.lang.reflect.Array;
  37. /**
  38. * Linked list implementation of the List interface. In addition to the
  39. * methods of the List interface, this class provides access to the first
  40. * and last list elements in O(1) time for easy stack, queue, or double-ended
  41. * queue (deque) creation. The list is doubly-linked, with traversal to a
  42. * given index starting from the end closest to the element.<p>
  43. *
  44. * LinkedList is not synchronized, so if you need multi-threaded access,
  45. * consider using:<br>
  46. * <code>List l = Collections.synchronizedList(new LinkedList(...));</code>
  47. * <p>
  48. *
  49. * The iterators are <i>fail-fast</i>, meaning that any structural
  50. * modification, except for <code>remove()</code> called on the iterator
  51. * itself, cause the iterator to throw a
  52. * {@link ConcurrentModificationException} rather than exhibit
  53. * non-deterministic behavior.
  54. *
  55. * @author Original author unknown
  56. * @author Bryce McKinlay
  57. * @author Eric Blake (ebb9@email.byu.edu)
  58. * @author Tom Tromey (tromey@redhat.com)
  59. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  60. * @see List
  61. * @see ArrayList
  62. * @see Vector
  63. * @see Collections#synchronizedList(List)
  64. * @since 1.2
  65. * @status Complete to 1.6
  66. */
  67. public class LinkedList<T> extends AbstractSequentialList<T>
  68. implements List<T>, Deque<T>, Cloneable, Serializable
  69. {
  70. /**
  71. * Compatible with JDK 1.2.
  72. */
  73. private static final long serialVersionUID = 876323262645176354L;
  74. /**
  75. * The first element in the list.
  76. */
  77. transient Entry<T> first;
  78. /**
  79. * The last element in the list.
  80. */
  81. transient Entry<T> last;
  82. /**
  83. * The current length of the list.
  84. */
  85. transient int size = 0;
  86. /**
  87. * Class to represent an entry in the list. Holds a single element.
  88. */
  89. private static final class Entry<T>
  90. {
  91. /** The element in the list. */
  92. T data;
  93. /** The next list entry, null if this is last. */
  94. Entry<T> next;
  95. /** The previous list entry, null if this is first. */
  96. Entry<T> previous;
  97. /**
  98. * Construct an entry.
  99. * @param data the list element
  100. */
  101. Entry(T data)
  102. {
  103. this.data = data;
  104. }
  105. } // class Entry
  106. /**
  107. * Obtain the Entry at a given position in a list. This method of course
  108. * takes linear time, but it is intelligent enough to take the shorter of the
  109. * paths to get to the Entry required. This implies that the first or last
  110. * entry in the list is obtained in constant time, which is a very desirable
  111. * property.
  112. * For speed and flexibility, range checking is not done in this method:
  113. * Incorrect values will be returned if (n &lt; 0) or (n &gt;= size).
  114. *
  115. * @param n the number of the entry to get
  116. * @return the entry at position n
  117. */
  118. // Package visible for use in nested classes.
  119. Entry<T> getEntry(int n)
  120. {
  121. Entry<T> e;
  122. if (n < size / 2)
  123. {
  124. e = first;
  125. // n less than size/2, iterate from start
  126. while (n-- > 0)
  127. e = e.next;
  128. }
  129. else
  130. {
  131. e = last;
  132. // n greater than size/2, iterate from end
  133. while (++n < size)
  134. e = e.previous;
  135. }
  136. return e;
  137. }
  138. /**
  139. * Remove an entry from the list. This will adjust size and deal with
  140. * `first' and `last' appropriatly.
  141. *
  142. * @param e the entry to remove
  143. */
  144. // Package visible for use in nested classes.
  145. void removeEntry(Entry<T> e)
  146. {
  147. modCount++;
  148. size--;
  149. if (size == 0)
  150. first = last = null;
  151. else
  152. {
  153. if (e == first)
  154. {
  155. first = e.next;
  156. e.next.previous = null;
  157. }
  158. else if (e == last)
  159. {
  160. last = e.previous;
  161. e.previous.next = null;
  162. }
  163. else
  164. {
  165. e.next.previous = e.previous;
  166. e.previous.next = e.next;
  167. }
  168. }
  169. }
  170. /**
  171. * Checks that the index is in the range of possible elements (inclusive).
  172. *
  173. * @param index the index to check
  174. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size
  175. */
  176. private void checkBoundsInclusive(int index)
  177. {
  178. if (index < 0 || index > size)
  179. throw new IndexOutOfBoundsException("Index: " + index + ", Size:"
  180. + size);
  181. }
  182. /**
  183. * Checks that the index is in the range of existing elements (exclusive).
  184. *
  185. * @param index the index to check
  186. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size
  187. */
  188. private void checkBoundsExclusive(int index)
  189. {
  190. if (index < 0 || index >= size)
  191. throw new IndexOutOfBoundsException("Index: " + index + ", Size:"
  192. + size);
  193. }
  194. /**
  195. * Create an empty linked list.
  196. */
  197. public LinkedList()
  198. {
  199. }
  200. /**
  201. * Create a linked list containing the elements, in order, of a given
  202. * collection.
  203. *
  204. * @param c the collection to populate this list from
  205. * @throws NullPointerException if c is null
  206. */
  207. public LinkedList(Collection<? extends T> c)
  208. {
  209. addAll(c);
  210. }
  211. /**
  212. * Returns the first element in the list.
  213. *
  214. * @return the first list element
  215. * @throws NoSuchElementException if the list is empty
  216. */
  217. public T getFirst()
  218. {
  219. if (size == 0)
  220. throw new NoSuchElementException();
  221. return first.data;
  222. }
  223. /**
  224. * Returns the last element in the list.
  225. *
  226. * @return the last list element
  227. * @throws NoSuchElementException if the list is empty
  228. */
  229. public T getLast()
  230. {
  231. if (size == 0)
  232. throw new NoSuchElementException();
  233. return last.data;
  234. }
  235. /**
  236. * Remove and return the first element in the list.
  237. *
  238. * @return the former first element in the list
  239. * @throws NoSuchElementException if the list is empty
  240. */
  241. public T removeFirst()
  242. {
  243. if (size == 0)
  244. throw new NoSuchElementException();
  245. modCount++;
  246. size--;
  247. T r = first.data;
  248. if (first.next != null)
  249. first.next.previous = null;
  250. else
  251. last = null;
  252. first = first.next;
  253. return r;
  254. }
  255. /**
  256. * Remove and return the last element in the list.
  257. *
  258. * @return the former last element in the list
  259. * @throws NoSuchElementException if the list is empty
  260. */
  261. public T removeLast()
  262. {
  263. if (size == 0)
  264. throw new NoSuchElementException();
  265. modCount++;
  266. size--;
  267. T r = last.data;
  268. if (last.previous != null)
  269. last.previous.next = null;
  270. else
  271. first = null;
  272. last = last.previous;
  273. return r;
  274. }
  275. /**
  276. * Insert an element at the first of the list.
  277. *
  278. * @param o the element to insert
  279. */
  280. public void addFirst(T o)
  281. {
  282. Entry<T> e = new Entry(o);
  283. modCount++;
  284. if (size == 0)
  285. first = last = e;
  286. else
  287. {
  288. e.next = first;
  289. first.previous = e;
  290. first = e;
  291. }
  292. size++;
  293. }
  294. /**
  295. * Insert an element at the last of the list.
  296. *
  297. * @param o the element to insert
  298. */
  299. public void addLast(T o)
  300. {
  301. addLastEntry(new Entry<T>(o));
  302. }
  303. /**
  304. * Inserts an element at the end of the list.
  305. *
  306. * @param e the entry to add
  307. */
  308. private void addLastEntry(Entry<T> e)
  309. {
  310. modCount++;
  311. if (size == 0)
  312. first = last = e;
  313. else
  314. {
  315. e.previous = last;
  316. last.next = e;
  317. last = e;
  318. }
  319. size++;
  320. }
  321. /**
  322. * Returns true if the list contains the given object. Comparison is done by
  323. * <code>o == null ? e = null : o.equals(e)</code>.
  324. *
  325. * @param o the element to look for
  326. * @return true if it is found
  327. */
  328. public boolean contains(Object o)
  329. {
  330. Entry<T> e = first;
  331. while (e != null)
  332. {
  333. if (equals(o, e.data))
  334. return true;
  335. e = e.next;
  336. }
  337. return false;
  338. }
  339. /**
  340. * Returns the size of the list.
  341. *
  342. * @return the list size
  343. */
  344. public int size()
  345. {
  346. return size;
  347. }
  348. /**
  349. * Adds an element to the end of the list.
  350. *
  351. * @param o the entry to add
  352. * @return true, as it always succeeds
  353. */
  354. public boolean add(T o)
  355. {
  356. addLastEntry(new Entry<T>(o));
  357. return true;
  358. }
  359. /**
  360. * Removes the entry at the lowest index in the list that matches the given
  361. * object, comparing by <code>o == null ? e = null : o.equals(e)</code>.
  362. *
  363. * @param o the object to remove
  364. * @return true if an instance of the object was removed
  365. */
  366. public boolean remove(Object o)
  367. {
  368. Entry<T> e = first;
  369. while (e != null)
  370. {
  371. if (equals(o, e.data))
  372. {
  373. removeEntry(e);
  374. return true;
  375. }
  376. e = e.next;
  377. }
  378. return false;
  379. }
  380. /**
  381. * Append the elements of the collection in iteration order to the end of
  382. * this list. If this list is modified externally (for example, if this
  383. * list is the collection), behavior is unspecified.
  384. *
  385. * @param c the collection to append
  386. * @return true if the list was modified
  387. * @throws NullPointerException if c is null
  388. */
  389. public boolean addAll(Collection<? extends T> c)
  390. {
  391. return addAll(size, c);
  392. }
  393. /**
  394. * Insert the elements of the collection in iteration order at the given
  395. * index of this list. If this list is modified externally (for example,
  396. * if this list is the collection), behavior is unspecified.
  397. *
  398. * @param c the collection to append
  399. * @return true if the list was modified
  400. * @throws NullPointerException if c is null
  401. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  402. */
  403. public boolean addAll(int index, Collection<? extends T> c)
  404. {
  405. checkBoundsInclusive(index);
  406. int csize = c.size();
  407. if (csize == 0)
  408. return false;
  409. Iterator<? extends T> itr = c.iterator();
  410. // Get the entries just before and after index. If index is at the start
  411. // of the list, BEFORE is null. If index is at the end of the list, AFTER
  412. // is null. If the list is empty, both are null.
  413. Entry<T> after = null;
  414. Entry<T> before = null;
  415. if (index != size)
  416. {
  417. after = getEntry(index);
  418. before = after.previous;
  419. }
  420. else
  421. before = last;
  422. // Create the first new entry. We do not yet set the link from `before'
  423. // to the first entry, in order to deal with the case where (c == this).
  424. // [Actually, we don't have to handle this case to fufill the
  425. // contract for addAll(), but Sun's implementation appears to.]
  426. Entry<T> e = new Entry<T>(itr.next());
  427. e.previous = before;
  428. Entry<T> prev = e;
  429. Entry<T> firstNew = e;
  430. // Create and link all the remaining entries.
  431. for (int pos = 1; pos < csize; pos++)
  432. {
  433. e = new Entry<T>(itr.next());
  434. e.previous = prev;
  435. prev.next = e;
  436. prev = e;
  437. }
  438. // Link the new chain of entries into the list.
  439. modCount++;
  440. size += csize;
  441. prev.next = after;
  442. if (after != null)
  443. after.previous = e;
  444. else
  445. last = e;
  446. if (before != null)
  447. before.next = firstNew;
  448. else
  449. first = firstNew;
  450. return true;
  451. }
  452. /**
  453. * Remove all elements from this list.
  454. */
  455. public void clear()
  456. {
  457. if (size > 0)
  458. {
  459. modCount++;
  460. first = null;
  461. last = null;
  462. size = 0;
  463. }
  464. }
  465. /**
  466. * Return the element at index.
  467. *
  468. * @param index the place to look
  469. * @return the element at index
  470. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  471. */
  472. public T get(int index)
  473. {
  474. checkBoundsExclusive(index);
  475. return getEntry(index).data;
  476. }
  477. /**
  478. * Replace the element at the given location in the list.
  479. *
  480. * @param index which index to change
  481. * @param o the new element
  482. * @return the prior element
  483. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  484. */
  485. public T set(int index, T o)
  486. {
  487. checkBoundsExclusive(index);
  488. Entry<T> e = getEntry(index);
  489. T old = e.data;
  490. e.data = o;
  491. return old;
  492. }
  493. /**
  494. * Inserts an element in the given position in the list.
  495. *
  496. * @param index where to insert the element
  497. * @param o the element to insert
  498. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  499. */
  500. public void add(int index, T o)
  501. {
  502. checkBoundsInclusive(index);
  503. Entry<T> e = new Entry<T>(o);
  504. if (index < size)
  505. {
  506. modCount++;
  507. Entry<T> after = getEntry(index);
  508. e.next = after;
  509. e.previous = after.previous;
  510. if (after.previous == null)
  511. first = e;
  512. else
  513. after.previous.next = e;
  514. after.previous = e;
  515. size++;
  516. }
  517. else
  518. addLastEntry(e);
  519. }
  520. /**
  521. * Removes the element at the given position from the list.
  522. *
  523. * @param index the location of the element to remove
  524. * @return the removed element
  525. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  526. */
  527. public T remove(int index)
  528. {
  529. checkBoundsExclusive(index);
  530. Entry<T> e = getEntry(index);
  531. removeEntry(e);
  532. return e.data;
  533. }
  534. /**
  535. * Returns the first index where the element is located in the list, or -1.
  536. *
  537. * @param o the element to look for
  538. * @return its position, or -1 if not found
  539. */
  540. public int indexOf(Object o)
  541. {
  542. int index = 0;
  543. Entry<T> e = first;
  544. while (e != null)
  545. {
  546. if (equals(o, e.data))
  547. return index;
  548. index++;
  549. e = e.next;
  550. }
  551. return -1;
  552. }
  553. /**
  554. * Returns the last index where the element is located in the list, or -1.
  555. *
  556. * @param o the element to look for
  557. * @return its position, or -1 if not found
  558. */
  559. public int lastIndexOf(Object o)
  560. {
  561. int index = size - 1;
  562. Entry<T> e = last;
  563. while (e != null)
  564. {
  565. if (equals(o, e.data))
  566. return index;
  567. index--;
  568. e = e.previous;
  569. }
  570. return -1;
  571. }
  572. /**
  573. * Obtain a ListIterator over this list, starting at a given index. The
  574. * ListIterator returned by this method supports the add, remove and set
  575. * methods.
  576. *
  577. * @param index the index of the element to be returned by the first call to
  578. * next(), or size() to be initially positioned at the end of the list
  579. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  580. */
  581. public ListIterator<T> listIterator(int index)
  582. {
  583. checkBoundsInclusive(index);
  584. return new LinkedListItr<T>(index);
  585. }
  586. /**
  587. * Create a shallow copy of this LinkedList (the elements are not cloned).
  588. *
  589. * @return an object of the same class as this object, containing the
  590. * same elements in the same order
  591. */
  592. public Object clone()
  593. {
  594. LinkedList<T> copy = null;
  595. try
  596. {
  597. copy = (LinkedList<T>) super.clone();
  598. }
  599. catch (CloneNotSupportedException ex)
  600. {
  601. }
  602. copy.clear();
  603. copy.addAll(this);
  604. return copy;
  605. }
  606. /**
  607. * Returns an array which contains the elements of the list in order.
  608. *
  609. * @return an array containing the list elements
  610. */
  611. public Object[] toArray()
  612. {
  613. Object[] array = new Object[size];
  614. Entry<T> e = first;
  615. for (int i = 0; i < size; i++)
  616. {
  617. array[i] = e.data;
  618. e = e.next;
  619. }
  620. return array;
  621. }
  622. /**
  623. * Returns an Array whose component type is the runtime component type of
  624. * the passed-in Array. The returned Array is populated with all of the
  625. * elements in this LinkedList. If the passed-in Array is not large enough
  626. * to store all of the elements in this List, a new Array will be created
  627. * and returned; if the passed-in Array is <i>larger</i> than the size
  628. * of this List, then size() index will be set to null.
  629. *
  630. * @param a the passed-in Array
  631. * @return an array representation of this list
  632. * @throws ArrayStoreException if the runtime type of a does not allow
  633. * an element in this list
  634. * @throws NullPointerException if a is null
  635. */
  636. public <S> S[] toArray(S[] a)
  637. {
  638. if (a.length < size)
  639. a = (S[]) Array.newInstance(a.getClass().getComponentType(), size);
  640. else if (a.length > size)
  641. a[size] = null;
  642. Entry<T> e = first;
  643. for (int i = 0; i < size; i++)
  644. {
  645. a[i] = (S) e.data;
  646. e = e.next;
  647. }
  648. return a;
  649. }
  650. /**
  651. * Adds the specified element to the end of the list.
  652. *
  653. * @param value the value to add.
  654. * @return true.
  655. * @since 1.5
  656. */
  657. public boolean offer(T value)
  658. {
  659. return add(value);
  660. }
  661. /**
  662. * Returns the first element of the list without removing
  663. * it.
  664. *
  665. * @return the first element of the list.
  666. * @throws NoSuchElementException if the list is empty.
  667. * @since 1.5
  668. */
  669. public T element()
  670. {
  671. return getFirst();
  672. }
  673. /**
  674. * Returns the first element of the list without removing
  675. * it.
  676. *
  677. * @return the first element of the list, or <code>null</code>
  678. * if the list is empty.
  679. * @since 1.5
  680. */
  681. public T peek()
  682. {
  683. if (size == 0)
  684. return null;
  685. return getFirst();
  686. }
  687. /**
  688. * Removes and returns the first element of the list.
  689. *
  690. * @return the first element of the list, or <code>null</code>
  691. * if the list is empty.
  692. * @since 1.5
  693. */
  694. public T poll()
  695. {
  696. if (size == 0)
  697. return null;
  698. return removeFirst();
  699. }
  700. /**
  701. * Removes and returns the first element of the list.
  702. *
  703. * @return the first element of the list.
  704. * @throws NoSuchElementException if the list is empty.
  705. * @since 1.5
  706. */
  707. public T remove()
  708. {
  709. return removeFirst();
  710. }
  711. /**
  712. * Serializes this object to the given stream.
  713. *
  714. * @param s the stream to write to
  715. * @throws IOException if the underlying stream fails
  716. * @serialData the size of the list (int), followed by all the elements
  717. * (Object) in proper order
  718. */
  719. private void writeObject(ObjectOutputStream s) throws IOException
  720. {
  721. s.defaultWriteObject();
  722. s.writeInt(size);
  723. Entry<T> e = first;
  724. while (e != null)
  725. {
  726. s.writeObject(e.data);
  727. e = e.next;
  728. }
  729. }
  730. /**
  731. * Deserializes this object from the given stream.
  732. *
  733. * @param s the stream to read from
  734. * @throws ClassNotFoundException if the underlying stream fails
  735. * @throws IOException if the underlying stream fails
  736. * @serialData the size of the list (int), followed by all the elements
  737. * (Object) in proper order
  738. */
  739. private void readObject(ObjectInputStream s)
  740. throws IOException, ClassNotFoundException
  741. {
  742. s.defaultReadObject();
  743. int i = s.readInt();
  744. while (--i >= 0)
  745. addLastEntry(new Entry<T>((T) s.readObject()));
  746. }
  747. /**
  748. * A ListIterator over the list. This class keeps track of its
  749. * position in the list and the two list entries it is between.
  750. *
  751. * @author Original author unknown
  752. * @author Eric Blake (ebb9@email.byu.edu)
  753. */
  754. private final class LinkedListItr<I>
  755. implements ListIterator<I>
  756. {
  757. /** Number of modifications we know about. */
  758. private int knownMod = modCount;
  759. /** Entry that will be returned by next(). */
  760. private Entry<I> next;
  761. /** Entry that will be returned by previous(). */
  762. private Entry<I> previous;
  763. /** Entry that will be affected by remove() or set(). */
  764. private Entry<I> lastReturned;
  765. /** Index of `next'. */
  766. private int position;
  767. /**
  768. * Initialize the iterator.
  769. *
  770. * @param index the initial index
  771. */
  772. LinkedListItr(int index)
  773. {
  774. if (index == size)
  775. {
  776. next = null;
  777. previous = (Entry<I>) last;
  778. }
  779. else
  780. {
  781. next = (Entry<I>) getEntry(index);
  782. previous = next.previous;
  783. }
  784. position = index;
  785. }
  786. /**
  787. * Checks for iterator consistency.
  788. *
  789. * @throws ConcurrentModificationException if the list was modified
  790. */
  791. private void checkMod()
  792. {
  793. if (knownMod != modCount)
  794. throw new ConcurrentModificationException();
  795. }
  796. /**
  797. * Returns the index of the next element.
  798. *
  799. * @return the next index
  800. */
  801. public int nextIndex()
  802. {
  803. return position;
  804. }
  805. /**
  806. * Returns the index of the previous element.
  807. *
  808. * @return the previous index
  809. */
  810. public int previousIndex()
  811. {
  812. return position - 1;
  813. }
  814. /**
  815. * Returns true if more elements exist via next.
  816. *
  817. * @return true if next will succeed
  818. */
  819. public boolean hasNext()
  820. {
  821. return (next != null);
  822. }
  823. /**
  824. * Returns true if more elements exist via previous.
  825. *
  826. * @return true if previous will succeed
  827. */
  828. public boolean hasPrevious()
  829. {
  830. return (previous != null);
  831. }
  832. /**
  833. * Returns the next element.
  834. *
  835. * @return the next element
  836. * @throws ConcurrentModificationException if the list was modified
  837. * @throws NoSuchElementException if there is no next
  838. */
  839. public I next()
  840. {
  841. checkMod();
  842. if (next == null)
  843. throw new NoSuchElementException();
  844. position++;
  845. lastReturned = previous = next;
  846. next = lastReturned.next;
  847. return lastReturned.data;
  848. }
  849. /**
  850. * Returns the previous element.
  851. *
  852. * @return the previous element
  853. * @throws ConcurrentModificationException if the list was modified
  854. * @throws NoSuchElementException if there is no previous
  855. */
  856. public I previous()
  857. {
  858. checkMod();
  859. if (previous == null)
  860. throw new NoSuchElementException();
  861. position--;
  862. lastReturned = next = previous;
  863. previous = lastReturned.previous;
  864. return lastReturned.data;
  865. }
  866. /**
  867. * Remove the most recently returned element from the list.
  868. *
  869. * @throws ConcurrentModificationException if the list was modified
  870. * @throws IllegalStateException if there was no last element
  871. */
  872. public void remove()
  873. {
  874. checkMod();
  875. if (lastReturned == null)
  876. throw new IllegalStateException();
  877. // Adjust the position to before the removed element, if the element
  878. // being removed is behind the cursor.
  879. if (lastReturned == previous)
  880. position--;
  881. next = lastReturned.next;
  882. previous = lastReturned.previous;
  883. removeEntry((Entry<T>) lastReturned);
  884. knownMod++;
  885. lastReturned = null;
  886. }
  887. /**
  888. * Adds an element between the previous and next, and advance to the next.
  889. *
  890. * @param o the element to add
  891. * @throws ConcurrentModificationException if the list was modified
  892. */
  893. public void add(I o)
  894. {
  895. checkMod();
  896. modCount++;
  897. knownMod++;
  898. size++;
  899. position++;
  900. Entry<I> e = new Entry<I>(o);
  901. e.previous = previous;
  902. e.next = next;
  903. if (previous != null)
  904. previous.next = e;
  905. else
  906. first = (Entry<T>) e;
  907. if (next != null)
  908. next.previous = e;
  909. else
  910. last = (Entry<T>) e;
  911. previous = e;
  912. lastReturned = null;
  913. }
  914. /**
  915. * Changes the contents of the element most recently returned.
  916. *
  917. * @param o the new element
  918. * @throws ConcurrentModificationException if the list was modified
  919. * @throws IllegalStateException if there was no last element
  920. */
  921. public void set(I o)
  922. {
  923. checkMod();
  924. if (lastReturned == null)
  925. throw new IllegalStateException();
  926. lastReturned.data = o;
  927. }
  928. } // class LinkedListItr
  929. /**
  930. * Obtain an Iterator over this list in reverse sequential order.
  931. *
  932. * @return an Iterator over the elements of the list in
  933. * reverse order.
  934. * @since 1.6
  935. */
  936. public Iterator<T> descendingIterator()
  937. {
  938. return new Iterator<T>()
  939. {
  940. /** Number of modifications we know about. */
  941. private int knownMod = modCount;
  942. /** Entry that will be returned by next(). */
  943. private Entry<T> next = last;
  944. /** Entry that will be affected by remove() or set(). */
  945. private Entry<T> lastReturned;
  946. /** Index of `next'. */
  947. private int position = size() - 1;
  948. // This will get inlined, since it is private.
  949. /**
  950. * Checks for modifications made to the list from
  951. * elsewhere while iteration is in progress.
  952. *
  953. * @throws ConcurrentModificationException if the
  954. * list has been modified elsewhere.
  955. */
  956. private void checkMod()
  957. {
  958. if (knownMod != modCount)
  959. throw new ConcurrentModificationException();
  960. }
  961. /**
  962. * Tests to see if there are any more objects to
  963. * return.
  964. *
  965. * @return true if the start of the list has not yet been
  966. * reached.
  967. */
  968. public boolean hasNext()
  969. {
  970. return next != null;
  971. }
  972. /**
  973. * Retrieves the next object from the list.
  974. *
  975. * @return The next object.
  976. * @throws NoSuchElementException if there are
  977. * no more objects to retrieve.
  978. * @throws ConcurrentModificationException if the
  979. * list has been modified elsewhere.
  980. */
  981. public T next()
  982. {
  983. checkMod();
  984. if (next == null)
  985. throw new NoSuchElementException();
  986. --position;
  987. lastReturned = next;
  988. next = lastReturned.previous;
  989. return lastReturned.data;
  990. }
  991. /**
  992. * Removes the last object retrieved by <code>next()</code>
  993. * from the list, if the list supports object removal.
  994. *
  995. * @throws ConcurrentModificationException if the list
  996. * has been modified elsewhere.
  997. * @throws IllegalStateException if the iterator is positioned
  998. * before the start of the list or the last object has already
  999. * been removed.
  1000. */
  1001. public void remove()
  1002. {
  1003. checkMod();
  1004. if (lastReturned == null)
  1005. throw new IllegalStateException();
  1006. removeEntry(lastReturned);
  1007. lastReturned = null;
  1008. ++knownMod;
  1009. }
  1010. };
  1011. }
  1012. /**
  1013. * Inserts the specified element at the front of the list.
  1014. *
  1015. * @param value the element to insert.
  1016. * @return true.
  1017. * @since 1.6
  1018. */
  1019. public boolean offerFirst(T value)
  1020. {
  1021. addFirst(value);
  1022. return true;
  1023. }
  1024. /**
  1025. * Inserts the specified element at the end of the list.
  1026. *
  1027. * @param value the element to insert.
  1028. * @return true.
  1029. * @since 1.6
  1030. */
  1031. public boolean offerLast(T value)
  1032. {
  1033. return add(value);
  1034. }
  1035. /**
  1036. * Returns the first element of the list without removing
  1037. * it.
  1038. *
  1039. * @return the first element of the list, or <code>null</code>
  1040. * if the list is empty.
  1041. * @since 1.6
  1042. */
  1043. public T peekFirst()
  1044. {
  1045. return peek();
  1046. }
  1047. /**
  1048. * Returns the last element of the list without removing
  1049. * it.
  1050. *
  1051. * @return the last element of the list, or <code>null</code>
  1052. * if the list is empty.
  1053. * @since 1.6
  1054. */
  1055. public T peekLast()
  1056. {
  1057. if (size == 0)
  1058. return null;
  1059. return getLast();
  1060. }
  1061. /**
  1062. * Removes and returns the first element of the list.
  1063. *
  1064. * @return the first element of the list, or <code>null</code>
  1065. * if the list is empty.
  1066. * @since 1.6
  1067. */
  1068. public T pollFirst()
  1069. {
  1070. return poll();
  1071. }
  1072. /**
  1073. * Removes and returns the last element of the list.
  1074. *
  1075. * @return the last element of the list, or <code>null</code>
  1076. * if the list is empty.
  1077. * @since 1.6
  1078. */
  1079. public T pollLast()
  1080. {
  1081. if (size == 0)
  1082. return null;
  1083. return removeLast();
  1084. }
  1085. /**
  1086. * Pops an element from the stack by removing and returning
  1087. * the first element in the list. This is equivalent to
  1088. * calling {@link #removeFirst()}.
  1089. *
  1090. * @return the top of the stack, which is the first element
  1091. * of the list.
  1092. * @throws NoSuchElementException if the list is empty.
  1093. * @since 1.6
  1094. * @see #removeFirst()
  1095. */
  1096. public T pop()
  1097. {
  1098. return removeFirst();
  1099. }
  1100. /**
  1101. * Pushes an element on to the stack by adding it to the
  1102. * front of the list. This is equivalent to calling
  1103. * {@link #addFirst(T)}.
  1104. *
  1105. * @param value the element to push on to the stack.
  1106. * @throws NoSuchElementException if the list is empty.
  1107. * @since 1.6
  1108. * @see #addFirst(T)
  1109. */
  1110. public void push(T value)
  1111. {
  1112. addFirst(value);
  1113. }
  1114. /**
  1115. * Removes the first occurrence of the specified element
  1116. * from the list, when traversing the list from head to
  1117. * tail. The list is unchanged if the element is not found.
  1118. * This is equivalent to calling {@link #remove(Object)}.
  1119. *
  1120. * @param o the element to remove.
  1121. * @return true if an instance of the object was removed.
  1122. * @since 1.6
  1123. */
  1124. public boolean removeFirstOccurrence(Object o)
  1125. {
  1126. return remove(o);
  1127. }
  1128. /**
  1129. * Removes the last occurrence of the specified element
  1130. * from the list, when traversing the list from head to
  1131. * tail. The list is unchanged if the element is not found.
  1132. *
  1133. * @param o the element to remove.
  1134. * @return true if an instance of the object was removed.
  1135. * @since 1.6
  1136. */
  1137. public boolean removeLastOccurrence(Object o)
  1138. {
  1139. Entry<T> e = last;
  1140. while (e != null)
  1141. {
  1142. if (equals(o, e.data))
  1143. {
  1144. removeEntry(e);
  1145. return true;
  1146. }
  1147. e = e.previous;
  1148. }
  1149. return false;
  1150. }
  1151. }