死磕容器-Arraylist

Arraylist概述

Arraylist是实现了list接口的动态数组,所谓动态就是,该数组大小可变,具有可以改变数组大小的方法。
每个Arraylist都有一个容量,该容量用来指定存储元素数组的大小,默认初始容量为10.随着Arraylist中元素的添加,容量也会随着自动增长。每次添加进新元素,Arraylist都会检查是否需要扩容操作。扩容操作带来数据向新数组的拷贝,如果我们知道大概实际的容量,提前指定初始容量,就能降低拷贝的次数,减少系统的销毁。在大量增加元素前,应用程序可以使用ensureCapacity操作来增加Arraylist的容量,这样可以减少递增式再分配的数量。

Arraylist源码剖析

Arraylist实现list接口,底层采用数组实现,很多操作都是基于数组实现的。

底层使用数组

 transient Object[] elementData;

transient声明当对象存储时,这个值不需要维持(用于序列化).

构造函数
构造默认初始化容量(默认为10):public ArrayList()
构造指定容量的:public ArrayList(int initialCapacity)
构造包含指定collection元素的:public ArrayList(Collection<? extends E> c)

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

 public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
    
public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

Add

直接看add()中将指定元素插入特定位置的方法

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

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    
//跟踪arraycopy
//对源数组进行复制(位移)处理,从index+1位移size-index长度
//主要目的就是空出index槽,添加新元素
//arraycopy
//它的根本目的就是进行数组元素的复制。
//即从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
//将源数组src从srcPos位置开始复制到dest数组中,复制长度为length,
//据从dest的destPos位置开始粘贴。
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
          

对数组进行复制和位移是非常耗时的,所以如果需要频繁地在数组中间插入元素,最好还是使用LinkedList。

将collection全部元素添加到尾部
无非就是将collection转换为数组,再利用system.arraycopy

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

将collection元素放到指定的位置
如果能够理解上面那两个,这个方法就很好理解了

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

Remove

remove(int index):删除指定位置的元素

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

        modCount++;
        E oldValue = elementData(index);
		//向左移动的位移量
		//这里-1,我自己是这样理解的:删除一个元素了,所以可能不需要复制全部
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//向左位移,覆盖要被删除的元素
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
          	//将最后一个元素赋空,交给GC回收
        elementData[--size] = null; // clear to let GC do its work
        return oldValue;
    }

remove(Object o):移除此列表中首次出现的指定元素(如果存在)

public boolean remove(Object o) {
     	//Arraylisy允许出现null,所以需要对null进行判断
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                	//fastRemove用于删除指定元素,相比remove(int index)少了对数组越界的判断
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

removeRange(int fromIndex, int toIndex):
移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素

protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        // 将剩余容量的槽赋空,方便GC回收
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

removeAll():是继承自AbstractCollection的方法,ArrayList本身并没有提供实现

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

查找

Arraylist是基于数组实现的,数据具有索引,适于查找。

 public E get(int index) {
        RangeCheck(index);
        return (E) elementData[index];
    }

扩容

public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //增长1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值