CopyOnWriteArrayList.java 44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* CopyOnWriteArrayList.java
   Copyright (C) 2006 Free Software Foundation

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package java.util.concurrent;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
44

45
import java.lang.reflect.Array;
46

47
import java.util.AbstractList;
48
import java.util.Arrays;
49
import java.util.Collection;
50
import java.util.ConcurrentModificationException;
51 52
import java.util.Iterator;
import java.util.List;
53 54
import java.util.ListIterator;
import java.util.NoSuchElementException;
55 56
import java.util.RandomAccess;

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
/**
 * A thread-safe implementation of an ArrayList. A CopyOnWriteArrayList is
 * as special ArrayList which performs copies of the underlying storage
 * each time a write (<code>remove</code>, <code>add</code> etc..) operation
 * is performed.<br />
 * <br />
 * The update operation in this class run usually in <code>O(n)</code> or worse,
 * but traversal operations are fast and efficient, especially when running in
 * a multi-thread environment without the need to design complex synchronize
 * mechanisms.<br />
 * <br />
 * <code>Iterator</code>s in this class work on a snapshot of the backing store
 * at the moment the iterator itself was created, hence the iterator will not
 * reflect changes in the underlying storage. Thus, update operation on the
 * <code>Iterator</code>s are not supported, but as interferences from other
 * threads are impossible, no <code>ConcurrentModificationException</code>
 * will be ever thrown from within the <code>Iterator</code>.
 * <br /><br />
 * This class is especially useful when used with event handling, like the
 * following code demonstrates:<br />
 * <code><pre>
78
 *
79 80
 * CopyOnWriteArrayList<EventListener> listeners =
 *   new CopyOnWriteArrayList<EventListener>();
81
 *
82
 * [...]
83
 *
84 85 86 87 88 89 90 91
 * for (final EventListener listener : listeners)
 *   {
 *     Runnable dispatcher = new Runnable() {
 *       public void run()
 *       {
 *         listener.preferenceChange(event);
 *       }
 *     };
92
 *
93 94 95 96
 *     Executor executor = Executors.newSingleThreadExecutor();
 *     executor.execute(dispatcher);
 *   }
 * </pre></code>
97
 *
98 99
 * @since 1.5
 */
100
public class CopyOnWriteArrayList<E>
101
  implements List<E>, RandomAccess, Cloneable, Serializable
