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

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

As a special exception, if you link this library with other files to
produce an executable, this library does not by itself cause the
resulting executable to be covered by the GNU General Public License.
This exception does not however invalidate any other reasons why the
executable file might be covered by the GNU General Public License. */


package java.util;

import java.lang.reflect.Array;
import java.io.Serializable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * An array-backed implementation of the List interface.  ArrayList
 * performs well on simple tasks:  random access into a list, appending
 * to or removing from the end of a list, checking the size, &c.
 *
 * @author        Jon A. Zeppieri
 * @see           java.util.AbstractList
 * @see           java.util.List
 */
46
public class ArrayList extends AbstractList
47 48 49 50 51 52
  implements List, Cloneable, Serializable
{
  /** the default capacity for new ArrayLists */
  private static final int DEFAULT_CAPACITY = 16;

  /** the number of elements in this list */
53
  int size;
54 55

  /** where the data is stored */
56
  transient Object[] data;
57 58 59 60

  /** 
   * Construct a new ArrayList with the supplied initial capacity. 
   *
61
   * @param capacity Initial capacity of this ArrayList
62
   */
63
  public ArrayList(int capacity)
64
  {
65
    data = new Object[capacity];
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  }


  /**
   * Construct a new ArrayList with the default capcity 
   */
  public ArrayList()
  {
    this(DEFAULT_CAPACITY);
  }

  /** 
   * Construct a new ArrayList, and initialize it with the elements
   * in the supplied Collection; Sun specs say that the initial 
   * capacity is 110% of the Collection's size.
   *
82
   * @param c the collection whose elements will initialize this list
83
   */
84
  public ArrayList(Collection c)
85
  {
86 87
    this((int) (c.size() * 1.1));
    addAll(c);
88 89 90 91
  }

  /**
   * Guarantees that this list will have at least enough capacity to
92
   * hold minCapacity elements. 
93
   *
94 95 96 97 98 99
   * @specnote This implementation will grow the list to 
   *   max(current * 2, minCapacity) if (minCapacity > current). The JCL says
   *   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.
   * @param minCapacity the minimum guaranteed capacity
100
   */
101
  public void ensureCapacity(int minCapacity)
102
  {
103 104 105 106 107 108 109 110 111
    Object[] newData;
    int current = data.length;

    if (minCapacity > current)
      {
	newData = new Object[Math.max((current * 2), minCapacity)];
	System.arraycopy(data, 0, newData, 0, size);
	data = newData;
      }
112 113 114 115 116
  }

  /**
   * Appends the supplied element to the end of this list.
   *
117
   * @param       e      the element to be appended to this list
118
   */
119
  public boolean add(Object e)
120 121
  {
    modCount++;
122 123
    if (size == data.length)
      ensureCapacity(size + 1);
124
    data[size++] = e;
125 126 127 128 129 130
    return true;
  }

  /**
   * Retrieves the element at the user-supplied index.
   *
131
   * @param    index        the index of the element we are fetching
132 133
   * @throws   IndexOutOfBoundsException  (iIndex < 0) || (iIndex >= size())
   */
134
  public Object get(int index)
135
  {
136 137 138 139
    if (index < 0 || index >= size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + 
                                          size);
    return data[index];
140 141 142 143 144 145 146
  }

  /**
   * Returns the number of elements in this list 
   */
  public int size()
  {
147
    return size;
148 149 150 151 152 153 154 155 156
  }

  /**
   * Removes the element at the user-supplied index
   *
   * @param     iIndex      the index of the element to be removed
   * @return    the removed Object
   * @throws    IndexOutOfBoundsException  (iIndex < 0) || (iIndex >= size())
   */
157
  public Object remove(int index)
158 159
  {
    modCount++;
160 161 162 163 164 165 166 167
    if (index < 0 || index > size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + 
                                          size);
    Object r = data[index];
    if (index != --size)
      System.arraycopy(data, (index + 1), data, index, (size - index));
    data[size] = null;
    return r;
168 169 170 171 172
  }

  /**
   * Removes all elements in the half-open interval [iFromIndex, iToIndex).
   *
173 174
   * @param     fromIndex   the first index which will be removed
   * @param     toIndex     one greater than the last index which will be 
175 176
   *                         removed
   */
177
  protected void removeRange(int fromIndex, int toIndex)
178
  {
179 180 181 182
    modCount++;
    if (fromIndex != toIndex)
      {
	System.arraycopy(data, toIndex, data, fromIndex, size - toIndex);
183
	size -= (toIndex - fromIndex);
184
      }
185 186 187 188 189 190
  }

  /**
   * Adds the supplied element at the specified index, shifting all
   * elements currently at that index or higher one to the right.
   *
191 192
   * @param     index      the index at which the element is being added
   * @param     e          the item being added
193
   */
194
  public void add(int index, Object e)
195 196
  {
    modCount++;
197 198 199
    if (index < 0 || index > size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + 
                                          size);
200 201
    if (size == data.length)
      ensureCapacity(size + 1);
202 203 204 205
    if (index != size)
      System.arraycopy(data, index, data, index + 1, size - index);    
    data[index] = e;
    size++;
206 207 208 209 210
  }

  /** 
   * Add each element in the supplied Collection to this List.
   *
211 212
   * @param        c          a Collection containing elements to be 
   *                          added to this List
213
   */
214
  public boolean addAll(Collection c)
215
  {
Bryce McKinlay committed
216
    return addAll(size, c);
217 218 219 220 221 222
  }

  /** 
   * Add all elements in the supplied collection, inserting them beginning
   * at the specified index.
   *
223 224 225
   * @param     index       the index at which the elements will be inserted
   * @param     c           the Collection containing the elements to be
   *                        inserted
226
   */
227
  public boolean addAll(int index, Collection c)
228
  {
229 230 231
    if (index < 0 || index > size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + 
                                          size);
232 233 234 235
    modCount++;
    Iterator itr = c.iterator();
    int csize = c.size();

236 237
    if (csize + size > data.length)
      ensureCapacity(size + csize);
238 239 240 241 242 243 244 245 246
    int end = index + csize;
    if (size > 0 && index != size)
      System.arraycopy(data, index, data, end, csize);
    size += csize;
    for (; index < end; index++)
      {
        data[index] = itr.next();
      }
    return (csize > 0);
247 248 249 250 251 252 253
  }

  /**
   * Creates a shallow copy of this ArrayList
   */
  public Object clone()
  {
254
    ArrayList clone = null;
255
    try
256 257 258 259 260 261 262
      {
	clone = (ArrayList) super.clone();
	clone.data = new Object[data.length];
	System.arraycopy(data, 0, clone.data, 0, size);
      }
    catch (CloneNotSupportedException e) {}
    return clone;
263 264 265 266 267
  }

  /** 
   * Returns true iff oElement is in this ArrayList.
   *
268 269
   * @param     e     the element whose inclusion in the List is being
   *                  tested
270
   */
271
  public boolean contains(Object e)
272
  {
273
    return (indexOf(e) != -1);
274 275 276 277 278 279
  }

  /**
   * Returns the lowest index at which oElement appears in this List, or 
   * -1 if it does not appear.
   *
280 281
   * @param    e       the element whose inclusion in the List is being
   *                   tested
282
   */
283
  public int indexOf(Object e)
284
  {
Bryce McKinlay committed
285
    for (int i = 0; i < size; i++)
286 287 288 289
      {
	if (e == null ? data[i] == null : e.equals(data[i]))
	  return i;
      }
290 291 292 293 294 295 296
    return -1;
  }

  /**
   * Returns the highest index at which oElement appears in this List, or 
   * -1 if it does not appear.
   *
297 298
   * @param    e       the element whose inclusion in the List is being
   *                   tested
299
   */
300
  public int lastIndexOf(Object e)
301 302 303
  {
    int i;

304 305 306 307 308
    for (i = size - 1; i >= 0; i--)
      {
	if (e == null ? data[i] == null : e.equals(data[i]))
	  return i;
      }
309 310 311 312 313 314 315 316
    return -1;
  }

  /**
   * Removes all elements from this List
   */
  public void clear()
  {
317
    modCount++;
Bryce McKinlay committed
318 319 320 321
    for (int i = 0; i < size; i++)
      {
	data[i] = null;
      }    
322
    size = 0;
323 324 325 326 327
  }

  /**
   * Sets the element at the specified index.
   *
328 329
   * @param     index   the index at which the element is being set
   * @param     e       the element to be set
330 331 332
   * @return    the element previously at the specified index, or null if
   *            none was there
   */
333
  public Object set(int index, Object e)
334
  {
335 336 337 338 339
    Object result;
    if (index < 0 || index >= size)
      throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + 
                                          size);
    result = data[index];
340
    // SEH: no structural change, so don't update modCount
341 342
    data[index] = e;
    return result;
343 344 345 346 347 348 349
  }

  /**
   * Returns an Object Array containing all of the elements in this ArrayList
   */
  public Object[] toArray()
  {
350 351 352
    Object[] array = new Object[size];
    System.arraycopy(data, 0, array, 0, size);
    return array;
353 354 355
  }

  /**
Bryce McKinlay committed
356 357
   * 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
358 359 360
   * 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
361
   * of this List, then size() index will be set to null.
362
   *
363
   * @param      array      the passed-in Array
364
   */
