ArrayList源码分析

ArrayList源码解析
疑问:1.ArrayList继承自AbstractList,为什么父类和子类都实现了List接口

1. 定义
ArrayList继承AbstractList(这是一个抽象类,对一些基础的list操作进行封装),实现List,RandomAccess,Cloneable,Serializable几个接口,RandomAccess表明其支持快速随机访问,Cloneable表明其支持浅拷贝,Serializable 序列化及反序列化功能。

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

    //这个是干嘛的??
    private static final long serialVersionUID = 8683452581122892189L;

    //默认容量
    private static final int DEFAULT_CAPACITY = 10;

    private static final Object[] EMPTY_ELEMENTDATA = {};

    //存放元素的数组,transient修饰
    private transient Object[] elementData;

    // 存储元素个数,对应的容量用elementData.length来得到
    private int size;

注意到存储元素的elementData数组,用transient修饰。序列化时,elementData不会被序列化,序列化时元素具体数据不会被存储?看到后面,我们就会明白,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 size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

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

    /**
     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);

            Object[] a = elementData;
            //反序列读取元素顺序应该不会改变,序列化顺序和反序列化读取顺序是相反的?
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

然我们来测试一下,

public class ArrayDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("hello");
        list.add("Hello");
        try {  
            ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream(  
                    "d:/Seriatest.out"));  
            outStream.writeObject(list);  
            outStream.close();  
            System.out.println("out success"); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }

        try {  
            ObjectInputStream inStream = new ObjectInputStream(new FileInputStream(  
                    "d:/Seriatest.out"));  
            ArrayList inList = (ArrayList) inStream.readObject(); 
            inStream.close();
            System.out.println("in success");  
            System.out.println(inList.get(0));
            System.out.println(inList.get(1));
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
}

这样做的好处,序列化时,按照size,元素各个来序列化的,而不是容量,节省了开支。

下面是构造方法,定义了三个构造方法

/**
     * 构造一个指定长度的list
     */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

    /**
     * 容量为0,直接将final常量EMPTY_ELEMENTDATA赋予elementData
     */
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }

    /**
     * 构造一个由Collection转换后的list,list顺序与Collection.iterator一致
     * iterator.
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // 返回若不是Object[]将调用Arrays.copyOf
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

2.add

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


     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //直接用 System.arraycopy方法,而不是逐个后移,这样增加了效率
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
  /**
     * 添加后的顺序与Collection.iterator顺序一致
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(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;
    }

    /**
     * 都是应有System.arraycopy
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

3.get,set

  @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    public E set(int index, E element) {
        rangeCheck(index);

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

4.remove

/**
     * 移除以后,并没有减少数list容量,所以在remove多个成员后,可以利用前面定义
     *的trimToSize()方法来,减少容量,这个方法时public的哦
     */
    public E remove(int index) {
        rangeCheck(index);

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

        int numMoved = size - index - 1;
        if (numMoved > 0)
            //直接用 System.arraycopy方法,而不是逐个后移,这样增加了效率
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false);
    }

    private boolean batchRemove(Collection<?> c, boolean complement) {
        //final修饰
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            //这个循环666
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    //remove时,complement=false,
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                //修改modCount的值
                modCount += size - w;
                size = w;
                //根据元素个数判断是否remove过元素
                modified = true;
            }
        }
        return modified;
    }
    /**
     * 都是应用System.arraycopy
     * protected修饰
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

5.sublist
这段代码略长,就不贴了,这个方法放回的是一个this原来list的副本,对副本中做任何改变,都会对原来的list做出相同的变化,副本与原来list区别,就是reference不同吧

6.容量的变化
ArrayList向外部提供了两个改变容量的方法,trimToSize()默认改变为最小容量值,ensureCapacity(int minCapacity)可以传入具体需要设置的容量值

/**
     * 改变容量为数组元素个数,用来节约内存
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }

    /**
     * public
     *设置具体的容量值,但可以发现扩展容量不足1.5倍时,自动扩展为1.5倍
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != EMPTY_ELEMENTDATA)
            // any size if real element table
            ? 0
            // larger than default for empty table. It's already supposed to be
            // at default size.
            : DEFAULT_CAPACITY;
        //不符合要求时不予理睬
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
    /*
     *无参构造器生产list,容量扩充时最小值为默认容量10)
     */
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        //用于在迭代器中同步
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 容量扩充为原来的1.5倍
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //为什么看到别人的都是1.5+1,版本不同吧
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
        //制定容量大于1.5倍时,扩充至制定容量
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    /**
     * list容量过大,1.5*容量<MAX_ARRAY_SIZE时,下次扩充容量不再为1.5倍
     */
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

7.其他

public void clear() {
        //modeCount只改变一次,这个方法不是同步安全的哎
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;//不改变容量?数组长度大是,造成很大浪费
    }

注意点:容量扩充时,通常是1.5倍,但根据情况也可能出现意外,如制定容量大于1.5时,容量超过最大值时;ArrayList向外提供了两个改变容量的方法;subList方法返回的是一个副本;add,remove时,采用的是System.arraycopy来增加效率;序列化时,要利用ArrayList自定义的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值