102 103
{
  /**
104
   *
105 106
   */
  private static final long serialVersionUID = 8673264195747942595L;
107

108
  /**
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
   * Where the data is stored.
   */
  private transient E[] data;

  /**
   * Construct a new ArrayList with the default capacity (16).
   */
  public CopyOnWriteArrayList()
  {
    data = (E[]) new Object[0];
  }

  /**
   * Construct a new ArrayList, and initialize it with the elements in the
   * supplied Collection. The initial capacity is 110% of the Collection's size.
124
   *
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
   * @param c
   *          the collection whose elements will initialize this list
   * @throws NullPointerException
   *           if c is null
   */
  public CopyOnWriteArrayList(Collection< ? extends E> c)
  {
    // FIXME ... correct?  use c.toArray()
    data = (E[]) new Object[c.size()];
    int index = 0;
    for (E value : c)
      data[index++] = value;
  }

  /**
   * Construct a new ArrayList, and initialize it with the elements in the
   * supplied array.
142
   *
143 144 145 146 147 148 149 150 151 152 153 154
   * @param array
   *          the array used to initialize this list
   * @throws NullPointerException
   *           if array is null
   */
  public CopyOnWriteArrayList(E[] array)
  {
    data = (E[]) array.clone();
  }

  /**
   * Returns the number of elements in this list.
155
   *
156 157 158 159 160 161 162 163 164
   * @return the list size
   */
  public int size()
  {
    return data.length;
  }

  /**
   * Checks if the list is empty.
165
   *
166 167 168 169 170 171 172 173
   * @return true if there are no elements
   */
  public boolean isEmpty()
  {
    return data.length == 0;
  }

  /**
174
   * Returns true if element is in this ArrayList.
175
   *
176 177 178 179 180 181 182 183 184 185
   * @param e
   *          the element whose inclusion in the List is being tested
   * @return true if the list contains e
   */
  public boolean contains(Object e)
  {
    return indexOf(e) != -1;
  }

  /**
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
   * Tests whether this collection contains all the elements in a given
   * collection. This implementation iterates over the given collection,
   * testing whether each element is contained in this collection. If any one
   * is not, false is returned. Otherwise true is returned.
   *
   * @param c the collection to test against
   * @return true if this collection contains all the elements in the given
   *         collection
   * @throws NullPointerException if the given collection is null
   * @see #contains(Object)
   */
  public boolean containsAll(Collection<?> c)
  {
    Iterator<?> itr = c.iterator();
    int pos = c.size();
    while (--pos >= 0)
      if (!contains(itr.next()))
        return false;
    return true;
  }

  /**
208 209
   * Returns the lowest index at which element appears in this List, or -1 if it
   * does not appear.
210
   *
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
   * @param e
   *          the element whose inclusion in the List is being tested
   * @return the index where e was found
   */
  public int indexOf(Object e)
  {
    E[] data = this.data;
    for (int i = 0; i < data.length; i++)
      if (equals(e, data[i]))
        return i;
    return -1;
  }

  /**
   * Return the lowest index greater equal <code>index</code> at which
   * <code>e</code> appears in this List, or -1 if it does not
   * appear.
   *
   * @param e the element whose inclusion in the list is being tested
   * @param index the index at which the search begins
   * @return the index where <code>e</code> was found
   */
  public int indexOf(E e, int index)
  {
    E[] data = this.data;

    for (int i = index; i < data.length; i++)
      if (equals(e, data[i]))
239
        return i;
240 241 242 243 244 245
    return -1;
  }

  /**
   * Returns the highest index at which element appears in this List, or -1 if
   * it does not appear.
246
   *
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
   * @param e
   *          the element whose inclusion in the List is being tested
   * @return the index where e was found
   */
  public int lastIndexOf(Object e)
  {
    E[] data = this.data;
    for (int i = data.length - 1; i >= 0; i--)
      if (equals(e, data[i]))
        return i;
    return -1;
  }

  /**
   * Returns the highest index lesser equal <code>index</code> at
   * which <code>e</code> appears in this List, or -1 if it does not
   * appear.
   *
   * @param e the element whose inclusion in the list is being tested
   * @param index the index at which the search begins
   * @return the index where <code>e</code> was found
   */
  public int lastIndexOf(E e, int index)
  {
    E[] data = this.data;

    for (int i = index; i >= 0; i--)
      if (equals(e, data[i]))
275
        return i;
276 277 278 279 280
    return -1;
  }

  /**
   * Creates a shallow copy of this ArrayList (elements are not cloned).
281
   *
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
   * @return the cloned object
   */
  public Object clone()
  {
    CopyOnWriteArrayList<E> clone = null;
    try
      {
        clone = (CopyOnWriteArrayList<E>) super.clone();
      }
    catch (CloneNotSupportedException e)
      {
        // Impossible to get here.
      }
    return clone;
  }

  /**
   * Returns an Object array containing all of the elements in this ArrayList.
   * The array is independent of this list.
301
   *
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
   * @return an array representation of this list
   */
  public Object[] toArray()
  {
    E[] data = this.data;
    E[] array = (E[]) new Object[data.length];
    System.arraycopy(data, 0, array, 0, data.length);
    return array;
  }

  /**
   * Returns an Array whose component type is the runtime component type of the
   * passed-in Array. The returned Array is populated with all of the elements
   * in this ArrayList. If the passed-in Array is not large enough to store all
   * of the elements in this List, a new Array will be created and returned; if
   * the passed-in Array is <i>larger</i> than the size of this List, then
   * size() index will be set to null.
319
   *
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
   * @param a
   *          the passed-in Array
   * @return an array representation of this list
   * @throws ArrayStoreException
   *           if the runtime type of a does not allow an element in this list
   * @throws NullPointerException
   *           if a is null
   */
  public <T> T[] toArray(T[] a)
  {
    E[] data = this.data;
    if (a.length < data.length)
      a = (T[]) Array.newInstance(a.getClass().getComponentType(), data.length);
    else if (a.length > data.length)
      a[data.length] = null;
    System.arraycopy(data, 0, a, 0, data.length);
    return a;
  }

  /**
   * Retrieves the element at the user-supplied index.
341
   *
342 343 344 345 346 347 348 349 350 351 352 353 354
   * @param index
   *          the index of the element we are fetching
   * @throws IndexOutOfBoundsException
   *           if index &lt; 0 || index &gt;= size()
   */
  public E get(int index)
  {
    return data[index];
  }

  /**
   * Sets the element at the specified index. The new element, e, can be an
   * object of any type or null.
355
   *
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
   * @param index
   *          the index at which the element is being set
   * @param e
   *          the element to be set
   * @return the element previously at the specified index
   * @throws IndexOutOfBoundsException
   *           if index &lt; 0 || index &gt;= 0
   */
  public synchronized E set(int index, E e)
  {
    E result = data[index];
    E[] newData = (E[]) data.clone();
    newData[index] = e;
    data = newData;
    return result;
  }

  /**
   * Appends the supplied element to the end of this list. The element, e, can
   * be an object of any type or null.
376
   *
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
   * @param e
   *          the element to be appended to this list
   * @return true, the add will always succeed
   */
  public synchronized boolean add(E e)
  {
    E[] data = this.data;
    E[] newData = (E[]) new Object[data.length + 1];
    System.arraycopy(data, 0, newData, 0, data.length);
    newData[data.length] = e;
    this.data = newData;
    return true;
  }

  /**
   * Adds the supplied element at the specified index, shifting all elements
   * currently at that index or higher one to the right. The element, e, can be
   * an object of any type or null.
395
   *
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
   * @param index
   *          the index at which the element is being added
   * @param e
   *          the item being added
   * @throws IndexOutOfBoundsException
   *           if index &lt; 0 || index &gt; size()
   */
  public synchronized void add(int index, E e)
  {
    E[] data = this.data;
    E[] newData = (E[]) new Object[data.length + 1];
    System.arraycopy(data, 0, newData, 0, index);
    newData[index] = e;
    System.arraycopy(data, index, newData, index + 1, data.length - index);
    this.data = newData;
  }

  /**
   * Removes the element at the user-supplied index.
415
   *
416 417 418 419 420 421 422 423
   * @param index
   *          the index of the element to be removed
   * @return the removed Object
   * @throws IndexOutOfBoundsException
   *           if index &lt; 0 || index &gt;= size()
   */
  public synchronized E remove(int index)
  {
424 425
    if (index < 0 || index >= this.size())
      throw new IndexOutOfBoundsException("index = " +  index);
426

427 428
    E[] snapshot = this.data;
    E[] newData = (E[]) new Object[snapshot.length - 1];
429

430
    E result = snapshot[index];
431

432
    if (index > 0)
433
      System.arraycopy(snapshot, 0, newData, 0, index);
434

435 436
    System.arraycopy(snapshot, index + 1, newData, index,
                     snapshot.length - index - 1);
437

438
    this.data = newData;
439

440
    return result;
441 442 443
  }

  /**
444 445 446
   * Remove the first occurrence, if any, of the given object from this list,
   * returning <code>true</code> if the object was removed, <code>false</code>
   * otherwise.
447
   *
448 449 450 451 452 453 454
   * @param element the object to be removed.
   * @return true if element was removed, false otherwise. false means also that
   * the underlying storage was unchanged after this operation concluded.
   */
  public synchronized boolean remove(Object element)
  {
    E[] snapshot = this.data;
455 456 457 458 459 460
    int len = snapshot.length;

    if (len == 0)
      return false;

    E[] newData = (E[]) new Object[len - 1];
461

462 463 464 465 466 467 468 469 470 471
    // search the element to remove while filling the backup array
    // this way we can run this method in O(n)
    int elementIndex = -1;
    for (int i = 0; i < snapshot.length; i++)
      {
        if (equals(element, snapshot[i]))
          {
            elementIndex = i;
            break;
          }
472

473 474 475
        if (i < newData.length)
          newData[i] = snapshot[i];
      }
476

477 478
    if (elementIndex < 0)
      return false;
479

480 481 482
    System.arraycopy(snapshot, elementIndex + 1, newData, elementIndex,
                     snapshot.length - elementIndex - 1);
    this.data = newData;
483

484 485
    return true;
  }
486

487 488 489 490
  /**
   * Removes all the elements contained in the given collection.
   * This method removes the elements that are contained in both
   * this list and in the given collection.
491
   *
492 493 494
   * @param c the collection containing the elements to be removed from this
   * list.
   * @return true if at least one element was removed, indicating that
495
   * the list internal storage changed as a result, false otherwise.
496 497 498 499 500
   */
  public synchronized boolean removeAll(Collection<?> c)
  {
    if (c.size() == 0)
      return false;
501

502
    E [] snapshot = this.data;
503
    E [] storage = (E[]) new Object[this.data.length];
504
    boolean changed = false;
505

506 507 508 509 510 511 512 513 514 515 516
    int length = 0;
    for (E element : snapshot)
      {
        // copy all the elements, including null values
        // if the collection can hold it
        // FIXME: slow operation
        if (c.contains(element))
          changed = true;
        else
          storage[length++] = element;
      }
517

518 519
    if (!changed)
      return false;
520

521 522
    E[] newData = (E[]) new Object[length];
    System.arraycopy(storage, 0, newData, 0, length);
523

524
    this.data = newData;
525

526 527
    return true;
  }
528

529 530 531 532 533 534 535
  /**
   * Removes all the elements that are not in the passed collection.
   * If the collection is void, this method has the same effect of
   * <code>clear()</code>.
   * Please, note that this method is extremely slow (unless the argument has
   * <code>size == 0</code>) and has bad performance is both space and time
   * usage.
536
   *
537 538 539 540 541 542 543 544 545 546 547 548 549 550
   * @param c the collection containing the elements to be retained by this
   * list.
   * @return true the list internal storage changed as a result of this
   * operation, false otherwise.
   */
  public synchronized boolean retainAll(Collection<?> c)
  {
    // if the given collection does not contain elements
    // we remove all the elements from our storage
    if (c.size() == 0)
      {
        this.clear();
        return true;
      }
551

552
    E [] snapshot = this.data;
553 554
    E [] storage = (E[]) new Object[this.data.length];

555 556 557 558 559 560
    int length = 0;
    for (E element : snapshot)
      {
        if (c.contains(element))
          storage[length++] = element;
      }
561

562 563 564 565 566
    // means we retained all the elements previously in our storage
    // we are running already slow here, but at least we avoid copying
    // another array and changing the internal storage
    if (length == snapshot.length)
      return false;
567

568 569
    E[] newData = (E[]) new Object[length];
    System.arraycopy(storage, 0, newData, 0, length);
570

571
    this.data = newData;
572

573 574
    return true;
  }
575

576
  /**
577 578 579 580 581 582 583 584 585 586 587 588
   * Removes all elements from this List
   */
  public synchronized void clear()
  {
    data = (E[]) new Object[0];
  }

  /**
   * Add each element in the supplied Collection to this List. It is undefined
   * what happens if you modify the list while this is taking place; for
   * example, if the collection contains this list. c can contain objects of any
   * type, as well as null values.
589
   *
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
   * @param c
   *          a Collection containing elements to be added to this List
   * @return true if the list was modified, in other words c is not empty
   * @throws NullPointerException
   *           if c is null
   */
  public synchronized boolean addAll(Collection< ? extends E> c)
  {
    return addAll(data.length, c);
  }

  /**
   * Add all elements in the supplied collection, inserting them beginning at
   * the specified index. c can contain objects of any type, as well as null
   * values.
605
   *
606 607 608 609 610 611 612 613 614 615 616
   * @param index
   *          the index at which the elements will be inserted
   * @param c
   *          the Collection containing the elements to be inserted
   * @throws IndexOutOfBoundsException
   *           if index &lt; 0 || index &gt; 0
   * @throws NullPointerException
   *           if c is null
   */
  public synchronized boolean addAll(int index, Collection< ? extends E> c)
  {
617 618
    if (index < 0 || index > this.size())
      throw new IndexOutOfBoundsException("index = " +  index);
619

620 621 622
    int csize = c.size();
    if (csize == 0)
      return false;
623

624 625
    E[] data = this.data;
    Iterator<? extends E> itr = c.iterator();
626

627
    E[] newData = (E[]) new Object[data.length + csize];
628

629 630 631 632
    // avoid this call at all if we were asked to put the elements at the
    // beginning of our storage
    if (index != 0)
      System.arraycopy(data, 0, newData, 0, index);
633

634
    int itemsLeft = index;
635

636
    for (E value : c)
637
      newData[index++] = value;
638

639 640
    // now copy the remaining elements
    System.arraycopy(data, itemsLeft, newData, 0, data.length - itemsLeft);
641

642
    this.data = newData;
643

644 645
    return true;
  }
646

647 648
  /**
   * Adds an element if the list does not contains it already.
649
   *
650 651 652
   * @param val the element to add to the list.
   * @return true if the element was added, false otherwise.
   */
653 654 655 656 657 658 659 660
  public synchronized boolean addIfAbsent(E val)
  {
    if (contains(val))
      return false;
    add(val);
    return true;
  }

661 662 663
  /**
   * Adds all the element from the given collection that are not already
   * in this list.
664
   *
665 666 667 668
   * @param c the Collection containing the elements to be inserted
   * @return true the list internal storage changed as a result of this
   * operation, false otherwise.
   */
669 670
  public synchronized int addAllAbsent(Collection<? extends E> c)
  {
671 672 673
    int size = c.size();
    if (size == 0)
      return 0;
674

675 676
    E [] snapshot = this.data;
    E [] storage = (E[]) new Object[size];
677

678
    size = 0;
679 680
    for (E val : c)
      {
681 682
        if (!this.contains(val))
          storage[size++] = val;
683
      }
684

685 686
    if (size == 0)
      return 0;
687

688 689
    // append storage to data
    E [] newData = (E[]) new Object[snapshot.length + size];
690

691 692
    System.arraycopy(snapshot, 0, newData, 0, snapshot.length);
    System.arraycopy(storage, 0, newData, snapshot.length, size);
693

694
    this.data = newData;
695

696 697 698 699 700 701 702 703 704 705 706 707
    return size;
  }

  public String toString()
  {
    return Arrays.toString(this.data);
  }

  public boolean equals(Object o)
  {
    if (o == null)
      return false;
708

709 710
    if (this == o)
      return true;
711

712 713 714 715 716
    // let's see if 'o' is a list, if so, we need to compare the elements
    // as returned by the iterator
    if (o instanceof List)
      {
        List<?> source = (List<?>) o;
717

718 719
        if (source.size() != this.size())
          return false;
720

721 722 723 724 725 726 727 728 729
        Iterator<?> sourceIterator = source.iterator();
        for (E element : this)
          {
            if (!element.equals(sourceIterator.next()))
              return false;
          }

        return true;
      }
730

731 732
    return false;
  }
733

734 735 736 737 738 739 740 741 742 743
  public int hashCode()
  {
    // see http://java.sun.com/6/docs/api/java/util/List.html#hashcode()
    int hashcode = 1;
    for (E element : this)
      {
        hashcode = 31 * hashcode + (element == null ? 0 : element.hashCode());
      }
    return hashcode;
  }
744

745 746 747 748 749 750
  /**
   * Return an Iterator containing the elements of this list.
   * The Iterator uses a snapshot of the state of the internal storage
   * at the moment this method is called and does <strong>not</strong> support
   * update operations, so no synchronization is needed to traverse the
   * iterator.
751
   *
752 753 754 755 756 757 758 759
   * @return an Iterator containing the elements of this list in sequence.
   */
  public Iterator<E> iterator()
  {
    return new Iterator<E>()
    {
      E [] iteratorData = CopyOnWriteArrayList.this.data;
      int currentElement = 0;
760

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
      public boolean hasNext()
      {
        return (currentElement < iteratorData.length);
      }

      public E next()
      {
        return iteratorData[currentElement++];
      }

      public void remove()
      {
        throw new UnsupportedOperationException("updating of elements in " +
                                                "iterators is not supported " +
                                                "by this class");
      }
    };
778
  }
779

780 781 782 783 784 785
  /**
   * Return a ListIterator containing the elements of this list.
   * The Iterator uses a snapshot of the state of the internal storage
   * at the moment this method is called and does <strong>not</strong> support
   * update operations, so no synchronization is needed to traverse the
   * iterator.
786
   *
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
   * @return a ListIterator containing the elements of this list in sequence.
   */
  public ListIterator<E> listIterator()
  {
    return listIterator(0);
  }

  /**
   * Return a ListIterator over the elements of this list starting at
   * the specified index.  An initial call to {@code next()} will thus
   * return the element at {@code index}, while an initial call to
   * {@code previous()} will return the element at {@code index-1}.  The
   * Iterator uses a snapshot of the state of the internal storage
   * at the moment this method is called and does <strong>not</strong> support
   * update operations, so no synchronization is needed to traverse the
   * iterator.
803
   *
804 805 806 807 808 809 810 811 812 813 814 815 816
   * @param index the index at which to start iterating.
   * @return a ListIterator containing the elements of this list in sequence.
   */
  public ListIterator<E> listIterator(final int index)
  {
    if (index < 0 || index > size())
      throw new IndexOutOfBoundsException("Index: " + index + ", Size:"
                                          + size());

    return new ListIterator<E>()
    {
      E [] iteratorData = CopyOnWriteArrayList.this.data;
      int currentElement = index;
817

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
      public void add(E o)
      {
        throw new UnsupportedOperationException("updating of elements in " +
                                                "iterators is not supported " +
                                                "by this class");
      }

      public boolean hasNext()
      {
        return (currentElement < iteratorData.length);
      }

      public boolean hasPrevious()
      {
        return (currentElement > 0);
      }

      public E next()
      {
        if (hasNext() == false)
          throw new java.util.NoSuchElementException();
839

840 841 842 843 844 845 846 847 848 849 850 851
        return iteratorData[currentElement++];
      }

      public int nextIndex()
      {
        return (currentElement + 1);
      }

      public E previous()
      {
        if (hasPrevious() == false)
          throw new java.util.NoSuchElementException();
852

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
        return iteratorData[--currentElement];
      }

      public int previousIndex()
      {
        return (currentElement - 1);
      }

      public void remove()
      {
        throw new UnsupportedOperationException("updating of elements in " +
                                                "iterators is not supported " +
                                                "by this class");
      }

      public void set(E o)
      {
        throw new UnsupportedOperationException("updating of elements in " +
                                                "iterators is not supported " +
                                                "by this class");
      }
874

875 876
    };
  }
877

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  /**
   * Obtain a List view of a subsection of this list, from fromIndex
   * (inclusive) to toIndex (exclusive). If the two indices are equal, the
   * sublist is empty. The returned list should be modifiable if and only
   * if this list is modifiable. Changes to the returned list should be
   * reflected in this list. If this list is structurally modified in
   * any way other than through the returned list, the result of any subsequent
   * operations on the returned list is undefined.
   * <p>
   *
   * This implementation returns a subclass of AbstractList. It stores, in
   * private fields, the offset and size of the sublist, and the expected
   * modCount of the backing list. If the backing list implements RandomAccess,
   * the sublist will also.
   * <p>
   *
   * The subclass's <code>set(int, Object)</code>, <code>get(int)</code>,
   * <code>add(int, Object)</code>, <code>remove(int)</code>,
   * <code>addAll(int, Collection)</code> and
   * <code>removeRange(int, int)</code> methods all delegate to the
   * corresponding methods on the backing abstract list, after
   * bounds-checking the index and adjusting for the offset. The
   * <code>addAll(Collection c)</code> method merely returns addAll(size, c).
   * The <code>listIterator(int)</code> method returns a "wrapper object"
   * over a list iterator on the backing list, which is created with the
   * corresponding method on the backing list. The <code>iterator()</code>
   * method merely returns listIterator(), and the <code>size()</code> method
   * merely returns the subclass's size field.
   * <p>
   *
   * All methods first check to see if the actual modCount of the backing
   * list is equal to its expected value, and throw a
910
   * ConcurrentModificationException if it is not.
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
   *
   * @param fromIndex the index that the returned list should start from
   *        (inclusive)
   * @param toIndex the index that the returned list should go to (exclusive)
   * @return a List backed by a subsection of this list
   * @throws IndexOutOfBoundsException if fromIndex &lt; 0
   *         || toIndex &gt; size()
   * @throws IndexOutOfBoundsException if fromIndex &gt; toIndex
   * @see ConcurrentModificationException
   * @see RandomAccess
   */
  public synchronized List<E> subList(int fromIndex, int toIndex)
  {
    // This follows the specification of AbstractList, but is inconsistent
    // with the one in List. Don't you love Sun's inconsistencies?
    if (fromIndex > toIndex)
      throw new IndexOutOfBoundsException(fromIndex + " > " + toIndex);
    if (fromIndex < 0 || toIndex > size())
      throw new IndexOutOfBoundsException();

    if (this instanceof RandomAccess)
      return new RandomAccessSubList<E>(this, fromIndex, toIndex);
    return new SubList<E>(this, fromIndex, toIndex);
  }

  /**
   * This class follows the implementation requirements set forth in
   * {@link AbstractList#subList(int, int)}. It matches Sun's implementation
   * by using a non-public top-level class in the same package.
   *
   * @author Original author unknown
   * @author Eric Blake (ebb9@email.byu.edu)
   */
944
  private static class SubList<E>
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    extends AbstractList<E>
  {
    // Package visible, for use by iterator.
    /** The original list. */
    final CopyOnWriteArrayList<E> backingList;
    /** The index of the first element of the sublist. */
    final int offset;
    /** The size of the sublist. */
    int size;
    /** The backing data */
    E[] data;

    /**
     * Construct the sublist.
     *
     * @param backing the list this comes from
     * @param fromIndex the lower bound, inclusive
     * @param toIndex the upper bound, exclusive
     */
    SubList(CopyOnWriteArrayList<E> backing, int fromIndex, int toIndex)
    {
      backingList = backing;
      data = backing.data;
      offset = fromIndex;
      size = toIndex - fromIndex;
    }
971

972 973 974 975 976 977 978 979 980 981 982 983 984
    /**
     * This method checks the two modCount fields to ensure that there has
     * not been a concurrent modification, returning if all is okay.
     *
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     */
    // This can be inlined. Package visible, for use by iterator.
    void checkMod()
    {
      if (data != backingList.data)
        throw new ConcurrentModificationException();
    }
985

986 987 988 989 990 991 992 993 994 995 996 997 998 999
    /**
     * This method checks that a value is between 0 and size (inclusive). If
     * it is not, an exception is thrown.
     *
     * @param index the value to check
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
     */
    // This will get inlined, since it is private.
    private void checkBoundsInclusive(int index)
    {
      if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: " + index +
                                            ", Size:" + size);
    }
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    /**
     * This method checks that a value is between 0 (inclusive) and size
     * (exclusive). If it is not, an exception is thrown.
     *
     * @param index the value to check
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
     */
    // This will get inlined, since it is private.
    private void checkBoundsExclusive(int index)
    {
      if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException("Index: " + index +
                                            ", Size:" + size);
    }
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    /**
     * Specified by AbstractList.subList to return the private field size.
     *
     * @return the sublist size
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     */
    public int size()
    {
      synchronized (backingList)
        {
          checkMod();
          return size;
        }
    }
1031

1032 1033 1034 1035 1036 1037 1038 1039
    public void clear()
    {
      synchronized (backingList)
        {
          E[] snapshot = backingList.data;
          E[] newData = (E[]) new Object[snapshot.length - size];

          int toIndex = size + offset;
1040

1041 1042 1043
          System.arraycopy(snapshot, 0, newData, 0, offset);
          System.arraycopy(snapshot, toIndex, newData, offset,
                           snapshot.length - toIndex);
1044

1045 1046 1047 1048 1049
          backingList.data = newData;
          this.data = backingList.data;
          this.size = 0;
        }
    }
1050

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    /**
     * Specified by AbstractList.subList to delegate to the backing list.
     *
     * @param index the location to modify
     * @param o the new value
     * @return the old value
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws UnsupportedOperationException if the backing list does not
     *         support the set operation
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
     * @throws ClassCastException if o cannot be added to the backing list due
     *         to its type
     * @throws IllegalArgumentException if o cannot be added to the backing list
     *         for some other reason
     */
    public E set(int index, E o)
    {
      synchronized (backingList)
        {
          checkMod();
          checkBoundsExclusive(index);
1073

1074 1075
          E el =  backingList.set(index + offset, o);
          this.data = backingList.data;
1076

1077 1078 1079
          return el;
        }
    }
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    /**
     * Specified by AbstractList.subList to delegate to the backing list.
     *
     * @param index the location to get from
     * @return the object at that location
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
     */
    public E get(int index)
    {
      synchronized (backingList)
      {
        checkMod();
        checkBoundsExclusive(index);
1096

1097 1098 1099
        return backingList.get(index + offset);
      }
    }
1100

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    /**
     * Specified by AbstractList.subList to delegate to the backing list.
     *
     * @param index the index to insert at
     * @param o the object to add
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
     * @throws UnsupportedOperationException if the backing list does not
     *         support the add operation.
     * @throws ClassCastException if o cannot be added to the backing list due
     *         to its type.
     * @throws IllegalArgumentException if o cannot be added to the backing
     *         list for some other reason.
     */
    public void add(int index, E o)
    {
      synchronized (backingList)
      {
        checkMod();
        checkBoundsInclusive(index);
1122

1123
        backingList.add(index + offset, o);
1124

1125 1126 1127 1128
        this.data = backingList.data;
        size++;
      }
    }
1129

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    /**
     * Specified by AbstractList.subList to delegate to the backing list.
     *
     * @param index the index to remove
     * @return the removed object
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
     * @throws UnsupportedOperationException if the backing list does not
     *         support the remove operation
     */
    public E remove(int index)
    {
      synchronized (backingList)
      {
        checkMod();
        checkBoundsExclusive(index);
        E o = backingList.remove(index + offset);
1148

1149 1150
        this.data = backingList.data;
        size--;
1151

1152 1153 1154
        return o;
      }
    }
1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    /**
     * Specified by AbstractList.subList to delegate to the backing list.
     *
     * @param index the location to insert at
     * @param c the collection to insert
     * @return true if this list was modified, in other words, c is non-empty
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
     * @throws UnsupportedOperationException if this list does not support the
     *         addAll operation
     * @throws ClassCastException if some element of c cannot be added to this
     *         list due to its type
     * @throws IllegalArgumentException if some element of c cannot be added
     *         to this list for some other reason
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c)
    {
      synchronized (backingList)
      {
        checkMod();
        checkBoundsInclusive(index);
        int csize = c.size();
        boolean result = backingList.addAll(offset + index, c);
1181

1182 1183
        this.data = backingList.data;
        size += csize;
1184

1185 1186 1187
        return result;
      }
    }
1188

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
    /**
     * Specified by AbstractList.subList to return addAll(size, c).
     *
     * @param c the collection to insert
     * @return true if this list was modified, in other words, c is non-empty
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws UnsupportedOperationException if this list does not support the
     *         addAll operation
     * @throws ClassCastException if some element of c cannot be added to this
     *         list due to its type
     * @throws IllegalArgumentException if some element of c cannot be added
     *         to this list for some other reason
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c)
    {
      synchronized (backingList)
      {
        return addAll(size, c);
      }
    }
1211

1212 1213 1214 1215 1216 1217 1218 1219 1220
    /**
     * Specified by AbstractList.subList to return listIterator().
     *
     * @return an iterator over the sublist
     */
    public Iterator<E> iterator()
    {
      return listIterator();
    }
1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    /**
     * Specified by AbstractList.subList to return a wrapper around the
     * backing list's iterator.
     *
     * @param index the start location of the iterator
     * @return a list iterator over the sublist
     * @throws ConcurrentModificationException if the backing list has been
     *         modified externally to this sublist
     * @throws IndexOutOfBoundsException if the value is out of range
     */
    public ListIterator<E> listIterator(final int index)
    {
      checkMod();
      checkBoundsInclusive(index);

      return new ListIterator<E>()
      {
        private final ListIterator<E> i =
          backingList.listIterator(index + offset);
        private int position = index;

        /**
         * Tests to see if there are any more objects to
         * return.
         *
         * @return True if the end of the list has not yet been
         *         reached.
         */
        public boolean hasNext()
        {
          return position < size;
        }

        /**
         * Tests to see if there are objects prior to the
         * current position in the list.
         *
         * @return True if objects exist prior to the current
         *         position of the iterator.
         */
        public boolean hasPrevious()
        {
          return position > 0;
        }

        /**
         * Retrieves the next object from the list.
         *
         * @return The next object.
         * @throws NoSuchElementException if there are no
         *         more objects to retrieve.
         * @throws ConcurrentModificationException if the
         *         list has been modified elsewhere.
         */
        public E next()
        {
          if (position == size)
            throw new NoSuchElementException();
          position++;
          return i.next();
        }

        /**
         * Retrieves the previous object from the list.
         *
         * @return The next object.
         * @throws NoSuchElementException if there are no
         *         previous objects to retrieve.
         * @throws ConcurrentModificationException if the
         *         list has been modified elsewhere.
         */
        public E previous()
        {
          if (position == 0)
            throw new NoSuchElementException();
          position--;
          return i.previous();
        }

        /**
         * Returns the index of the next element in the
         * list, which will be retrieved by <code>next()</code>
         *
         * @return The index of the next element.
         */
        public int nextIndex()
        {
          return i.nextIndex() - offset;
        }

        /**
         * Returns the index of the previous element in the
         * list, which will be retrieved by <code>previous()</code>
         *
         * @return The index of the previous element.
         */
        public int previousIndex()
        {
          return i.previousIndex() - offset;
        }

        /**
         * Removes the last object retrieved by <code>next()</code>
         * from the list, if the list supports object removal.
         *
         * @throws IllegalStateException if the iterator is positioned
         *         before the start of the list or the last object has already
         *         been removed.
         * @throws UnsupportedOperationException if the list does
         *         not support removing elements.
         */
        public void remove()
        {
          throw new UnsupportedOperationException("Modification not supported " +
              "on CopyOnWriteArrayList iterators");
        }

        /**
         * Replaces the last object retrieved by <code>next()</code>
         * or <code>previous</code> with o, if the list supports object
         * replacement and an add or remove operation has not already
         * been performed.
         *
         * @throws IllegalStateException if the iterator is positioned
         *         before the start of the list or the last object has already
         *         been removed.
         * @throws UnsupportedOperationException if the list doesn't support
         *         the addition or removal of elements.
         * @throws ClassCastException if the type of o is not a valid type
         *         for this list.
         * @throws IllegalArgumentException if something else related to o
         *         prevents its addition.
         * @throws ConcurrentModificationException if the list
         *         has been modified elsewhere.
         */
        public void set(E o)
        {
          throw new UnsupportedOperationException("Modification not supported " +
              "on CopyOnWriteArrayList iterators");
        }

        /**
         * Adds the supplied object before the element that would be returned
         * by a call to <code>next()</code>, if the list supports addition.
1366
         *
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
         * @param o The object to add to the list.
         * @throws UnsupportedOperationException if the list doesn't support
         *         the addition of new elements.
         * @throws ClassCastException if the type of o is not a valid type
         *         for this list.
         * @throws IllegalArgumentException if something else related to o
         *         prevents its addition.
         * @throws ConcurrentModificationException if the list
         *         has been modified elsewhere.
         */
        public void add(E o)
        {
          throw new UnsupportedOperationException("Modification not supported " +
              "on CopyOnWriteArrayList iterators");
1381
        }
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
      };
    }
  } // class SubList

  /**
   * This class is a RandomAccess version of SubList, as required by
   * {@link AbstractList#subList(int, int)}.
   *
   * @author Eric Blake (ebb9@email.byu.edu)
   */
  private static final class RandomAccessSubList<E> extends SubList<E>
    implements RandomAccess
  {
    /**
     * Construct the sublist.
     *
     * @param backing the list this comes from
     * @param fromIndex the lower bound, inclusive
     * @param toIndex the upper bound, exclusive
     */
    RandomAccessSubList(CopyOnWriteArrayList<E> backing, int fromIndex, int toIndex)
    {
      super(backing, fromIndex, toIndex);
    }
  } // class RandomAccessSubList
