Print this page
Split |
Close |
Expand all |
Collapse all |
--- old/src/share/classes/java/util/LinkedList.java
+++ new/src/share/classes/java/util/LinkedList.java
1 1 /*
2 2 * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
3 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 4 *
5 5 * This code is free software; you can redistribute it and/or modify it
6 6 * under the terms of the GNU General Public License version 2 only, as
7 7 * published by the Free Software Foundation. Oracle designates this
8 8 * particular file as subject to the "Classpath" exception as provided
9 9 * by Oracle in the LICENSE file that accompanied this code.
10 10 *
11 11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 14 * version 2 for more details (a copy is included in the LICENSE file that
15 15 * accompanied this code).
16 16 *
17 17 * You should have received a copy of the GNU General Public License version
18 18 * 2 along with this work; if not, write to the Free Software Foundation,
↓ open down ↓ |
18 lines elided |
↑ open up ↑ |
19 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 20 *
21 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 22 * or visit www.oracle.com if you need additional information or have any
23 23 * questions.
24 24 */
25 25
26 26 package java.util;
27 27
28 28 /**
29 - * Linked list implementation of the {@link List} and {@link Deque} interfaces.
30 - * Implements all optional operations, and permits all elements (including
31 - * {@code null}).
29 + * Linked list implementation of the {@code List} interface. Implements all
30 + * optional list operations, and permits all elements (including
31 + * {@code null}). In addition to implementing the {@code List} interface,
32 + * the {@code LinkedList} class provides uniformly named methods to
33 + * {@code get}, {@code remove} and {@code insert} an element at the
34 + * beginning and end of the list. These operations allow linked lists to be
35 + * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque
36 + * double-ended queue}.
32 37 *
38 + * <p>The class implements the {@code Deque} interface, providing
39 + * first-in-first-out queue operations for {@code add},
40 + * {@code poll}, along with other stack and deque operations.
41 + *
33 42 * <p>All of the operations perform as could be expected for a doubly-linked
34 43 * list. Operations that index into the list will traverse the list from
35 44 * the beginning or the end, whichever is closer to the specified index.
36 45 *
37 46 * <p><strong>Note that this implementation is not synchronized.</strong>
38 47 * If multiple threads access a linked list concurrently, and at least
39 48 * one of the threads modifies the list structurally, it <i>must</i> be
40 49 * synchronized externally. (A structural modification is any operation
41 50 * that adds or deletes one or more elements; merely setting the value of
42 51 * an element is not a structural modification.) This is typically
43 52 * accomplished by synchronizing on some object that naturally
44 53 * encapsulates the list.
45 54 *
46 55 * If no such object exists, the list should be "wrapped" using the
47 56 * {@link Collections#synchronizedList Collections.synchronizedList}
48 57 * method. This is best done at creation time, to prevent accidental
49 58 * unsynchronized access to the list:<pre>
50 59 * List list = Collections.synchronizedList(new LinkedList(...));</pre>
51 60 *
52 61 * <p>The iterators returned by this class's {@code iterator} and
53 62 * {@code listIterator} methods are <i>fail-fast</i>: if the list is
54 63 * structurally modified at any time after the iterator is created, in
55 64 * any way except through the Iterator's own {@code remove} or
56 65 * {@code add} methods, the iterator will throw a {@link
57 66 * ConcurrentModificationException}. Thus, in the face of concurrent
58 67 * modification, the iterator fails quickly and cleanly, rather than
59 68 * risking arbitrary, non-deterministic behavior at an undetermined
60 69 * time in the future.
61 70 *
62 71 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
63 72 * as it is, generally speaking, impossible to make any hard guarantees in the
64 73 * presence of unsynchronized concurrent modification. Fail-fast iterators
65 74 * throw {@code ConcurrentModificationException} on a best-effort basis.
66 75 * Therefore, it would be wrong to write a program that depended on this
67 76 * exception for its correctness: <i>the fail-fast behavior of iterators
68 77 * should be used only to detect bugs.</i>
69 78 *
70 79 * <p>This class is a member of the
71 80 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
72 81 * Java Collections Framework</a>.
73 82 *
74 83 * @author Josh Bloch
75 84 * @see List
76 85 * @see ArrayList
77 86 * @since 1.2
78 87 * @param <E> the type of elements held in this collection
79 88 */
80 89
81 90 public class LinkedList<E>
82 91 extends AbstractSequentialList<E>
83 92 implements List<E>, Deque<E>, Cloneable, java.io.Serializable
84 93 {
85 94 transient int size = 0;
86 95
87 96 /**
88 97 * Pointer to first node.
89 98 * Invariant: (first == null && last == null) ||
90 99 * (first.prev == null && first.item != null)
91 100 */
92 101 transient Node<E> first;
93 102
94 103 /**
95 104 * Pointer to last node.
96 105 * Invariant: (first == null && last == null) ||
97 106 * (last.next == null && last.item != null)
98 107 */
99 108 transient Node<E> last;
100 109
101 110 /**
102 111 * Constructs an empty list.
103 112 */
104 113 public LinkedList() {
105 114 }
106 115
107 116 /**
108 117 * Constructs a list containing the elements of the specified
109 118 * collection, in the order they are returned by the collection's
110 119 * iterator.
111 120 *
112 121 * @param c the collection whose elements are to be placed into this list
113 122 * @throws NullPointerException if the specified collection is null
114 123 */
115 124 public LinkedList(Collection<? extends E> c) {
116 125 this();
117 126 addAll(c);
118 127 }
119 128
120 129 /**
121 130 * Links e as first element.
122 131 */
123 132 private void linkFirst(E e) {
124 133 final Node<E> f = first;
125 134 final Node<E> newNode = new Node<E>(null, e, f);
126 135 first = newNode;
127 136 if (f == null)
128 137 last = newNode;
129 138 else
130 139 f.prev = newNode;
131 140 size++;
132 141 modCount++;
133 142 }
134 143
135 144 /**
136 145 * Links e as last element.
137 146 */
138 147 void linkLast(E e) {
139 148 final Node<E> l = last;
140 149 final Node<E> newNode = new Node<E>(l, e, null);
141 150 last = newNode;
142 151 if (l == null)
143 152 first = newNode;
144 153 else
145 154 l.next = newNode;
146 155 size++;
147 156 modCount++;
148 157 }
149 158
150 159 /**
151 160 * Inserts element e before non-null Node succ.
152 161 */
153 162 void linkBefore(E e, Node<E> succ) {
154 163 // assert succ != null;
155 164 final Node<E> pred = succ.prev;
156 165 final Node<E> newNode = new Node<E>(pred, e, succ);
157 166 succ.prev = newNode;
158 167 if (pred == null)
159 168 first = newNode;
160 169 else
161 170 pred.next = newNode;
162 171 size++;
163 172 modCount++;
164 173 }
165 174
166 175 /**
167 176 * Unlinks non-null first node f.
168 177 */
169 178 private E unlinkFirst(Node<E> f) {
170 179 // assert f == first && f != null;
171 180 final E element = f.item;
172 181 final Node<E> next = f.next;
173 182 f.item = null;
174 183 f.next = null; // help GC
175 184 first = next;
176 185 if (next == null)
177 186 last = null;
178 187 else
179 188 next.prev = null;
180 189 size--;
181 190 modCount++;
182 191 return element;
183 192 }
184 193
185 194 /**
186 195 * Unlinks non-null last node l.
187 196 */
188 197 private E unlinkLast(Node<E> l) {
189 198 // assert l == last && l != null;
190 199 final E element = l.item;
191 200 final Node<E> prev = l.prev;
192 201 l.item = null;
193 202 l.prev = null; // help GC
194 203 last = prev;
195 204 if (prev == null)
196 205 first = null;
197 206 else
198 207 prev.next = null;
199 208 size--;
200 209 modCount++;
201 210 return element;
202 211 }
203 212
204 213 /**
205 214 * Unlinks non-null node x.
206 215 */
207 216 E unlink(Node<E> x) {
208 217 // assert x != null;
209 218 final E element = x.item;
210 219 final Node<E> next = x.next;
211 220 final Node<E> prev = x.prev;
212 221
213 222 if (prev == null) {
214 223 first = next;
215 224 } else {
216 225 prev.next = next;
217 226 x.prev = null;
218 227 }
219 228
220 229 if (next == null) {
221 230 last = prev;
222 231 } else {
223 232 next.prev = prev;
224 233 x.next = null;
225 234 }
226 235
227 236 x.item = null;
228 237 size--;
229 238 modCount++;
230 239 return element;
231 240 }
232 241
233 242 /**
234 243 * Returns the first element in this list.
235 244 *
236 245 * @return the first element in this list
237 246 * @throws NoSuchElementException if this list is empty
238 247 */
239 248 public E getFirst() {
240 249 final Node<E> f = first;
241 250 if (f == null)
↓ open down ↓ |
199 lines elided |
↑ open up ↑ |
242 251 throw new NoSuchElementException();
243 252 return f.item;
244 253 }
245 254
246 255 /**
247 256 * Returns the last element in this list.
248 257 *
249 258 * @return the last element in this list
250 259 * @throws NoSuchElementException if this list is empty
251 260 */
252 - public E getLast() {
261 + public E getLast() {
253 262 final Node<E> l = last;
254 263 if (l == null)
255 264 throw new NoSuchElementException();
256 265 return l.item;
257 266 }
258 267
259 268 /**
260 269 * Removes and returns the first element from this list.
261 270 *
262 271 * @return the first element from this list
263 272 * @throws NoSuchElementException if this list is empty
264 273 */
265 274 public E removeFirst() {
266 275 final Node<E> f = first;
267 276 if (f == null)
268 277 throw new NoSuchElementException();
269 278 return unlinkFirst(f);
270 279 }
271 280
272 281 /**
273 282 * Removes and returns the last element from this list.
274 283 *
275 284 * @return the last element from this list
276 285 * @throws NoSuchElementException if this list is empty
277 286 */
278 287 public E removeLast() {
279 288 final Node<E> l = last;
280 289 if (l == null)
281 290 throw new NoSuchElementException();
282 291 return unlinkLast(l);
283 292 }
284 293
285 294 /**
286 295 * Inserts the specified element at the beginning of this list.
287 296 *
288 297 * @param e the element to add
289 298 */
290 299 public void addFirst(E e) {
291 300 linkFirst(e);
292 301 }
293 302
294 303 /**
295 304 * Appends the specified element to the end of this list.
296 305 *
297 306 * <p>This method is equivalent to {@link #add}.
298 307 *
299 308 * @param e the element to add
300 309 */
301 310 public void addLast(E e) {
302 311 linkLast(e);
303 312 }
304 313
305 314 /**
306 315 * Returns {@code true} if this list contains the specified element.
307 316 * More formally, returns {@code true} if and only if this list contains
308 317 * at least one element {@code e} such that
309 318 * <tt>(o==null ? e==null : o.equals(e))</tt>.
310 319 *
311 320 * @param o element whose presence in this list is to be tested
312 321 * @return {@code true} if this list contains the specified element
313 322 */
314 323 public boolean contains(Object o) {
315 324 return indexOf(o) != -1;
316 325 }
317 326
318 327 /**
319 328 * Returns the number of elements in this list.
320 329 *
321 330 * @return the number of elements in this list
322 331 */
323 332 public int size() {
324 333 return size;
325 334 }
326 335
327 336 /**
328 337 * Appends the specified element to the end of this list.
329 338 *
330 339 * <p>This method is equivalent to {@link #addLast}.
331 340 *
332 341 * @param e element to be appended to this list
333 342 * @return {@code true} (as specified by {@link Collection#add})
334 343 */
335 344 public boolean add(E e) {
336 345 linkLast(e);
337 346 return true;
338 347 }
339 348
340 349 /**
341 350 * Removes the first occurrence of the specified element from this list,
342 351 * if it is present. If this list does not contain the element, it is
343 352 * unchanged. More formally, removes the element with the lowest index
344 353 * {@code i} such that
345 354 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
346 355 * (if such an element exists). Returns {@code true} if this list
347 356 * contained the specified element (or equivalently, if this list
348 357 * changed as a result of the call).
349 358 *
350 359 * @param o element to be removed from this list, if present
351 360 * @return {@code true} if this list contained the specified element
352 361 */
353 362 public boolean remove(Object o) {
354 363 if (o == null) {
355 364 for (Node<E> x = first; x != null; x = x.next) {
356 365 if (x.item == null) {
357 366 unlink(x);
358 367 return true;
359 368 }
360 369 }
361 370 } else {
362 371 for (Node<E> x = first; x != null; x = x.next) {
363 372 if (o.equals(x.item)) {
364 373 unlink(x);
365 374 return true;
366 375 }
367 376 }
368 377 }
369 378 return false;
370 379 }
371 380
372 381 /**
373 382 * Appends all of the elements in the specified collection to the end of
374 383 * this list, in the order that they are returned by the specified
375 384 * collection's iterator. The behavior of this operation is undefined if
376 385 * the specified collection is modified while the operation is in
377 386 * progress. (Note that this will occur if the specified collection is
378 387 * this list, and it's nonempty.)
379 388 *
380 389 * @param c collection containing elements to be added to this list
381 390 * @return {@code true} if this list changed as a result of the call
382 391 * @throws NullPointerException if the specified collection is null
383 392 */
384 393 public boolean addAll(Collection<? extends E> c) {
385 394 return addAll(size, c);
386 395 }
387 396
388 397 /**
389 398 * Inserts all of the elements in the specified collection into this
390 399 * list, starting at the specified position. Shifts the element
391 400 * currently at that position (if any) and any subsequent elements to
392 401 * the right (increases their indices). The new elements will appear
393 402 * in the list in the order that they are returned by the
394 403 * specified collection's iterator.
395 404 *
396 405 * @param index index at which to insert the first element
397 406 * from the specified collection
398 407 * @param c collection containing elements to be added to this list
399 408 * @return {@code true} if this list changed as a result of the call
400 409 * @throws IndexOutOfBoundsException {@inheritDoc}
401 410 * @throws NullPointerException if the specified collection is null
402 411 */
403 412 public boolean addAll(int index, Collection<? extends E> c) {
404 413 checkPositionIndex(index);
405 414
406 415 Object[] a = c.toArray();
407 416 int numNew = a.length;
408 417 if (numNew == 0)
409 418 return false;
410 419
411 420 Node<E> pred, succ;
412 421 if (index == size) {
413 422 succ = null;
414 423 pred = last;
415 424 } else {
416 425 succ = node(index);
417 426 pred = succ.prev;
418 427 }
419 428
420 429 for (Object o : a) {
421 430 @SuppressWarnings("unchecked") E e = (E) o;
422 431 Node<E> newNode = new Node<E>(pred, e, null);
423 432 if (pred == null)
424 433 first = newNode;
425 434 else
426 435 pred.next = newNode;
427 436 pred = newNode;
428 437 }
429 438
430 439 if (succ == null) {
431 440 last = pred;
432 441 } else {
433 442 pred.next = succ;
434 443 succ.prev = pred;
435 444 }
436 445
437 446 size += numNew;
438 447 modCount++;
439 448 return true;
440 449 }
441 450
442 451 /**
443 452 * Removes all of the elements from this list.
444 453 * The list will be empty after this call returns.
445 454 */
446 455 public void clear() {
447 456 // Clearing all of the links between nodes is "unnecessary", but:
448 457 // - helps a generational GC if the discarded nodes inhabit
449 458 // more than one generation
450 459 // - is sure to free memory even if there is a reachable Iterator
451 460 for (Node<E> x = first; x != null; ) {
452 461 Node<E> next = x.next;
453 462 x.item = null;
454 463 x.next = null;
455 464 x.prev = null;
456 465 x = next;
457 466 }
458 467 first = last = null;
459 468 size = 0;
460 469 modCount++;
461 470 }
462 471
463 472
464 473 // Positional Access Operations
465 474
466 475 /**
467 476 * Returns the element at the specified position in this list.
468 477 *
469 478 * @param index index of the element to return
470 479 * @return the element at the specified position in this list
471 480 * @throws IndexOutOfBoundsException {@inheritDoc}
472 481 */
473 482 public E get(int index) {
474 483 checkElementIndex(index);
475 484 return node(index).item;
476 485 }
477 486
478 487 /**
479 488 * Replaces the element at the specified position in this list with the
480 489 * specified element.
481 490 *
482 491 * @param index index of the element to replace
483 492 * @param element element to be stored at the specified position
484 493 * @return the element previously at the specified position
485 494 * @throws IndexOutOfBoundsException {@inheritDoc}
486 495 */
487 496 public E set(int index, E element) {
488 497 checkElementIndex(index);
489 498 Node<E> x = node(index);
490 499 E oldVal = x.item;
491 500 x.item = element;
492 501 return oldVal;
493 502 }
494 503
495 504 /**
496 505 * Inserts the specified element at the specified position in this list.
497 506 * Shifts the element currently at that position (if any) and any
498 507 * subsequent elements to the right (adds one to their indices).
499 508 *
500 509 * @param index index at which the specified element is to be inserted
501 510 * @param element element to be inserted
502 511 * @throws IndexOutOfBoundsException {@inheritDoc}
503 512 */
504 513 public void add(int index, E element) {
505 514 checkPositionIndex(index);
506 515
507 516 if (index == size)
508 517 linkLast(element);
509 518 else
510 519 linkBefore(element, node(index));
511 520 }
512 521
513 522 /**
514 523 * Removes the element at the specified position in this list. Shifts any
515 524 * subsequent elements to the left (subtracts one from their indices).
516 525 * Returns the element that was removed from the list.
517 526 *
518 527 * @param index the index of the element to be removed
519 528 * @return the element previously at the specified position
520 529 * @throws IndexOutOfBoundsException {@inheritDoc}
521 530 */
522 531 public E remove(int index) {
523 532 checkElementIndex(index);
524 533 return unlink(node(index));
525 534 }
526 535
527 536 /**
528 537 * Tells if the argument is the index of an existing element.
529 538 */
530 539 private boolean isElementIndex(int index) {
531 540 return index >= 0 && index < size;
532 541 }
533 542
534 543 /**
535 544 * Tells if the argument is the index of a valid position for an
536 545 * iterator or an add operation.
537 546 */
538 547 private boolean isPositionIndex(int index) {
539 548 return index >= 0 && index <= size;
540 549 }
541 550
542 551 /**
543 552 * Constructs an IndexOutOfBoundsException detail message.
544 553 * Of the many possible refactorings of the error handling code,
545 554 * this "outlining" performs best with both server and client VMs.
546 555 */
547 556 private String outOfBoundsMsg(int index) {
548 557 return "Index: "+index+", Size: "+size;
549 558 }
550 559
551 560 private void checkElementIndex(int index) {
552 561 if (!isElementIndex(index))
553 562 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
554 563 }
555 564
556 565 private void checkPositionIndex(int index) {
557 566 if (!isPositionIndex(index))
558 567 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
559 568 }
560 569
561 570 /**
562 571 * Returns the (non-null) Node at the specified element index.
563 572 */
564 573 Node<E> node(int index) {
565 574 // assert isElementIndex(index);
566 575
567 576 if (index < (size >> 1)) {
568 577 Node<E> x = first;
569 578 for (int i = 0; i < index; i++)
570 579 x = x.next;
571 580 return x;
572 581 } else {
573 582 Node<E> x = last;
574 583 for (int i = size - 1; i > index; i--)
575 584 x = x.prev;
576 585 return x;
577 586 }
578 587 }
579 588
580 589 // Search Operations
581 590
582 591 /**
583 592 * Returns the index of the first occurrence of the specified element
584 593 * in this list, or -1 if this list does not contain the element.
585 594 * More formally, returns the lowest index {@code i} such that
586 595 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
587 596 * or -1 if there is no such index.
588 597 *
589 598 * @param o element to search for
590 599 * @return the index of the first occurrence of the specified element in
591 600 * this list, or -1 if this list does not contain the element
592 601 */
593 602 public int indexOf(Object o) {
594 603 int index = 0;
595 604 if (o == null) {
596 605 for (Node<E> x = first; x != null; x = x.next) {
597 606 if (x.item == null)
598 607 return index;
599 608 index++;
600 609 }
601 610 } else {
602 611 for (Node<E> x = first; x != null; x = x.next) {
603 612 if (o.equals(x.item))
604 613 return index;
605 614 index++;
606 615 }
607 616 }
608 617 return -1;
609 618 }
610 619
611 620 /**
612 621 * Returns the index of the last occurrence of the specified element
613 622 * in this list, or -1 if this list does not contain the element.
614 623 * More formally, returns the highest index {@code i} such that
615 624 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
616 625 * or -1 if there is no such index.
617 626 *
618 627 * @param o element to search for
619 628 * @return the index of the last occurrence of the specified element in
620 629 * this list, or -1 if this list does not contain the element
621 630 */
622 631 public int lastIndexOf(Object o) {
623 632 int index = size;
624 633 if (o == null) {
625 634 for (Node<E> x = last; x != null; x = x.prev) {
626 635 index--;
627 636 if (x.item == null)
628 637 return index;
629 638 }
630 639 } else {
631 640 for (Node<E> x = last; x != null; x = x.prev) {
632 641 index--;
633 642 if (o.equals(x.item))
634 643 return index;
635 644 }
636 645 }
637 646 return -1;
638 647 }
639 648
640 649 // Queue operations.
641 650
642 651 /**
643 652 * Retrieves, but does not remove, the head (first element) of this list.
644 653 *
645 654 * @return the head of this list, or {@code null} if this list is empty
646 655 * @since 1.5
647 656 */
648 657 public E peek() {
649 658 final Node<E> f = first;
650 659 return (f == null) ? null : f.item;
651 660 }
652 661
653 662 /**
654 663 * Retrieves, but does not remove, the head (first element) of this list.
655 664 *
656 665 * @return the head of this list
657 666 * @throws NoSuchElementException if this list is empty
658 667 * @since 1.5
659 668 */
660 669 public E element() {
661 670 return getFirst();
662 671 }
663 672
664 673 /**
665 674 * Retrieves and removes the head (first element) of this list.
666 675 *
667 676 * @return the head of this list, or {@code null} if this list is empty
668 677 * @since 1.5
669 678 */
670 679 public E poll() {
671 680 final Node<E> f = first;
672 681 return (f == null) ? null : unlinkFirst(f);
673 682 }
674 683
675 684 /**
676 685 * Retrieves and removes the head (first element) of this list.
677 686 *
678 687 * @return the head of this list
679 688 * @throws NoSuchElementException if this list is empty
680 689 * @since 1.5
681 690 */
682 691 public E remove() {
683 692 return removeFirst();
684 693 }
685 694
686 695 /**
687 696 * Adds the specified element as the tail (last element) of this list.
688 697 *
689 698 * @param e the element to add
690 699 * @return {@code true} (as specified by {@link Queue#offer})
691 700 * @since 1.5
692 701 */
693 702 public boolean offer(E e) {
694 703 return add(e);
695 704 }
696 705
697 706 // Deque operations
698 707 /**
699 708 * Inserts the specified element at the front of this list.
700 709 *
701 710 * @param e the element to insert
702 711 * @return {@code true} (as specified by {@link Deque#offerFirst})
703 712 * @since 1.6
704 713 */
705 714 public boolean offerFirst(E e) {
706 715 addFirst(e);
707 716 return true;
708 717 }
709 718
710 719 /**
711 720 * Inserts the specified element at the end of this list.
712 721 *
713 722 * @param e the element to insert
714 723 * @return {@code true} (as specified by {@link Deque#offerLast})
715 724 * @since 1.6
716 725 */
717 726 public boolean offerLast(E e) {
718 727 addLast(e);
719 728 return true;
720 729 }
721 730
722 731 /**
723 732 * Retrieves, but does not remove, the first element of this list,
724 733 * or returns {@code null} if this list is empty.
725 734 *
726 735 * @return the first element of this list, or {@code null}
727 736 * if this list is empty
728 737 * @since 1.6
729 738 */
730 739 public E peekFirst() {
731 740 final Node<E> f = first;
732 741 return (f == null) ? null : f.item;
733 742 }
734 743
735 744 /**
736 745 * Retrieves, but does not remove, the last element of this list,
737 746 * or returns {@code null} if this list is empty.
738 747 *
739 748 * @return the last element of this list, or {@code null}
740 749 * if this list is empty
741 750 * @since 1.6
742 751 */
743 752 public E peekLast() {
744 753 final Node<E> l = last;
745 754 return (l == null) ? null : l.item;
746 755 }
747 756
748 757 /**
749 758 * Retrieves and removes the first element of this list,
750 759 * or returns {@code null} if this list is empty.
751 760 *
752 761 * @return the first element of this list, or {@code null} if
753 762 * this list is empty
754 763 * @since 1.6
755 764 */
756 765 public E pollFirst() {
757 766 final Node<E> f = first;
758 767 return (f == null) ? null : unlinkFirst(f);
759 768 }
760 769
761 770 /**
762 771 * Retrieves and removes the last element of this list,
763 772 * or returns {@code null} if this list is empty.
764 773 *
765 774 * @return the last element of this list, or {@code null} if
766 775 * this list is empty
767 776 * @since 1.6
768 777 */
769 778 public E pollLast() {
770 779 final Node<E> l = last;
771 780 return (l == null) ? null : unlinkLast(l);
772 781 }
773 782
774 783 /**
775 784 * Pushes an element onto the stack represented by this list. In other
776 785 * words, inserts the element at the front of this list.
777 786 *
778 787 * <p>This method is equivalent to {@link #addFirst}.
779 788 *
780 789 * @param e the element to push
781 790 * @since 1.6
782 791 */
783 792 public void push(E e) {
784 793 addFirst(e);
785 794 }
786 795
787 796 /**
788 797 * Pops an element from the stack represented by this list. In other
789 798 * words, removes and returns the first element of this list.
790 799 *
791 800 * <p>This method is equivalent to {@link #removeFirst()}.
792 801 *
793 802 * @return the element at the front of this list (which is the top
794 803 * of the stack represented by this list)
795 804 * @throws NoSuchElementException if this list is empty
796 805 * @since 1.6
797 806 */
798 807 public E pop() {
799 808 return removeFirst();
800 809 }
801 810
802 811 /**
803 812 * Removes the first occurrence of the specified element in this
804 813 * list (when traversing the list from head to tail). If the list
805 814 * does not contain the element, it is unchanged.
806 815 *
807 816 * @param o element to be removed from this list, if present
808 817 * @return {@code true} if the list contained the specified element
809 818 * @since 1.6
810 819 */
811 820 public boolean removeFirstOccurrence(Object o) {
812 821 return remove(o);
813 822 }
814 823
815 824 /**
816 825 * Removes the last occurrence of the specified element in this
817 826 * list (when traversing the list from head to tail). If the list
818 827 * does not contain the element, it is unchanged.
819 828 *
820 829 * @param o element to be removed from this list, if present
821 830 * @return {@code true} if the list contained the specified element
822 831 * @since 1.6
823 832 */
824 833 public boolean removeLastOccurrence(Object o) {
825 834 if (o == null) {
826 835 for (Node<E> x = last; x != null; x = x.prev) {
827 836 if (x.item == null) {
828 837 unlink(x);
829 838 return true;
830 839 }
831 840 }
832 841 } else {
833 842 for (Node<E> x = last; x != null; x = x.prev) {
834 843 if (o.equals(x.item)) {
835 844 unlink(x);
836 845 return true;
837 846 }
838 847 }
839 848 }
840 849 return false;
841 850 }
842 851
843 852 /**
844 853 * Returns a list-iterator of the elements in this list (in proper
845 854 * sequence), starting at the specified position in the list.
846 855 * Obeys the general contract of {@code List.listIterator(int)}.<p>
847 856 *
848 857 * The list-iterator is <i>fail-fast</i>: if the list is structurally
849 858 * modified at any time after the Iterator is created, in any way except
850 859 * through the list-iterator's own {@code remove} or {@code add}
851 860 * methods, the list-iterator will throw a
852 861 * {@code ConcurrentModificationException}. Thus, in the face of
853 862 * concurrent modification, the iterator fails quickly and cleanly, rather
854 863 * than risking arbitrary, non-deterministic behavior at an undetermined
855 864 * time in the future.
856 865 *
857 866 * @param index index of the first element to be returned from the
858 867 * list-iterator (by a call to {@code next})
859 868 * @return a ListIterator of the elements in this list (in proper
860 869 * sequence), starting at the specified position in the list
861 870 * @throws IndexOutOfBoundsException {@inheritDoc}
862 871 * @see List#listIterator(int)
863 872 */
864 873 public ListIterator<E> listIterator(int index) {
865 874 checkPositionIndex(index);
866 875 return new ListItr(index);
867 876 }
868 877
869 878 private class ListItr implements ListIterator<E> {
870 879 private Node<E> lastReturned = null;
871 880 private Node<E> next;
872 881 private int nextIndex;
873 882 private int expectedModCount = modCount;
874 883
875 884 ListItr(int index) {
876 885 // assert isPositionIndex(index);
877 886 next = (index == size) ? null : node(index);
878 887 nextIndex = index;
879 888 }
880 889
881 890 public boolean hasNext() {
882 891 return nextIndex < size;
883 892 }
884 893
885 894 public E next() {
886 895 checkForComodification();
887 896 if (!hasNext())
888 897 throw new NoSuchElementException();
889 898
890 899 lastReturned = next;
891 900 next = next.next;
892 901 nextIndex++;
893 902 return lastReturned.item;
894 903 }
895 904
896 905 public boolean hasPrevious() {
897 906 return nextIndex > 0;
898 907 }
899 908
900 909 public E previous() {
901 910 checkForComodification();
902 911 if (!hasPrevious())
903 912 throw new NoSuchElementException();
904 913
905 914 lastReturned = next = (next == null) ? last : next.prev;
906 915 nextIndex--;
907 916 return lastReturned.item;
908 917 }
909 918
910 919 public int nextIndex() {
911 920 return nextIndex;
912 921 }
913 922
914 923 public int previousIndex() {
915 924 return nextIndex - 1;
916 925 }
917 926
918 927 public void remove() {
919 928 checkForComodification();
920 929 if (lastReturned == null)
921 930 throw new IllegalStateException();
922 931
923 932 Node<E> lastNext = lastReturned.next;
924 933 unlink(lastReturned);
925 934 if (next == lastReturned)
926 935 next = lastNext;
927 936 else
928 937 nextIndex--;
929 938 lastReturned = null;
930 939 expectedModCount++;
931 940 }
932 941
933 942 public void set(E e) {
934 943 if (lastReturned == null)
935 944 throw new IllegalStateException();
936 945 checkForComodification();
937 946 lastReturned.item = e;
938 947 }
939 948
940 949 public void add(E e) {
941 950 checkForComodification();
942 951 lastReturned = null;
943 952 if (next == null)
944 953 linkLast(e);
945 954 else
946 955 linkBefore(e, next);
947 956 nextIndex++;
948 957 expectedModCount++;
949 958 }
950 959
951 960 final void checkForComodification() {
952 961 if (modCount != expectedModCount)
953 962 throw new ConcurrentModificationException();
954 963 }
955 964 }
956 965
957 966 private static class Node<E> {
958 967 E item;
959 968 Node<E> next;
960 969 Node<E> prev;
961 970
962 971 Node(Node<E> prev, E element, Node<E> next) {
963 972 this.item = element;
964 973 this.next = next;
965 974 this.prev = prev;
966 975 }
967 976 }
968 977
969 978 /**
970 979 * @since 1.6
971 980 */
972 981 public Iterator<E> descendingIterator() {
973 982 return new DescendingIterator();
974 983 }
975 984
976 985 /**
977 986 * Adapter to provide descending iterators via ListItr.previous
978 987 */
979 988 private class DescendingIterator implements Iterator<E> {
980 989 private final ListItr itr = new ListItr(size());
981 990 public boolean hasNext() {
982 991 return itr.hasPrevious();
983 992 }
984 993 public E next() {
985 994 return itr.previous();
986 995 }
987 996 public void remove() {
988 997 itr.remove();
989 998 }
990 999 }
991 1000
992 1001 @SuppressWarnings("unchecked")
993 1002 private LinkedList<E> superClone() {
994 1003 try {
995 1004 return (LinkedList<E>) super.clone();
996 1005 } catch (CloneNotSupportedException e) {
997 1006 throw new InternalError();
998 1007 }
999 1008 }
1000 1009
1001 1010 /**
1002 1011 * Returns a shallow copy of this {@code LinkedList}. (The elements
1003 1012 * themselves are not cloned.)
1004 1013 *
1005 1014 * @return a shallow copy of this {@code LinkedList} instance
1006 1015 */
1007 1016 public Object clone() {
1008 1017 LinkedList<E> clone = superClone();
1009 1018
1010 1019 // Put clone into "virgin" state
1011 1020 clone.first = clone.last = null;
1012 1021 clone.size = 0;
1013 1022 clone.modCount = 0;
1014 1023
1015 1024 // Initialize clone with our elements
1016 1025 for (Node<E> x = first; x != null; x = x.next)
1017 1026 clone.add(x.item);
1018 1027
1019 1028 return clone;
1020 1029 }
1021 1030
1022 1031 /**
1023 1032 * Returns an array containing all of the elements in this list
1024 1033 * in proper sequence (from first to last element).
1025 1034 *
1026 1035 * <p>The returned array will be "safe" in that no references to it are
1027 1036 * maintained by this list. (In other words, this method must allocate
1028 1037 * a new array). The caller is thus free to modify the returned array.
1029 1038 *
1030 1039 * <p>This method acts as bridge between array-based and collection-based
1031 1040 * APIs.
1032 1041 *
1033 1042 * @return an array containing all of the elements in this list
1034 1043 * in proper sequence
1035 1044 */
1036 1045 public Object[] toArray() {
1037 1046 Object[] result = new Object[size];
1038 1047 int i = 0;
1039 1048 for (Node<E> x = first; x != null; x = x.next)
1040 1049 result[i++] = x.item;
1041 1050 return result;
1042 1051 }
1043 1052
1044 1053 /**
1045 1054 * Returns an array containing all of the elements in this list in
1046 1055 * proper sequence (from first to last element); the runtime type of
1047 1056 * the returned array is that of the specified array. If the list fits
1048 1057 * in the specified array, it is returned therein. Otherwise, a new
1049 1058 * array is allocated with the runtime type of the specified array and
1050 1059 * the size of this list.
1051 1060 *
1052 1061 * <p>If the list fits in the specified array with room to spare (i.e.,
1053 1062 * the array has more elements than the list), the element in the array
1054 1063 * immediately following the end of the list is set to {@code null}.
1055 1064 * (This is useful in determining the length of the list <i>only</i> if
1056 1065 * the caller knows that the list does not contain any null elements.)
1057 1066 *
1058 1067 * <p>Like the {@link #toArray()} method, this method acts as bridge between
1059 1068 * array-based and collection-based APIs. Further, this method allows
1060 1069 * precise control over the runtime type of the output array, and may,
1061 1070 * under certain circumstances, be used to save allocation costs.
1062 1071 *
1063 1072 * <p>Suppose {@code x} is a list known to contain only strings.
1064 1073 * The following code can be used to dump the list into a newly
1065 1074 * allocated array of {@code String}:
1066 1075 *
1067 1076 * <pre>
1068 1077 * String[] y = x.toArray(new String[0]);</pre>
1069 1078 *
1070 1079 * Note that {@code toArray(new Object[0])} is identical in function to
1071 1080 * {@code toArray()}.
1072 1081 *
1073 1082 * @param a the array into which the elements of the list are to
1074 1083 * be stored, if it is big enough; otherwise, a new array of the
1075 1084 * same runtime type is allocated for this purpose.
1076 1085 * @return an array containing the elements of the list
1077 1086 * @throws ArrayStoreException if the runtime type of the specified array
1078 1087 * is not a supertype of the runtime type of every element in
1079 1088 * this list
1080 1089 * @throws NullPointerException if the specified array is null
1081 1090 */
1082 1091 @SuppressWarnings("unchecked")
1083 1092 public <T> T[] toArray(T[] a) {
1084 1093 if (a.length < size)
1085 1094 a = (T[])java.lang.reflect.Array.newInstance(
1086 1095 a.getClass().getComponentType(), size);
1087 1096 int i = 0;
1088 1097 Object[] result = a;
1089 1098 for (Node<E> x = first; x != null; x = x.next)
1090 1099 result[i++] = x.item;
1091 1100
1092 1101 if (a.length > size)
1093 1102 a[size] = null;
1094 1103
1095 1104 return a;
1096 1105 }
1097 1106
1098 1107 private static final long serialVersionUID = 876323262645176354L;
1099 1108
1100 1109 /**
1101 1110 * Saves the state of this {@code LinkedList} instance to a stream
1102 1111 * (that is, serializes it).
1103 1112 *
1104 1113 * @serialData The size of the list (the number of elements it
1105 1114 * contains) is emitted (int), followed by all of its
1106 1115 * elements (each an Object) in the proper order.
1107 1116 */
1108 1117 private void writeObject(java.io.ObjectOutputStream s)
1109 1118 throws java.io.IOException {
1110 1119 // Write out any hidden serialization magic
1111 1120 s.defaultWriteObject();
1112 1121
1113 1122 // Write out size
1114 1123 s.writeInt(size);
1115 1124
1116 1125 // Write out all elements in the proper order.
1117 1126 for (Node<E> x = first; x != null; x = x.next)
1118 1127 s.writeObject(x.item);
1119 1128 }
1120 1129
1121 1130 /**
1122 1131 * Reconstitutes this {@code LinkedList} instance from a stream
1123 1132 * (that is, deserializes it).
1124 1133 */
1125 1134 @SuppressWarnings("unchecked")
1126 1135 private void readObject(java.io.ObjectInputStream s)
1127 1136 throws java.io.IOException, ClassNotFoundException {
1128 1137 // Read in any hidden serialization magic
1129 1138 s.defaultReadObject();
1130 1139
1131 1140 // Read in size
1132 1141 int size = s.readInt();
1133 1142
1134 1143 // Read in all elements in the proper order.
1135 1144 for (int i = 0; i < size; i++)
1136 1145 linkLast((E)s.readObject());
1137 1146 }
1138 1147 }
↓ open down ↓ |
876 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX