ArrayList.java 17.1 KB
Newer Older
1 2
/* ArrayList.java -- JDK1.2's answer to Vector; this is an array-backed
   implementation of the List interface
Dalibor Topic committed
3
   Copyright (C) 1998, 1999, 2000, 2001, 2004 Free Software Foundation, Inc.
4 5 6 7 8 9 10

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.
11

12 13 14 15 16 17 18 19 20 21
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., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
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. */
38 39 40 41 42 43 44


package java.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
Dalibor Topic committed
45 46
import java.io.Serializable;
import java.lang.reflect.Array;
47 48

/**
49 50 51 52 53 54
 * An array-backed implementation of the List interface.  This implements
 * all optional list operations, and permits null elements, so that it is
 * better than Vector, which it replaces. Random access is roughly constant
 * time, and iteration is roughly linear time, so it is nice and fast, with
 * less overhead than a LinkedList.
 * <p>
55
 *
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
 * Each list has a capacity, and as the array reaches that capacity it
 * is automatically transferred to a larger array. You also have access to
 * ensureCapacity and trimToSize to control the backing array's size, avoiding
 * reallocation or wasted memory.
 * <p>
 *
 * ArrayList is not synchronized, so if you need multi-threaded access,
 * consider using:<br>
 * <code>List l = Collections.synchronizedList(new ArrayList(...));</code>
 * <p>
 *
 * The iterators are <i>fail-fast</i>, meaning that any structural
 * modification, except for <code>remove()</code> called on the iterator
 * itself, cause the iterator to throw a
 * {@link ConcurrentModificationException} rather than exhibit
 * non-deterministic behavior.
 *
 * @author Jon A. Zeppieri
 * @author Bryce McKinlay
 * @author Eric Blake <ebb9@email.byu.edu>
 * @see Collection
 * @see List
 * @see LinkedList
 * @see Vector
 * @see Collections#synchronizedList(List)
 * @see AbstractList
 * @status updated to 1.4
83
 */
84
public class ArrayList extends AbstractList
85
  implements List, RandomAccess, Cloneable, Serializable
86
{
87 88 89 90 91 92 93 94
  /**
   * Compatible with JDK 1.2
   */
  private static final long serialVersionUID = 8683452581122892189L;

  /**
   * The default capacity for new ArrayLists.
   */
95 96
  private static final int DEFAULT_CAPACITY = 16;

97 98 99 100 101
  /**
   * The number of elements in this list.
   * @serial the list size
   */
  private int size;
102

103 104 105 106
  /**
   * Where the data is stored.
   */
  private transient Object[] data;
107

108 109
  /**
   * Construct a new ArrayList with the supplied initial capacity.
110
   *
111 112
   * @param capacity initial capacity of this ArrayList
   * @throws IllegalArgumentException if capacity is negative
113
   */
114
  public ArrayList(int capacity)
115
  {
116 117 118
    // Must explicitly check, to get correct exception.
    if (capacity < 0)
      throw new IllegalArgumentException();
119
    data = new Object[capacity];
120 121 122
  }

  /**
123
   * Construct a new ArrayList with the default capcity (16).
124 125 126 127 128 129
   */
  public ArrayList()
  {
    this(DEFAULT_CAPACITY);
  }

130
  /**
131
   * Construct a new ArrayList, and initialize it with the elements
132 133
   * in the supplied Collection. The initial capacity is 110% of the
   * Collection's size.
134
   *
135
   * @param c the collection whose elements will initialize this list
136
   * @throws NullPointerException if c is null
137
   */
138
  public ArrayList(Collection c)
139
  {
140
    this((int) (c.size() * 1.1f));
141
    addAll(c);
142 143 144
  }

  /**
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
   * Trims the capacity of this List to be equal to its size;
   * a memory saver.
   */
  public void trimToSize()
  {
    // Not a structural change from the perspective of iterators on this list,
    // so don't update modCount.
    if (size != data.length)
      {
        Object[] newData = new Object[size];
        System.arraycopy(data, 0, newData, 0, size);
        data = newData;
      }
  }

  /**
161
   * Guarantees that this list will have at least enough capacity to
162
   * hold minCapacity elements. This implementation will grow the list to
163
   * max(current * 2, minCapacity) if (minCapacity &gt; current). The JCL says
164 165 166
   * explictly that "this method increases its capacity to minCap", while
   * the JDK 1.3 online docs specify that the list will grow to at least the
   * size specified.
167
   *
168
   * @param minCapacity the minimum guaranteed capacity
169
   */
170
  public void ensureCapacity(int minCapacity)
171
  {
172 173 174 175
    int current = data.length;

    if (minCapacity > current)
      {
176 177 178
        Object[] newData = new Object[Math.max(current * 2, minCapacity)];
        System.arraycopy(data, 0, newData, 0, size);
        data = newData;
179
      }
180 181 182
  }

  /**
183
   * Returns the number of elements in this list.
184
   *
185
   * @return the list size
186
   */
187
  public int size()
188
  {
189
    return size;
190 191 192
  }

  /**
193
   * Checks if the list is empty.
194
   *
195
   * @return true if there are no elements
196
   */
197
  public boolean isEmpty()
198
  {
199
    return size == 0;
200 201 202
  }

  /**
203 204 205 206
   * Returns true iff element is in this ArrayList.
   *
   * @param e the element whose inclusion in the List is being tested
   * @return true if the list contains e
207
   */
208
  public boolean contains(Object e)
209
  {
210
    return indexOf(e) != -1;
211 212 213
  }

  /**
214 215
   * Returns the lowest index at which element appears in this List, or
   * -1 if it does not appear.
216
   *
217 218
   * @param e the element whose inclusion in the List is being tested
   * @return the index where e was found
219
   */
220
  public int indexOf(Object e)
221
  {
222 223 224 225
    for (int i = 0; i < size; i++)
      if (equals(e, data[i]))
        return i;
    return -1;
226 227 228
  }

  /**
229 230
   * Returns the highest index at which element appears in this List, or
   * -1 if it does not appear.
231
   *
232 233
   * @param e the element whose inclusion in the List is being tested
   * @return the index where e was found
234
   */
235
  public int lastIndexOf(Object e)
236
  {
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    for (int i = size - 1; i >= 0; i--)
      if (equals(e, data[i]))
        return i;
    return -1;
  }

  /**
   * Creates a shallow copy of this ArrayList (elements are not cloned).
   *
   * @return the cloned object
   */
  public Object clone()
  {
    ArrayList clone = null;
    try
      {
        clone = (ArrayList) super.clone();
        clone.data = (Object[]) data.clone();
      }
    catch (CloneNotSupportedException e)
257
      {
258
        // Impossible to get here.
259
      }
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    return clone;
  }

  /**
   * Returns an Object array containing all of the elements in this ArrayList.
   * The array is independent of this list.
   *
   * @return an array representation of this list
   */
  public Object[] toArray()
  {
    Object[] array = new Object[size];
    System.arraycopy(data, 0, array, 0, size);
    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.
   *
   * @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 Object[] toArray(Object[] a)
  {
    if (a.length < size)
      a = (Object[]) Array.newInstance(a.getClass().getComponentType(),
                                       size);
    else if (a.length > size)
      a[size] = null;
    System.arraycopy(data, 0, a, 0, size);
    return a;
  }

  /**
   * Retrieves the element at the user-supplied index.
   *
   * @param index the index of the element we are fetching
   * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
   */
  public Object get(int index)
  {
    checkBoundExclusive(index);
    return data[index];
  }

  /**
   * Sets the element at the specified index.
   *
   * @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 Object set(int index, Object e)
  {
    checkBoundExclusive(index);
    Object result = data[index];
    data[index] = e;
    return result;
  }

  /**
   * Appends the supplied element to the end of this list.
   *
   * @param e the element to be appended to this list
   * @return true, the add will always succeed
   */
  public boolean add(Object e)
  {
    modCount++;
    if (size == data.length)
      ensureCapacity(size + 1);
    data[size++] = e;
    return true;
342 343 344 345 346 347
  }

  /**
   * Adds the supplied element at the specified index, shifting all
   * elements currently at that index or higher one to the right.
   *
348 349 350
   * @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()
351
   */
352
  public void add(int index, Object e)
353
  {
354
    checkBoundInclusive(index);
355
    modCount++;
356 357
    if (size == data.length)
      ensureCapacity(size + 1);
358
    if (index != size)
359
      System.arraycopy(data, index, data, index + 1, size - index);
360 361
    data[index] = e;
    size++;
362 363
  }

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
  /**
   * Removes the element at the user-supplied index.
   *
   * @param index the index of the element to be removed
   * @return the removed Object
   * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
   */
  public Object remove(int index)
  {
    checkBoundExclusive(index);
    Object r = data[index];
    modCount++;
    if (index != --size)
      System.arraycopy(data, index + 1, data, index, size - index);
    // Aid for garbage collection by releasing this pointer.
    data[size] = null;
    return r;
  }

  /**
   * Removes all elements from this List
   */
  public void clear()
  {
    if (size > 0)
      {
        modCount++;
        // Allow for garbage collection.
        Arrays.fill(data, 0, size, null);
        size = 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.
401
   *
402 403 404
   * @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
405
   */
406
  public boolean addAll(Collection c)
407
  {
Bryce McKinlay committed
408
    return addAll(size, c);
409 410
  }

411
  /**
412 413 414
   * Add all elements in the supplied collection, inserting them beginning
   * at the specified index.
   *
415 416 417 418
   * @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
419
   */
420
  public boolean addAll(int index, Collection c)
421
  {
422
    checkBoundInclusive(index);
423 424 425
    Iterator itr = c.iterator();
    int csize = c.size();

426
    modCount++;
427 428
    if (csize + size > data.length)
      ensureCapacity(size + csize);
429
    int end = index + csize;
430 431
    if (size > 0 && index != size)
      System.arraycopy(data, index, data, end, size - index);
432
    size += csize;
433 434 435
    for ( ; index < end; index++)
      data[index] = itr.next();
    return csize > 0;
436 437 438
  }

  /**
439
   * Removes all elements in the half-open interval [fromIndex, toIndex).
440
   * Does nothing when toIndex is equal to fromIndex.
441 442 443
   *
   * @param fromIndex the first index which will be removed
   * @param toIndex one greater than the last index which will be removed
444
   * @throws IndexOutOfBoundsException if fromIndex &gt; toIndex
445
   */
446
  protected void removeRange(int fromIndex, int toIndex)
447
  {
448 449
    int change = toIndex - fromIndex;
    if (change > 0)
450
      {
451 452
        modCount++;
        System.arraycopy(data, toIndex, data, fromIndex, size - toIndex);
453
        size -= change;
454
      }
455 456
    else if (change < 0)
      throw new IndexOutOfBoundsException();
457 458
  }

459 460
  /**
   * Checks that the index is in the range of possible elements (inclusive).
461
   *
462 463
   * @param index the index to check
   * @throws IndexOutOfBoundsException if index &gt; size
464
   */
465
  private void checkBoundInclusive(int index)
466
  {
467 468 469 470 471 472
    // Implementation note: we do not check for negative ranges here, since
    // use of a negative index will cause an ArrayIndexOutOfBoundsException,
    // a subclass of the required exception, with no effort on our part.
    if (index > size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
                                          + size);
473 474 475
  }

  /**
476
   * Checks that the index is in the range of existing elements (exclusive).
477
   *
478 479
   * @param index the index to check
   * @throws IndexOutOfBoundsException if index &gt;= size
480
   */
481
  private void checkBoundExclusive(int index)
482
  {
483 484 485 486 487 488
    // Implementation note: we do not check for negative ranges here, since
    // use of a negative index will cause an ArrayIndexOutOfBoundsException,
    // a subclass of the required exception, with no effort on our part.
    if (index >= size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
                                          + size);
489 490 491
  }

  /**
492 493 494
   * Remove from this list all elements contained in the given collection.
   * This is not public, due to Sun's API, but this performs in linear
   * time while the default behavior of AbstractList would be quadratic.
495
   *
496 497 498
   * @param c the collection to filter out
   * @return true if this list changed
   * @throws NullPointerException if c is null
499
   */
500
  boolean removeAllInternal(Collection c)
501 502
  {
    int i;
503 504 505 506 507 508
    int j;
    for (i = 0; i < size; i++)
      if (c.contains(data[i]))
        break;
    if (i == size)
      return false;
509

510
    modCount++;
511 512 513 514 515
    for (j = i++; i < size; i++)
      if (! c.contains(data[i]))
        data[j++] = data[i];
    size -= i - j;
    return true;
516 517 518
  }

  /**
519 520 521
   * Retain in this vector only the elements contained in the given collection.
   * This is not public, due to Sun's API, but this performs in linear
   * time while the default behavior of AbstractList would be quadratic.
522
   *
523 524 525 526
   * @param c the collection to filter by
   * @return true if this vector changed
   * @throws NullPointerException if c is null
   * @since 1.2
527
   */
528
  boolean retainAllInternal(Collection c)
529
  {
530 531 532 533 534 535 536
    int i;
    int j;
    for (i = 0; i < size; i++)
      if (! c.contains(data[i]))
        break;
    if (i == size)
      return false;
537

538 539 540 541 542 543
    modCount++;
    for (j = i++; i < size; i++)
      if (c.contains(data[i]))
        data[j++] = data[i];
    size -= i - j;
    return true;
544 545 546
  }

  /**
547
   * Serializes this object to the given stream.
548
   *
549 550 551 552
   * @param out 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.
553
   */
554
  private void writeObject(ObjectOutputStream s) throws IOException
555
  {
556 557 558 559 560
    // The 'size' field.
    s.defaultWriteObject();
    // We serialize unused list entries to preserve capacity.
    int len = data.length;
    s.writeInt(len);
Mark Wielaard committed
561 562 563
    // it would be more efficient to just write "size" items,
    // this need readObject read "size" items too.
    for (int i = 0; i < size; i++)
564
      s.writeObject(data[i]);
565 566 567
  }

  /**
568 569 570 571 572 573 574
   * Deserializes this object from the given stream.
   *
   * @param in 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.
575
   */
576
  private void readObject(ObjectInputStream s)
577 578
    throws IOException, ClassNotFoundException
  {
579
    // the `size' field.
580 581
    s.defaultReadObject();
    int capacity = s.readInt();
582
    data = new Object[capacity];
Mark Wielaard committed
583
    for (int i = 0; i < size; i++)
584
      data[i] = s.readObject();
585 586
  }
}