jdk-ArrayList

来源:互联网 发布:淘宝贷款记录在哪里看 编辑:程序博客网 时间:2024/06/10 05:26

最近项目比较忙,上次分析线程池的时候中断掉了,不过幸运的是里面大部分内容已经分析完毕,其实自己在分析时也是磕磕绊绊的,或许是自己还没到那种程度吧,留着自己慢慢看吧,后期再来回复一下。

今天抽空先看些简单的源码吧,本着看多少是多少的原则,其实都比不看的要好。

//ArrayList 默认大小是10,也就是数组大小默认是10位    public ArrayList() {        this(10);    }

//常见的add方法    public boolean add(E e) {        //首先去确认下需不需要扩容        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }    private void ensureCapacityInternal(int minCapacity) {        modCount++;  //计数器一样的东西,每次执行到的话+1        // overflow-conscious code        if (minCapacity - elementData.length > 0)            grow(minCapacity);  //此处说明需要扩容了    }    //扩容    private void grow(int minCapacity) {        //第一次扩容发生在 minCapacity 是11时,也就是刚好添加了最后一个元素,下标是9,大小是10的时候,        // overflow-conscious code        int oldCapacity = elementData.length;        int newCapacity = oldCapacity + (oldCapacity >> 1);  //每次都是扩容旧的大小的一半,此处是5        if (newCapacity - minCapacity < 0)            newCapacity = minCapacity;    //此处在oldCapacity时Integer.MAX_VALUE出现,list所允许的最大值也就是Integer.MAX_VALUE了        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); //重新copy    }    private static int hugeCapacity(int minCapacity) {        //可以看见,最大值也就是Integer.MAX_VALUE了        if (minCapacity < 0) // overflow            throw new OutOfMemoryError();        return (minCapacity > MAX_ARRAY_SIZE) ?                Integer.MAX_VALUE :                MAX_ARRAY_SIZE;    }


get没什么好说的,本质上从数组取元素而已,首先会check一下下标有没有越界
public E get(int index) {        rangeCheck(index);        return elementData(index);    }

    //remove一个对象    public boolean remove(Object o) {        if (o == null) {            for (int index = 0; index < size; index++)                if (elementData[index] == null) {   //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    }


















原创粉丝点击