365
  public Object[] toArray(Object[] array)
366
  {
367 368 369 370 371 372 373
    if (array.length < size)
      array = (Object[]) Array.newInstance(array.getClass().getComponentType(), 
        				   size);
    else if (array.length > size)
      array[size] = null;
    System.arraycopy(data, 0, array, 0, size);
    return array;
374 375 376
  }

  /**
377 378
   * Trims the capacity of this List to be equal to its size; 
   * a memory saver.   
379 380 381
   */
  public void trimToSize()
  {
382 383 384 385 386
    // not a structural change from the perspective of iterators on this list, 
    // so don't update modCount
    Object[] newData = new Object[size];
    System.arraycopy(data, 0, newData, 0, size);
    data = newData;
387 388
  }

389
  private void writeObject(ObjectOutputStream out) throws IOException
390 391 392
  {
    int i;

393 394
    // The 'size' field.
    out.defaultWriteObject();
395

396 397 398 399
    // FIXME: Do we really want to serialize unused list entries??
    out.writeInt(data.length);
    for (i = 0; i < data.length; i++)
      out.writeObject(data[i]);
400 401
  }

402
  private void readObject(ObjectInputStream in)
403 404 405
    throws IOException, ClassNotFoundException
  {
    int i;
406
    int capacity;
407

408 409
    // the `size' field.
    in.defaultReadObject();
410

411 412
    capacity = in.readInt();
    data = new Object[capacity];
413

414 415
    for (i = 0; i < capacity; i++)
      data[i] = in.readObject();
416 417
  }
}