24 */ |
24 */ |
25 |
25 |
26 package java.util; |
26 package java.util; |
27 |
27 |
28 /** |
28 /** |
29 * Linked list implementation of the <tt>List</tt> interface. Implements all |
29 * Linked list implementation of the {@code List} interface. Implements all |
30 * optional list operations, and permits all elements (including |
30 * optional list operations, and permits all elements (including |
31 * <tt>null</tt>). In addition to implementing the <tt>List</tt> interface, |
31 * {@code null}). In addition to implementing the {@code List} interface, |
32 * the <tt>LinkedList</tt> class provides uniformly named methods to |
32 * the {@code LinkedList} class provides uniformly named methods to |
33 * <tt>get</tt>, <tt>remove</tt> and <tt>insert</tt> an element at the |
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 |
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 |
35 * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque |
36 * double-ended queue}. <p> |
36 * double-ended queue}. |
37 * |
37 * |
38 * The class implements the <tt>Deque</tt> interface, providing |
38 * <p>The class implements the {@code Deque} interface, providing |
39 * first-in-first-out queue operations for <tt>add</tt>, |
39 * first-in-first-out queue operations for {@code add}, |
40 * <tt>poll</tt>, along with other stack and deque operations.<p> |
40 * {@code poll}, along with other stack and deque operations. |
41 * |
41 * |
42 * All of the operations perform as could be expected for a doubly-linked |
42 * <p>All of the operations perform as could be expected for a doubly-linked |
43 * list. Operations that index into the list will traverse the list from |
43 * list. Operations that index into the list will traverse the list from |
44 * the beginning or the end, whichever is closer to the specified index.<p> |
44 * the beginning or the end, whichever is closer to the specified index. |
45 * |
45 * |
46 * <p><strong>Note that this implementation is not synchronized.</strong> |
46 * <p><strong>Note that this implementation is not synchronized.</strong> |
47 * If multiple threads access a linked list concurrently, and at least |
47 * If multiple threads access a linked list concurrently, and at least |
48 * one of the threads modifies the list structurally, it <i>must</i> be |
48 * one of the threads modifies the list structurally, it <i>must</i> be |
49 * synchronized externally. (A structural modification is any operation |
49 * synchronized externally. (A structural modification is any operation |
56 * {@link Collections#synchronizedList Collections.synchronizedList} |
56 * {@link Collections#synchronizedList Collections.synchronizedList} |
57 * method. This is best done at creation time, to prevent accidental |
57 * method. This is best done at creation time, to prevent accidental |
58 * unsynchronized access to the list:<pre> |
58 * unsynchronized access to the list:<pre> |
59 * List list = Collections.synchronizedList(new LinkedList(...));</pre> |
59 * List list = Collections.synchronizedList(new LinkedList(...));</pre> |
60 * |
60 * |
61 * <p>The iterators returned by this class's <tt>iterator</tt> and |
61 * <p>The iterators returned by this class's {@code iterator} and |
62 * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is |
62 * {@code listIterator} methods are <i>fail-fast</i>: if the list is |
63 * structurally modified at any time after the iterator is created, in |
63 * structurally modified at any time after the iterator is created, in |
64 * any way except through the Iterator's own <tt>remove</tt> or |
64 * any way except through the Iterator's own {@code remove} or |
65 * <tt>add</tt> methods, the iterator will throw a {@link |
65 * {@code add} methods, the iterator will throw a {@link |
66 * ConcurrentModificationException}. Thus, in the face of concurrent |
66 * ConcurrentModificationException}. Thus, in the face of concurrent |
67 * modification, the iterator fails quickly and cleanly, rather than |
67 * modification, the iterator fails quickly and cleanly, rather than |
68 * risking arbitrary, non-deterministic behavior at an undetermined |
68 * risking arbitrary, non-deterministic behavior at an undetermined |
69 * time in the future. |
69 * time in the future. |
70 * |
70 * |
71 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed |
71 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed |
72 * as it is, generally speaking, impossible to make any hard guarantees in the |
72 * as it is, generally speaking, impossible to make any hard guarantees in the |
73 * presence of unsynchronized concurrent modification. Fail-fast iterators |
73 * presence of unsynchronized concurrent modification. Fail-fast iterators |
74 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. |
74 * throw {@code ConcurrentModificationException} on a best-effort basis. |
75 * Therefore, it would be wrong to write a program that depended on this |
75 * Therefore, it would be wrong to write a program that depended on this |
76 * exception for its correctness: <i>the fail-fast behavior of iterators |
76 * exception for its correctness: <i>the fail-fast behavior of iterators |
77 * should be used only to detect bugs.</i> |
77 * should be used only to detect bugs.</i> |
78 * |
78 * |
79 * <p>This class is a member of the |
79 * <p>This class is a member of the |
114 this(); |
125 this(); |
115 addAll(c); |
126 addAll(c); |
116 } |
127 } |
117 |
128 |
118 /** |
129 /** |
|
130 * Links e as first element. |
|
131 */ |
|
132 private void linkFirst(E e) { |
|
133 final Node<E> f = first; |
|
134 final Node<E> newNode = new Node<E>(null, e, f); |
|
135 first = newNode; |
|
136 if (f == null) |
|
137 last = newNode; |
|
138 else |
|
139 f.prev = newNode; |
|
140 size++; |
|
141 modCount++; |
|
142 } |
|
143 |
|
144 /** |
|
145 * Links e as last element. |
|
146 */ |
|
147 void linkLast(E e) { |
|
148 final Node<E> l = last; |
|
149 final Node<E> newNode = new Node<E>(l, e, null); |
|
150 last = newNode; |
|
151 if (l == null) |
|
152 first = newNode; |
|
153 else |
|
154 l.next = newNode; |
|
155 size++; |
|
156 modCount++; |
|
157 } |
|
158 |
|
159 /** |
|
160 * Inserts element e before non-null Node succ. |
|
161 */ |
|
162 void linkBefore(E e, Node<E> succ) { |
|
163 // assert succ != null; |
|
164 final Node<E> pred = succ.prev; |
|
165 final Node<E> newNode = new Node<E>(pred, e, succ); |
|
166 succ.prev = newNode; |
|
167 if (pred == null) |
|
168 first = newNode; |
|
169 else |
|
170 pred.next = newNode; |
|
171 size++; |
|
172 modCount++; |
|
173 } |
|
174 |
|
175 /** |
|
176 * Unlinks non-null first node f. |
|
177 */ |
|
178 private E unlinkFirst(Node<E> f) { |
|
179 // assert f == first && f != null; |
|
180 final E element = f.item; |
|
181 final Node<E> next = f.next; |
|
182 f.item = null; |
|
183 f.next = null; // help GC |
|
184 first = next; |
|
185 if (next == null) |
|
186 last = null; |
|
187 else |
|
188 next.prev = null; |
|
189 size--; |
|
190 modCount++; |
|
191 return element; |
|
192 } |
|
193 |
|
194 /** |
|
195 * Unlinks non-null last node l. |
|
196 */ |
|
197 private E unlinkLast(Node<E> l) { |
|
198 // assert l == last && l != null; |
|
199 final E element = l.item; |
|
200 final Node<E> prev = l.prev; |
|
201 l.item = null; |
|
202 l.prev = null; // help GC |
|
203 last = prev; |
|
204 if (prev == null) |
|
205 first = null; |
|
206 else |
|
207 prev.next = null; |
|
208 size--; |
|
209 modCount++; |
|
210 return element; |
|
211 } |
|
212 |
|
213 /** |
|
214 * Unlinks non-null node x. |
|
215 */ |
|
216 E unlink(Node<E> x) { |
|
217 // assert x != null; |
|
218 final E element = x.item; |
|
219 final Node<E> next = x.next; |
|
220 final Node<E> prev = x.prev; |
|
221 |
|
222 if (prev == null) { |
|
223 first = next; |
|
224 } else { |
|
225 prev.next = next; |
|
226 x.prev = null; |
|
227 } |
|
228 |
|
229 if (next == null) { |
|
230 last = prev; |
|
231 } else { |
|
232 next.prev = prev; |
|
233 x.next = null; |
|
234 } |
|
235 |
|
236 x.item = null; |
|
237 size--; |
|
238 modCount++; |
|
239 return element; |
|
240 } |
|
241 |
|
242 /** |
119 * Returns the first element in this list. |
243 * Returns the first element in this list. |
120 * |
244 * |
121 * @return the first element in this list |
245 * @return the first element in this list |
122 * @throws NoSuchElementException if this list is empty |
246 * @throws NoSuchElementException if this list is empty |
123 */ |
247 */ |
124 public E getFirst() { |
248 public E getFirst() { |
125 if (size==0) |
249 final Node<E> f = first; |
|
250 if (f == null) |
126 throw new NoSuchElementException(); |
251 throw new NoSuchElementException(); |
127 |
252 return f.item; |
128 return header.next.element; |
|
129 } |
253 } |
130 |
254 |
131 /** |
255 /** |
132 * Returns the last element in this list. |
256 * Returns the last element in this list. |
133 * |
257 * |
134 * @return the last element in this list |
258 * @return the last element in this list |
135 * @throws NoSuchElementException if this list is empty |
259 * @throws NoSuchElementException if this list is empty |
136 */ |
260 */ |
137 public E getLast() { |
261 public E getLast() { |
138 if (size==0) |
262 final Node<E> l = last; |
|
263 if (l == null) |
139 throw new NoSuchElementException(); |
264 throw new NoSuchElementException(); |
140 |
265 return l.item; |
141 return header.previous.element; |
|
142 } |
266 } |
143 |
267 |
144 /** |
268 /** |
145 * Removes and returns the first element from this list. |
269 * Removes and returns the first element from this list. |
146 * |
270 * |
147 * @return the first element from this list |
271 * @return the first element from this list |
148 * @throws NoSuchElementException if this list is empty |
272 * @throws NoSuchElementException if this list is empty |
149 */ |
273 */ |
150 public E removeFirst() { |
274 public E removeFirst() { |
151 return remove(header.next); |
275 final Node<E> f = first; |
|
276 if (f == null) |
|
277 throw new NoSuchElementException(); |
|
278 return unlinkFirst(f); |
152 } |
279 } |
153 |
280 |
154 /** |
281 /** |
155 * Removes and returns the last element from this list. |
282 * Removes and returns the last element from this list. |
156 * |
283 * |
157 * @return the last element from this list |
284 * @return the last element from this list |
158 * @throws NoSuchElementException if this list is empty |
285 * @throws NoSuchElementException if this list is empty |
159 */ |
286 */ |
160 public E removeLast() { |
287 public E removeLast() { |
161 return remove(header.previous); |
288 final Node<E> l = last; |
|
289 if (l == null) |
|
290 throw new NoSuchElementException(); |
|
291 return unlinkLast(l); |
162 } |
292 } |
163 |
293 |
164 /** |
294 /** |
165 * Inserts the specified element at the beginning of this list. |
295 * Inserts the specified element at the beginning of this list. |
166 * |
296 * |
167 * @param e the element to add |
297 * @param e the element to add |
168 */ |
298 */ |
169 public void addFirst(E e) { |
299 public void addFirst(E e) { |
170 addBefore(e, header.next); |
300 linkFirst(e); |
171 } |
301 } |
172 |
302 |
173 /** |
303 /** |
174 * Appends the specified element to the end of this list. |
304 * Appends the specified element to the end of this list. |
175 * |
305 * |
176 * <p>This method is equivalent to {@link #add}. |
306 * <p>This method is equivalent to {@link #add}. |
177 * |
307 * |
178 * @param e the element to add |
308 * @param e the element to add |
179 */ |
309 */ |
180 public void addLast(E e) { |
310 public void addLast(E e) { |
181 addBefore(e, header); |
311 linkLast(e); |
182 } |
312 } |
183 |
313 |
184 /** |
314 /** |
185 * Returns <tt>true</tt> if this list contains the specified element. |
315 * Returns {@code true} if this list contains the specified element. |
186 * More formally, returns <tt>true</tt> if and only if this list contains |
316 * More formally, returns {@code true} if and only if this list contains |
187 * at least one element <tt>e</tt> such that |
317 * at least one element {@code e} such that |
188 * <tt>(o==null ? e==null : o.equals(e))</tt>. |
318 * <tt>(o==null ? e==null : o.equals(e))</tt>. |
189 * |
319 * |
190 * @param o element whose presence in this list is to be tested |
320 * @param o element whose presence in this list is to be tested |
191 * @return <tt>true</tt> if this list contains the specified element |
321 * @return {@code true} if this list contains the specified element |
192 */ |
322 */ |
193 public boolean contains(Object o) { |
323 public boolean contains(Object o) { |
194 return indexOf(o) != -1; |
324 return indexOf(o) != -1; |
195 } |
325 } |
196 |
326 |
207 * Appends the specified element to the end of this list. |
337 * Appends the specified element to the end of this list. |
208 * |
338 * |
209 * <p>This method is equivalent to {@link #addLast}. |
339 * <p>This method is equivalent to {@link #addLast}. |
210 * |
340 * |
211 * @param e element to be appended to this list |
341 * @param e element to be appended to this list |
212 * @return <tt>true</tt> (as specified by {@link Collection#add}) |
342 * @return {@code true} (as specified by {@link Collection#add}) |
213 */ |
343 */ |
214 public boolean add(E e) { |
344 public boolean add(E e) { |
215 addBefore(e, header); |
345 linkLast(e); |
216 return true; |
346 return true; |
217 } |
347 } |
218 |
348 |
219 /** |
349 /** |
220 * Removes the first occurrence of the specified element from this list, |
350 * Removes the first occurrence of the specified element from this list, |
221 * if it is present. If this list does not contain the element, it is |
351 * if it is present. If this list does not contain the element, it is |
222 * unchanged. More formally, removes the element with the lowest index |
352 * unchanged. More formally, removes the element with the lowest index |
223 * <tt>i</tt> such that |
353 * {@code i} such that |
224 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> |
354 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> |
225 * (if such an element exists). Returns <tt>true</tt> if this list |
355 * (if such an element exists). Returns {@code true} if this list |
226 * contained the specified element (or equivalently, if this list |
356 * contained the specified element (or equivalently, if this list |
227 * changed as a result of the call). |
357 * changed as a result of the call). |
228 * |
358 * |
229 * @param o element to be removed from this list, if present |
359 * @param o element to be removed from this list, if present |
230 * @return <tt>true</tt> if this list contained the specified element |
360 * @return {@code true} if this list contained the specified element |
231 */ |
361 */ |
232 public boolean remove(Object o) { |
362 public boolean remove(Object o) { |
233 if (o==null) { |
363 if (o == null) { |
234 for (Entry<E> e = header.next; e != header; e = e.next) { |
364 for (Node<E> x = first; x != null; x = x.next) { |
235 if (e.element==null) { |
365 if (x.item == null) { |
236 remove(e); |
366 unlink(x); |
237 return true; |
367 return true; |
238 } |
368 } |
239 } |
369 } |
240 } else { |
370 } else { |
241 for (Entry<E> e = header.next; e != header; e = e.next) { |
371 for (Node<E> x = first; x != null; x = x.next) { |
242 if (o.equals(e.element)) { |
372 if (o.equals(x.item)) { |
243 remove(e); |
373 unlink(x); |
244 return true; |
374 return true; |
245 } |
375 } |
246 } |
376 } |
247 } |
377 } |
248 return false; |
378 return false; |
273 * specified collection's iterator. |
403 * specified collection's iterator. |
274 * |
404 * |
275 * @param index index at which to insert the first element |
405 * @param index index at which to insert the first element |
276 * from the specified collection |
406 * from the specified collection |
277 * @param c collection containing elements to be added to this list |
407 * @param c collection containing elements to be added to this list |
278 * @return <tt>true</tt> if this list changed as a result of the call |
408 * @return {@code true} if this list changed as a result of the call |
279 * @throws IndexOutOfBoundsException {@inheritDoc} |
409 * @throws IndexOutOfBoundsException {@inheritDoc} |
280 * @throws NullPointerException if the specified collection is null |
410 * @throws NullPointerException if the specified collection is null |
281 */ |
411 */ |
282 public boolean addAll(int index, Collection<? extends E> c) { |
412 public boolean addAll(int index, Collection<? extends E> c) { |
283 if (index < 0 || index > size) |
413 checkPositionIndex(index); |
284 throw new IndexOutOfBoundsException("Index: "+index+ |
414 |
285 ", Size: "+size); |
|
286 Object[] a = c.toArray(); |
415 Object[] a = c.toArray(); |
287 int numNew = a.length; |
416 int numNew = a.length; |
288 if (numNew==0) |
417 if (numNew == 0) |
289 return false; |
418 return false; |
|
419 |
|
420 Node<E> pred, succ; |
|
421 if (index == size) { |
|
422 succ = null; |
|
423 pred = last; |
|
424 } else { |
|
425 succ = node(index); |
|
426 pred = succ.prev; |
|
427 } |
|
428 |
|
429 for (Object o : a) { |
|
430 @SuppressWarnings("unchecked") E e = (E) o; |
|
431 Node<E> newNode = new Node<E>(pred, e, null); |
|
432 if (pred == null) |
|
433 first = newNode; |
|
434 else |
|
435 pred.next = newNode; |
|
436 pred = newNode; |
|
437 } |
|
438 |
|
439 if (succ == null) { |
|
440 last = pred; |
|
441 } else { |
|
442 pred.next = succ; |
|
443 succ.prev = pred; |
|
444 } |
|
445 |
|
446 size += numNew; |
290 modCount++; |
447 modCount++; |
291 |
|
292 Entry<E> successor = (index==size ? header : entry(index)); |
|
293 Entry<E> predecessor = successor.previous; |
|
294 for (int i=0; i<numNew; i++) { |
|
295 Entry<E> e = new Entry<E>((E)a[i], successor, predecessor); |
|
296 predecessor.next = e; |
|
297 predecessor = e; |
|
298 } |
|
299 successor.previous = predecessor; |
|
300 |
|
301 size += numNew; |
|
302 return true; |
448 return true; |
303 } |
449 } |
304 |
450 |
305 /** |
451 /** |
306 * Removes all of the elements from this list. |
452 * Removes all of the elements from this list. |
|
453 * The list will be empty after this call returns. |
307 */ |
454 */ |
308 public void clear() { |
455 public void clear() { |
309 Entry<E> e = header.next; |
456 // Clearing all of the links between nodes is "unnecessary", but: |
310 while (e != header) { |
457 // - helps a generational GC if the discarded nodes inhabit |
311 Entry<E> next = e.next; |
458 // more than one generation |
312 e.next = e.previous = null; |
459 // - is sure to free memory even if there is a reachable Iterator |
313 e.element = null; |
460 for (Node<E> x = first; x != null; ) { |
314 e = next; |
461 Node<E> next = x.next; |
315 } |
462 x.item = null; |
316 header.next = header.previous = header; |
463 x.next = null; |
|
464 x.prev = null; |
|
465 x = next; |
|
466 } |
|
467 first = last = null; |
317 size = 0; |
468 size = 0; |
318 modCount++; |
469 modCount++; |
319 } |
470 } |
320 |
471 |
321 |
472 |
369 * @param index the index of the element to be removed |
527 * @param index the index of the element to be removed |
370 * @return the element previously at the specified position |
528 * @return the element previously at the specified position |
371 * @throws IndexOutOfBoundsException {@inheritDoc} |
529 * @throws IndexOutOfBoundsException {@inheritDoc} |
372 */ |
530 */ |
373 public E remove(int index) { |
531 public E remove(int index) { |
374 return remove(entry(index)); |
532 checkElementIndex(index); |
375 } |
533 return unlink(node(index)); |
376 |
534 } |
377 /** |
535 |
378 * Returns the indexed entry. |
536 /** |
379 */ |
537 * Tells if the argument is the index of an existing element. |
380 private Entry<E> entry(int index) { |
538 */ |
381 if (index < 0 || index >= size) |
539 private boolean isElementIndex(int index) { |
382 throw new IndexOutOfBoundsException("Index: "+index+ |
540 return index >= 0 && index < size; |
383 ", Size: "+size); |
541 } |
384 Entry<E> e = header; |
542 |
|
543 /** |
|
544 * Tells if the argument is the index of a valid position for an |
|
545 * iterator or an add operation. |
|
546 */ |
|
547 private boolean isPositionIndex(int index) { |
|
548 return index >= 0 && index <= size; |
|
549 } |
|
550 |
|
551 /** |
|
552 * Constructs an IndexOutOfBoundsException detail message. |
|
553 * Of the many possible refactorings of the error handling code, |
|
554 * this "outlining" performs best with both server and client VMs. |
|
555 */ |
|
556 private String outOfBoundsMsg(int index) { |
|
557 return "Index: "+index+", Size: "+size; |
|
558 } |
|
559 |
|
560 private void checkElementIndex(int index) { |
|
561 if (!isElementIndex(index)) |
|
562 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); |
|
563 } |
|
564 |
|
565 private void checkPositionIndex(int index) { |
|
566 if (!isPositionIndex(index)) |
|
567 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); |
|
568 } |
|
569 |
|
570 /** |
|
571 * Returns the (non-null) Node at the specified element index. |
|
572 */ |
|
573 Node<E> node(int index) { |
|
574 // assert isElementIndex(index); |
|
575 |
385 if (index < (size >> 1)) { |
576 if (index < (size >> 1)) { |
386 for (int i = 0; i <= index; i++) |
577 Node<E> x = first; |
387 e = e.next; |
578 for (int i = 0; i < index; i++) |
|
579 x = x.next; |
|
580 return x; |
388 } else { |
581 } else { |
389 for (int i = size; i > index; i--) |
582 Node<E> x = last; |
390 e = e.previous; |
583 for (int i = size - 1; i > index; i--) |
391 } |
584 x = x.prev; |
392 return e; |
585 return x; |
393 } |
586 } |
394 |
587 } |
395 |
588 |
396 // Search Operations |
589 // Search Operations |
397 |
590 |
398 /** |
591 /** |
399 * Returns the index of the first occurrence of the specified element |
592 * Returns the index of the first occurrence of the specified element |
400 * in this list, or -1 if this list does not contain the element. |
593 * in this list, or -1 if this list does not contain the element. |
401 * More formally, returns the lowest index <tt>i</tt> such that |
594 * More formally, returns the lowest index {@code i} such that |
402 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, |
595 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, |
403 * or -1 if there is no such index. |
596 * or -1 if there is no such index. |
404 * |
597 * |
405 * @param o element to search for |
598 * @param o element to search for |
406 * @return the index of the first occurrence of the specified element in |
599 * @return the index of the first occurrence of the specified element in |
407 * this list, or -1 if this list does not contain the element |
600 * this list, or -1 if this list does not contain the element |
408 */ |
601 */ |
409 public int indexOf(Object o) { |
602 public int indexOf(Object o) { |
410 int index = 0; |
603 int index = 0; |
411 if (o==null) { |
604 if (o == null) { |
412 for (Entry e = header.next; e != header; e = e.next) { |
605 for (Node<E> x = first; x != null; x = x.next) { |
413 if (e.element==null) |
606 if (x.item == null) |
414 return index; |
607 return index; |
415 index++; |
608 index++; |
416 } |
609 } |
417 } else { |
610 } else { |
418 for (Entry e = header.next; e != header; e = e.next) { |
611 for (Node<E> x = first; x != null; x = x.next) { |
419 if (o.equals(e.element)) |
612 if (o.equals(x.item)) |
420 return index; |
613 return index; |
421 index++; |
614 index++; |
422 } |
615 } |
423 } |
616 } |
424 return -1; |
617 return -1; |
425 } |
618 } |
426 |
619 |
427 /** |
620 /** |
428 * Returns the index of the last occurrence of the specified element |
621 * Returns the index of the last occurrence of the specified element |
429 * in this list, or -1 if this list does not contain the element. |
622 * in this list, or -1 if this list does not contain the element. |
430 * More formally, returns the highest index <tt>i</tt> such that |
623 * More formally, returns the highest index {@code i} such that |
431 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, |
624 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, |
432 * or -1 if there is no such index. |
625 * or -1 if there is no such index. |
433 * |
626 * |
434 * @param o element to search for |
627 * @param o element to search for |
435 * @return the index of the last occurrence of the specified element in |
628 * @return the index of the last occurrence of the specified element in |
436 * this list, or -1 if this list does not contain the element |
629 * this list, or -1 if this list does not contain the element |
437 */ |
630 */ |
438 public int lastIndexOf(Object o) { |
631 public int lastIndexOf(Object o) { |
439 int index = size; |
632 int index = size; |
440 if (o==null) { |
633 if (o == null) { |
441 for (Entry e = header.previous; e != header; e = e.previous) { |
634 for (Node<E> x = last; x != null; x = x.prev) { |
442 index--; |
635 index--; |
443 if (e.element==null) |
636 if (x.item == null) |
444 return index; |
637 return index; |
445 } |
638 } |
446 } else { |
639 } else { |
447 for (Entry e = header.previous; e != header; e = e.previous) { |
640 for (Node<E> x = last; x != null; x = x.prev) { |
448 index--; |
641 index--; |
449 if (o.equals(e.element)) |
642 if (o.equals(x.item)) |
450 return index; |
643 return index; |
451 } |
644 } |
452 } |
645 } |
453 return -1; |
646 return -1; |
454 } |
647 } |
455 |
648 |
456 // Queue operations. |
649 // Queue operations. |
457 |
650 |
458 /** |
651 /** |
459 * Retrieves, but does not remove, the head (first element) of this list. |
652 * Retrieves, but does not remove, the head (first element) of this list. |
460 * @return the head of this list, or <tt>null</tt> if this list is empty |
653 * |
|
654 * @return the head of this list, or {@code null} if this list is empty |
461 * @since 1.5 |
655 * @since 1.5 |
462 */ |
656 */ |
463 public E peek() { |
657 public E peek() { |
464 if (size==0) |
658 final Node<E> f = first; |
465 return null; |
659 return (f == null) ? null : f.item; |
466 return getFirst(); |
|
467 } |
660 } |
468 |
661 |
469 /** |
662 /** |
470 * Retrieves, but does not remove, the head (first element) of this list. |
663 * Retrieves, but does not remove, the head (first element) of this list. |
|
664 * |
471 * @return the head of this list |
665 * @return the head of this list |
472 * @throws NoSuchElementException if this list is empty |
666 * @throws NoSuchElementException if this list is empty |
473 * @since 1.5 |
667 * @since 1.5 |
474 */ |
668 */ |
475 public E element() { |
669 public E element() { |
476 return getFirst(); |
670 return getFirst(); |
477 } |
671 } |
478 |
672 |
479 /** |
673 /** |
480 * Retrieves and removes the head (first element) of this list |
674 * Retrieves and removes the head (first element) of this list. |
481 * @return the head of this list, or <tt>null</tt> if this list is empty |
675 * |
|
676 * @return the head of this list, or {@code null} if this list is empty |
482 * @since 1.5 |
677 * @since 1.5 |
483 */ |
678 */ |
484 public E poll() { |
679 public E poll() { |
485 if (size==0) |
680 final Node<E> f = first; |
486 return null; |
681 return (f == null) ? null : unlinkFirst(f); |
487 return removeFirst(); |
|
488 } |
682 } |
489 |
683 |
490 /** |
684 /** |
491 * Retrieves and removes the head (first element) of this list. |
685 * Retrieves and removes the head (first element) of this list. |
492 * |
686 * |
524 |
718 |
525 /** |
719 /** |
526 * Inserts the specified element at the end of this list. |
720 * Inserts the specified element at the end of this list. |
527 * |
721 * |
528 * @param e the element to insert |
722 * @param e the element to insert |
529 * @return <tt>true</tt> (as specified by {@link Deque#offerLast}) |
723 * @return {@code true} (as specified by {@link Deque#offerLast}) |
530 * @since 1.6 |
724 * @since 1.6 |
531 */ |
725 */ |
532 public boolean offerLast(E e) { |
726 public boolean offerLast(E e) { |
533 addLast(e); |
727 addLast(e); |
534 return true; |
728 return true; |
535 } |
729 } |
536 |
730 |
537 /** |
731 /** |
538 * Retrieves, but does not remove, the first element of this list, |
732 * Retrieves, but does not remove, the first element of this list, |
539 * or returns <tt>null</tt> if this list is empty. |
733 * or returns {@code null} if this list is empty. |
540 * |
734 * |
541 * @return the first element of this list, or <tt>null</tt> |
735 * @return the first element of this list, or {@code null} |
542 * if this list is empty |
736 * if this list is empty |
543 * @since 1.6 |
737 * @since 1.6 |
544 */ |
738 */ |
545 public E peekFirst() { |
739 public E peekFirst() { |
546 if (size==0) |
740 final Node<E> f = first; |
547 return null; |
741 return (f == null) ? null : f.item; |
548 return getFirst(); |
742 } |
549 } |
|
550 |
743 |
551 /** |
744 /** |
552 * Retrieves, but does not remove, the last element of this list, |
745 * Retrieves, but does not remove, the last element of this list, |
553 * or returns <tt>null</tt> if this list is empty. |
746 * or returns {@code null} if this list is empty. |
554 * |
747 * |
555 * @return the last element of this list, or <tt>null</tt> |
748 * @return the last element of this list, or {@code null} |
556 * if this list is empty |
749 * if this list is empty |
557 * @since 1.6 |
750 * @since 1.6 |
558 */ |
751 */ |
559 public E peekLast() { |
752 public E peekLast() { |
560 if (size==0) |
753 final Node<E> l = last; |
561 return null; |
754 return (l == null) ? null : l.item; |
562 return getLast(); |
|
563 } |
755 } |
564 |
756 |
565 /** |
757 /** |
566 * Retrieves and removes the first element of this list, |
758 * Retrieves and removes the first element of this list, |
567 * or returns <tt>null</tt> if this list is empty. |
759 * or returns {@code null} if this list is empty. |
568 * |
760 * |
569 * @return the first element of this list, or <tt>null</tt> if |
761 * @return the first element of this list, or {@code null} if |
570 * this list is empty |
762 * this list is empty |
571 * @since 1.6 |
763 * @since 1.6 |
572 */ |
764 */ |
573 public E pollFirst() { |
765 public E pollFirst() { |
574 if (size==0) |
766 final Node<E> f = first; |
575 return null; |
767 return (f == null) ? null : unlinkFirst(f); |
576 return removeFirst(); |
|
577 } |
768 } |
578 |
769 |
579 /** |
770 /** |
580 * Retrieves and removes the last element of this list, |
771 * Retrieves and removes the last element of this list, |
581 * or returns <tt>null</tt> if this list is empty. |
772 * or returns {@code null} if this list is empty. |
582 * |
773 * |
583 * @return the last element of this list, or <tt>null</tt> if |
774 * @return the last element of this list, or {@code null} if |
584 * this list is empty |
775 * this list is empty |
585 * @since 1.6 |
776 * @since 1.6 |
586 */ |
777 */ |
587 public E pollLast() { |
778 public E pollLast() { |
588 if (size==0) |
779 final Node<E> l = last; |
589 return null; |
780 return (l == null) ? null : unlinkLast(l); |
590 return removeLast(); |
|
591 } |
781 } |
592 |
782 |
593 /** |
783 /** |
594 * Pushes an element onto the stack represented by this list. In other |
784 * Pushes an element onto the stack represented by this list. In other |
595 * words, inserts the element at the front of this list. |
785 * words, inserts the element at the front of this list. |
635 * Removes the last occurrence of the specified element in this |
825 * Removes the last occurrence of the specified element in this |
636 * list (when traversing the list from head to tail). If the list |
826 * list (when traversing the list from head to tail). If the list |
637 * does not contain the element, it is unchanged. |
827 * does not contain the element, it is unchanged. |
638 * |
828 * |
639 * @param o element to be removed from this list, if present |
829 * @param o element to be removed from this list, if present |
640 * @return <tt>true</tt> if the list contained the specified element |
830 * @return {@code true} if the list contained the specified element |
641 * @since 1.6 |
831 * @since 1.6 |
642 */ |
832 */ |
643 public boolean removeLastOccurrence(Object o) { |
833 public boolean removeLastOccurrence(Object o) { |
644 if (o==null) { |
834 if (o == null) { |
645 for (Entry<E> e = header.previous; e != header; e = e.previous) { |
835 for (Node<E> x = last; x != null; x = x.prev) { |
646 if (e.element==null) { |
836 if (x.item == null) { |
647 remove(e); |
837 unlink(x); |
648 return true; |
838 return true; |
649 } |
839 } |
650 } |
840 } |
651 } else { |
841 } else { |
652 for (Entry<E> e = header.previous; e != header; e = e.previous) { |
842 for (Node<E> x = last; x != null; x = x.prev) { |
653 if (o.equals(e.element)) { |
843 if (o.equals(x.item)) { |
654 remove(e); |
844 unlink(x); |
655 return true; |
845 return true; |
656 } |
846 } |
657 } |
847 } |
658 } |
848 } |
659 return false; |
849 return false; |
660 } |
850 } |
661 |
851 |
662 /** |
852 /** |
663 * Returns a list-iterator of the elements in this list (in proper |
853 * Returns a list-iterator of the elements in this list (in proper |
664 * sequence), starting at the specified position in the list. |
854 * sequence), starting at the specified position in the list. |
665 * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p> |
855 * Obeys the general contract of {@code List.listIterator(int)}.<p> |
666 * |
856 * |
667 * The list-iterator is <i>fail-fast</i>: if the list is structurally |
857 * The list-iterator is <i>fail-fast</i>: if the list is structurally |
668 * modified at any time after the Iterator is created, in any way except |
858 * modified at any time after the Iterator is created, in any way except |
669 * through the list-iterator's own <tt>remove</tt> or <tt>add</tt> |
859 * through the list-iterator's own {@code remove} or {@code add} |
670 * methods, the list-iterator will throw a |
860 * methods, the list-iterator will throw a |
671 * <tt>ConcurrentModificationException</tt>. Thus, in the face of |
861 * {@code ConcurrentModificationException}. Thus, in the face of |
672 * concurrent modification, the iterator fails quickly and cleanly, rather |
862 * concurrent modification, the iterator fails quickly and cleanly, rather |
673 * than risking arbitrary, non-deterministic behavior at an undetermined |
863 * than risking arbitrary, non-deterministic behavior at an undetermined |
674 * time in the future. |
864 * time in the future. |
675 * |
865 * |
676 * @param index index of the first element to be returned from the |
866 * @param index index of the first element to be returned from the |
677 * list-iterator (by a call to <tt>next</tt>) |
867 * list-iterator (by a call to {@code next}) |
678 * @return a ListIterator of the elements in this list (in proper |
868 * @return a ListIterator of the elements in this list (in proper |
679 * sequence), starting at the specified position in the list |
869 * sequence), starting at the specified position in the list |
680 * @throws IndexOutOfBoundsException {@inheritDoc} |
870 * @throws IndexOutOfBoundsException {@inheritDoc} |
681 * @see List#listIterator(int) |
871 * @see List#listIterator(int) |
682 */ |
872 */ |
683 public ListIterator<E> listIterator(int index) { |
873 public ListIterator<E> listIterator(int index) { |
|
874 checkPositionIndex(index); |
684 return new ListItr(index); |
875 return new ListItr(index); |
685 } |
876 } |
686 |
877 |
687 private class ListItr implements ListIterator<E> { |
878 private class ListItr implements ListIterator<E> { |
688 private Entry<E> lastReturned = header; |
879 private Node<E> lastReturned = null; |
689 private Entry<E> next; |
880 private Node<E> next; |
690 private int nextIndex; |
881 private int nextIndex; |
691 private int expectedModCount = modCount; |
882 private int expectedModCount = modCount; |
692 |
883 |
693 ListItr(int index) { |
884 ListItr(int index) { |
694 if (index < 0 || index > size) |
885 // assert isPositionIndex(index); |
695 throw new IndexOutOfBoundsException("Index: "+index+ |
886 next = (index == size) ? null : node(index); |
696 ", Size: "+size); |
887 nextIndex = index; |
697 if (index < (size >> 1)) { |
|
698 next = header.next; |
|
699 for (nextIndex=0; nextIndex<index; nextIndex++) |
|
700 next = next.next; |
|
701 } else { |
|
702 next = header; |
|
703 for (nextIndex=size; nextIndex>index; nextIndex--) |
|
704 next = next.previous; |
|
705 } |
|
706 } |
888 } |
707 |
889 |
708 public boolean hasNext() { |
890 public boolean hasNext() { |
709 return nextIndex != size; |
891 return nextIndex < size; |
710 } |
892 } |
711 |
893 |
712 public E next() { |
894 public E next() { |
713 checkForComodification(); |
895 checkForComodification(); |
714 if (nextIndex == size) |
896 if (!hasNext()) |
715 throw new NoSuchElementException(); |
897 throw new NoSuchElementException(); |
716 |
898 |
717 lastReturned = next; |
899 lastReturned = next; |
718 next = next.next; |
900 next = next.next; |
719 nextIndex++; |
901 nextIndex++; |
720 return lastReturned.element; |
902 return lastReturned.item; |
721 } |
903 } |
722 |
904 |
723 public boolean hasPrevious() { |
905 public boolean hasPrevious() { |
724 return nextIndex != 0; |
906 return nextIndex > 0; |
725 } |
907 } |
726 |
908 |
727 public E previous() { |
909 public E previous() { |
728 if (nextIndex == 0) |
910 checkForComodification(); |
|
911 if (!hasPrevious()) |
729 throw new NoSuchElementException(); |
912 throw new NoSuchElementException(); |
730 |
913 |
731 lastReturned = next = next.previous; |
914 lastReturned = next = (next == null) ? last : next.prev; |
732 nextIndex--; |
915 nextIndex--; |
733 checkForComodification(); |
916 return lastReturned.item; |
734 return lastReturned.element; |
|
735 } |
917 } |
736 |
918 |
737 public int nextIndex() { |
919 public int nextIndex() { |
738 return nextIndex; |
920 return nextIndex; |
739 } |
921 } |
740 |
922 |
741 public int previousIndex() { |
923 public int previousIndex() { |
742 return nextIndex-1; |
924 return nextIndex - 1; |
743 } |
925 } |
744 |
926 |
745 public void remove() { |
927 public void remove() { |
746 checkForComodification(); |
928 checkForComodification(); |
747 Entry<E> lastNext = lastReturned.next; |
929 if (lastReturned == null) |
748 try { |
|
749 LinkedList.this.remove(lastReturned); |
|
750 } catch (NoSuchElementException e) { |
|
751 throw new IllegalStateException(); |
930 throw new IllegalStateException(); |
752 } |
931 |
753 if (next==lastReturned) |
932 Node<E> lastNext = lastReturned.next; |
|
933 unlink(lastReturned); |
|
934 if (next == lastReturned) |
754 next = lastNext; |
935 next = lastNext; |
755 else |
936 else |
756 nextIndex--; |
937 nextIndex--; |
757 lastReturned = header; |
938 lastReturned = null; |
758 expectedModCount++; |
939 expectedModCount++; |
759 } |
940 } |
760 |
941 |
761 public void set(E e) { |
942 public void set(E e) { |
762 if (lastReturned == header) |
943 if (lastReturned == null) |
763 throw new IllegalStateException(); |
944 throw new IllegalStateException(); |
764 checkForComodification(); |
945 checkForComodification(); |
765 lastReturned.element = e; |
946 lastReturned.item = e; |
766 } |
947 } |
767 |
948 |
768 public void add(E e) { |
949 public void add(E e) { |
769 checkForComodification(); |
950 checkForComodification(); |
770 lastReturned = header; |
951 lastReturned = null; |
771 addBefore(e, next); |
952 if (next == null) |
|
953 linkLast(e); |
|
954 else |
|
955 linkBefore(e, next); |
772 nextIndex++; |
956 nextIndex++; |
773 expectedModCount++; |
957 expectedModCount++; |
774 } |
958 } |
775 |
959 |
776 final void checkForComodification() { |
960 final void checkForComodification() { |
777 if (modCount != expectedModCount) |
961 if (modCount != expectedModCount) |
778 throw new ConcurrentModificationException(); |
962 throw new ConcurrentModificationException(); |
779 } |
963 } |
780 } |
964 } |
781 |
965 |
782 private static class Entry<E> { |
966 private static class Node<E> { |
783 E element; |
967 E item; |
784 Entry<E> next; |
968 Node<E> next; |
785 Entry<E> previous; |
969 Node<E> prev; |
786 |
970 |
787 Entry(E element, Entry<E> next, Entry<E> previous) { |
971 Node(Node<E> prev, E element, Node<E> next) { |
788 this.element = element; |
972 this.item = element; |
789 this.next = next; |
973 this.next = next; |
790 this.previous = previous; |
974 this.prev = prev; |
791 } |
975 } |
792 } |
|
793 |
|
794 private Entry<E> addBefore(E e, Entry<E> entry) { |
|
795 Entry<E> newEntry = new Entry<E>(e, entry, entry.previous); |
|
796 newEntry.previous.next = newEntry; |
|
797 newEntry.next.previous = newEntry; |
|
798 size++; |
|
799 modCount++; |
|
800 return newEntry; |
|
801 } |
|
802 |
|
803 private E remove(Entry<E> e) { |
|
804 if (e == header) |
|
805 throw new NoSuchElementException(); |
|
806 |
|
807 E result = e.element; |
|
808 e.previous.next = e.next; |
|
809 e.next.previous = e.previous; |
|
810 e.next = e.previous = null; |
|
811 e.element = null; |
|
812 size--; |
|
813 modCount++; |
|
814 return result; |
|
815 } |
976 } |
816 |
977 |
817 /** |
978 /** |
818 * @since 1.6 |
979 * @since 1.6 |
819 */ |
980 */ |
820 public Iterator<E> descendingIterator() { |
981 public Iterator<E> descendingIterator() { |
821 return new DescendingIterator(); |
982 return new DescendingIterator(); |
822 } |
983 } |
823 |
984 |
824 /** Adapter to provide descending iterators via ListItr.previous */ |
985 /** |
825 private class DescendingIterator implements Iterator { |
986 * Adapter to provide descending iterators via ListItr.previous |
826 final ListItr itr = new ListItr(size()); |
987 */ |
|
988 private class DescendingIterator implements Iterator<E> { |
|
989 private final ListItr itr = new ListItr(size()); |
827 public boolean hasNext() { |
990 public boolean hasNext() { |
828 return itr.hasPrevious(); |
991 return itr.hasPrevious(); |
829 } |
992 } |
830 public E next() { |
993 public E next() { |
831 return itr.previous(); |
994 return itr.previous(); |
892 * array is allocated with the runtime type of the specified array and |
1058 * array is allocated with the runtime type of the specified array and |
893 * the size of this list. |
1059 * the size of this list. |
894 * |
1060 * |
895 * <p>If the list fits in the specified array with room to spare (i.e., |
1061 * <p>If the list fits in the specified array with room to spare (i.e., |
896 * the array has more elements than the list), the element in the array |
1062 * the array has more elements than the list), the element in the array |
897 * immediately following the end of the list is set to <tt>null</tt>. |
1063 * immediately following the end of the list is set to {@code null}. |
898 * (This is useful in determining the length of the list <i>only</i> if |
1064 * (This is useful in determining the length of the list <i>only</i> if |
899 * the caller knows that the list does not contain any null elements.) |
1065 * the caller knows that the list does not contain any null elements.) |
900 * |
1066 * |
901 * <p>Like the {@link #toArray()} method, this method acts as bridge between |
1067 * <p>Like the {@link #toArray()} method, this method acts as bridge between |
902 * array-based and collection-based APIs. Further, this method allows |
1068 * array-based and collection-based APIs. Further, this method allows |
903 * precise control over the runtime type of the output array, and may, |
1069 * precise control over the runtime type of the output array, and may, |
904 * under certain circumstances, be used to save allocation costs. |
1070 * under certain circumstances, be used to save allocation costs. |
905 * |
1071 * |
906 * <p>Suppose <tt>x</tt> is a list known to contain only strings. |
1072 * <p>Suppose {@code x} is a list known to contain only strings. |
907 * The following code can be used to dump the list into a newly |
1073 * The following code can be used to dump the list into a newly |
908 * allocated array of <tt>String</tt>: |
1074 * allocated array of {@code String}: |
909 * |
1075 * |
910 * <pre> |
1076 * <pre> |
911 * String[] y = x.toArray(new String[0]);</pre> |
1077 * String[] y = x.toArray(new String[0]);</pre> |
912 * |
1078 * |
913 * Note that <tt>toArray(new Object[0])</tt> is identical in function to |
1079 * Note that {@code toArray(new Object[0])} is identical in function to |
914 * <tt>toArray()</tt>. |
1080 * {@code toArray()}. |
915 * |
1081 * |
916 * @param a the array into which the elements of the list are to |
1082 * @param a the array into which the elements of the list are to |
917 * be stored, if it is big enough; otherwise, a new array of the |
1083 * be stored, if it is big enough; otherwise, a new array of the |
918 * same runtime type is allocated for this purpose. |
1084 * same runtime type is allocated for this purpose. |
919 * @return an array containing the elements of the list |
1085 * @return an array containing the elements of the list |
920 * @throws ArrayStoreException if the runtime type of the specified array |
1086 * @throws ArrayStoreException if the runtime type of the specified array |
921 * is not a supertype of the runtime type of every element in |
1087 * is not a supertype of the runtime type of every element in |
922 * this list |
1088 * this list |
923 * @throws NullPointerException if the specified array is null |
1089 * @throws NullPointerException if the specified array is null |
924 */ |
1090 */ |
|
1091 @SuppressWarnings("unchecked") |
925 public <T> T[] toArray(T[] a) { |
1092 public <T> T[] toArray(T[] a) { |
926 if (a.length < size) |
1093 if (a.length < size) |
927 a = (T[])java.lang.reflect.Array.newInstance( |
1094 a = (T[])java.lang.reflect.Array.newInstance( |
928 a.getClass().getComponentType(), size); |
1095 a.getClass().getComponentType(), size); |
929 int i = 0; |
1096 int i = 0; |
930 Object[] result = a; |
1097 Object[] result = a; |
931 for (Entry<E> e = header.next; e != header; e = e.next) |
1098 for (Node<E> x = first; x != null; x = x.next) |
932 result[i++] = e.element; |
1099 result[i++] = x.item; |
933 |
1100 |
934 if (a.length > size) |
1101 if (a.length > size) |
935 a[size] = null; |
1102 a[size] = null; |
936 |
1103 |
937 return a; |
1104 return a; |
938 } |
1105 } |
939 |
1106 |
940 private static final long serialVersionUID = 876323262645176354L; |
1107 private static final long serialVersionUID = 876323262645176354L; |
941 |
1108 |
942 /** |
1109 /** |
943 * Save the state of this <tt>LinkedList</tt> instance to a stream (that |
1110 * Saves the state of this {@code LinkedList} instance to a stream |
944 * is, serialize it). |
1111 * (that is, serializes it). |
945 * |
1112 * |
946 * @serialData The size of the list (the number of elements it |
1113 * @serialData The size of the list (the number of elements it |
947 * contains) is emitted (int), followed by all of its |
1114 * contains) is emitted (int), followed by all of its |
948 * elements (each an Object) in the proper order. |
1115 * elements (each an Object) in the proper order. |
949 */ |
1116 */ |