1407 1408 1409

  /**
   * Serializes this object to the given stream.
1410
   *
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
   * @param s
   *          the stream to write to
   * @throws IOException
   *           if the underlying stream fails
   * @serialData the size field (int), the length of the backing array (int),
   *             followed by its elements (Objects) in proper order.
   */
  private void writeObject(ObjectOutputStream s) throws IOException
  {
    // The 'size' field.
    s.defaultWriteObject();
    // We serialize unused list entries to preserve capacity.
    int len = data.length;
    s.writeInt(len);
    // it would be more efficient to just write "size" items,
    // this need readObject read "size" items too.
    for (int i = 0; i < data.length; i++)
      s.writeObject(data[i]);
  }

  /**
   * Deserializes this object from the given stream.
1433
   *
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
   * @param s
   *          the stream to read from
   * @throws ClassNotFoundException
   *           if the underlying stream fails
   * @throws IOException
   *           if the underlying stream fails
   * @serialData the size field (int), the length of the backing array (int),
   *             followed by its elements (Objects) in proper order.
   */
  private void readObject(ObjectInputStream s) throws IOException,
      ClassNotFoundException
  {
    // the `size' field.
    s.defaultReadObject();
    int capacity = s.readInt();
    data = (E[]) new Object[capacity];
    for (int i = 0; i < capacity; i++)
      data[i] = (E) s.readObject();
  }

  static final boolean equals(Object o1, Object o2)
  {
    return o1 == null ? o2 == null : o1.equals(o2);
  }
1458

1459 1460 1461 1462 1463
  Object[] getArray()
  {
    return data;
  }
}