集合之ArrayList


package java.util;

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

     //用数组保存数据     transient关键字修饰的属性不会被序列化
    private transient Object[] elementData;

    //ArrayList中实际数据数量
    private int size;

    //指定初始容量的构造函数
    public ArrayList(int initialCapacity) {
   super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
   this.elementData = new Object[initialCapacity];
    }

    //无参构造函数,默认初始容量为10
    public ArrayList() {
   this(10);
    }

    //创建包含Collection的ArrayList    
    public ArrayList(Collection<? extends E> c) {
   elementData = c.toArray();
   size = elementData.length;
   // c.toArray might (incorrectly) not return Object[] (see 6260652)
   if (elementData.getClass() != Object[].class)
       elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

   //将数组容量设为实际数据数量
    public void trimToSize() {
   modCount++;
   int oldCapacity = elementData.length;
   if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
   }
    }


     //扩容,默认扩增至原来的1.5倍+1
    public void ensureCapacity(int minCapacity) {
   modCount++;
   int oldCapacity = elementData.length;
   if (minCapacity > oldCapacity) {
       Object oldData[] = elementData;
       int newCapacity = (oldCapacity * 3)/2 + 1;
           if (newCapacity < minCapacity)
      newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
   }
    }

    public int size() {
   return size;
    }

    public boolean isEmpty() {
   return size == 0;
    }

    public boolean contains(Object o) {
   return indexOf(o) >= 0;
    }


    //返回查找对象在ArrayList中首次出现的下标,从0开始,如果没有则返回-1
    public int indexOf(Object o) {
   if (o == null) {
       for (int i = 0; i < size; i++)
      if (elementData[i]==null)
          return i;
   } else {
       for (int i = 0; i < size; i++)
      if (o.equals(elementData[i]))
          return i;
   }
   return -1;
    }

    //返回查找对象在ArrayList中最后出现的下标,从0开始,如果没有则返回-1
    public int lastIndexOf(Object o) {
   if (o == null) {
       for (int i = size-1; i >= 0; i--)
      if (elementData[i]==null)
          return i;
   } else {
       for (int i = size-1; i >= 0; i--)
      if (o.equals(elementData[i]))
          return i;
   }
   return -1;
    }

    //返回当前ArrayList实例的浅拷贝
    public Object clone() {
   try {
       ArrayList<E> v = (ArrayList<E>) super.clone();
       v.elementData = Arrays.copyOf(elementData, size);
       v.modCount = 0;
       return v;
   } catch (CloneNotSupportedException e) {
       // this shouldn't happen, since we are Cloneable
       throw new InternalError();
   }
    }

   //返回ArrayList中的数组
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
   System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

   //返回指定索引的值
    public E get(int index) {
   RangeCheck(index);

   return (E) elementData[index];
    }

    //替换指定索引的值,返回旧值
    public E set(int index, E element) {
   RangeCheck(index);

   E oldValue = (E) elementData[index];
   elementData[index] = element;
   return oldValue;
    }

    public boolean add(E e) {
   ensureCapacity(size + 1);  // Increments modCount!!
   elementData[size++] = e;
   return true;
    }

   //将element添加到ArrayList指定位置
    public void add(int index, E element) {
   if (index > size || index < 0)
       throw new IndexOutOfBoundsException(
      "Index: "+index+", Size: "+size);

   ensureCapacity(size+1);  // Increments modCount!!
   System.arraycopy(elementData, index, elementData, index + 1,
          size - index);
   elementData[index] = element;
   size++;
    }

   //删掉指定索引的值
    public E remove(int index) {
   RangeCheck(index);

   modCount++;
   E oldValue = (E) elementData[index];

   int numMoved = size - index - 1;
   if (numMoved > 0)
       System.arraycopy(elementData, index+1, elementData, index,
              numMoved);
   elementData[--size] = null; // Let gc do its work

   return oldValue;
    }

   //移除ArrayList中首次出现的元素
    public boolean remove(Object o) {
   if (o == null) {
            for (int index = 0; index < size; index++)
      if (elementData[index] == null) {
          fastRemove(index);
          return true;
      }
   } else {
       for (int index = 0; index < size; index++)
      if (o.equals(elementData[index])) {
          fastRemove(index);
          return true;
      }
        }
   return false;
    }

    //快速删除
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }


    public void clear() {
   modCount++;

   // Let gc do its work
   for (int i = 0; i < size; i++)
       elementData[i] = null;

   size = 0;
    }

   //末尾加入Collection所有值
    public boolean addAll(Collection<? extends E> c) {
   Object[] a = c.toArray();
        int numNew = a.length;
   ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
   return numNew != 0;
    }

  //从指定索引位置开始,把Collection所有值加到ArrayList中
    public boolean addAll(int index, Collection<? extends E> c) {
   if (index > size || index < 0)
       throw new IndexOutOfBoundsException(
      "Index: " + index + ", Size: " + size);

   Object[] a = c.toArray();
   int numNew = a.length;
   ensureCapacity(size + numNew);  // Increments modCount

   int numMoved = size - index;
   if (numMoved > 0)
       System.arraycopy(elementData, index, elementData, index + numNew,
              numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
   size += numNew;
   return numNew != 0;
    }

  //删除从fromIndex到toIndex的所有元素,包含fromIndex,不包含TO
    protected void removeRange(int fromIndex, int toIndex) {
   modCount++;
   int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

   // Let gc do its work
   int newSize = size - (toIndex-fromIndex);
   while (size != newSize)
       elementData[--size] = null;
    }

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void RangeCheck(int index) {
   if (index >= size)
       throw new IndexOutOfBoundsException(
      "Index: "+index+", Size: "+size);
    }

    //将ArrayList中所有元素写到输出流中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
   // Write out element count, and any hidden stuff
   int expectedModCount = modCount;
   s.defaultWriteObject();

        // Write out array length
        s.writeInt(elementData.length);

   // Write out all elements in the proper order.
   for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);

   if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

    }

   //从输入流中读取元素并保存到数组中
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
   // Read in size, and any hidden stuff
   s.defaultReadObject();

        // Read in array length and allocate array
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];

   // Read in all elements in the proper order.
   for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }
}

