collection之arraylist源码初步

1、通过iterator遍历arraylist的时候要特别注意并发问题,通过modCount记录了arrayList的改变次数,通过此provide fail-fast iterators

* <p>The iterators returned by this class's <tt>iterator</tt> and
 * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
 * structurally modified at any time after the iterator is created, in any way
 * except through the iterator's own <tt>remove</tt> or <tt>add</tt> methods,
 * the iterator will throw a {@link ConcurrentModificationException}.  Thus, in
 * the face of concurrent modification, the iterator fails quickly and cleanly,
 * rather than risking arbitrary, non-deterministic behavior at an undetermined
 * time in the future.<p>
 2、arraylist属性

 /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient Object[] elementData;    //非序列化

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;   //标注list元素数量

3、构造函数

(1)、在构造函数中有一段:

  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);
    }

查看了Arrays.copyOf,public static <T> T[] copyOf(T[] original, int newLength),注释中有这么一段说明 The resulting array is of exactly the same class as the original array.

4、方法

(1)、contains方法,内部调用了indexOf方法,而indexOf方法是对整个数组循环遍历

(2)、arrayList的writeObject:

private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount; //保证在序列化前后没有对list进行修改
    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();
        }
    }

付:defaultWriteObject:将当前类的非静态和非瞬态字段写入此流

(3),readObject:

  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();
    }


转载于:https://my.oschina.net/mutianya/blog/189879

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值