迭代器(父类Abstract中)

 public Iterator<E> iterator() {
return new Itr();
   }

   //listIterator可实现逆序遍历列表中所有元素
   public ListIterator<E> listIterator() {
return listIterator(0);
   }


   public ListIterator<E> listIterator(final int index) {
if (index<0 || index>size())
  throw new IndexOutOfBoundsException("Index: "+index);

return new ListItr(index);
   }

   private class Itr implements Iterator<E> {
 
 //下一个要遍历的元素索引位置(游标)
int cursor = 0;

/**
 * Index of element returned by most recent call to next or
 * previous.  Reset to -1 if this element is deleted by a call
 * to remove.
 */
int lastRet = -1;

/**
 * The modCount value that the iterator believes that the backing
 * List should have.  If this expectation is violated, the iterator
 * has detected concurrent modification.
 */
int expectedModCount = modCount;

public boolean hasNext() {
           return cursor != size();
}
//获取迭代的下一个元素
public E next() {
           checkForComodification();
    try {
   E next = get(cursor);
   lastRet = cursor++;
   return next;
    } catch (IndexOutOfBoundsException e) {
   checkForComodification();
   throw new NoSuchElementException();
    }
}
//从列表中移除迭代器返回的最后一个元素,不过每次调用next方法后只能调用一次此方法
public void remove() {
    if (lastRet == -1)
   throw new IllegalStateException();
           checkForComodification();

    try {
   AbstractList.this.remove(lastRet);
   if (lastRet < cursor)
       cursor--;
   lastRet = -1;
   expectedModCount = modCount;
    } catch (IndexOutOfBoundsException e) {
   throw new ConcurrentModificationException();
    }
}

final void checkForComodification() {
    if (modCount != expectedModCount)
   throw new ConcurrentModificationException();
}
   }

   private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
    cursor = index;
}
public E previous() {
           checkForComodification();
           try {
               int i = cursor - 1;
               E previous = get(i);
               lastRet = cursor = i;
               return previous;
           } catch (IndexOutOfBoundsException e) {
               checkForComodification();
               throw new NoSuchElementException();
           }
       }

public int nextIndex() {
    return cursor;
}

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

public void set(E e) {
    if (lastRet == -1)
   throw new IllegalStateException();
           checkForComodification();

    try {
   AbstractList.this.set(lastRet, e);
   expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
   throw new ConcurrentModificationException();
    }
}

public void add(E e) {
           checkForComodification();

    try {
   AbstractList.this.add(cursor++, e);
   lastRet = -1;
   expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
   throw new ConcurrentModificationException();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值