Java 源码分析之ArrayList

本文基于jdk1.7源码分析

ArrayList 简介

ArrayList 底层是基于数组实现的,是一个动态数组,当存储空间不足时,会自动扩容,ArrayList 不是线程安全的,如果要在多线程环境下使用,可以使用Collections.synchronizedList(List list)获取一个线程安全的List对象,或使用java.util.concurrent.CopyOnWriteArrayList类生成一个线程安全的List.

ArrayList 结构

ArrayList 继承结构
RandomAccess, Cloneable, Serializable 这三个接口都是标记接口,没有定义方法和参数。
RandomAccess 接口,表示该类支持随机访问,即通过下标访问。
Cloneable 接口,表示该类能被克隆。
Serializable 接口,表示该类支持序列化。

ArrayList 源码之构造方法

  1. 不带参数的构造方法,该方法默认构建一个初始化容量为10的列表。
public ArrayList() {
    this(10);
}

2.该构造方法可指定列表的初始化容量,在知道数据量的情况下,可适当调整初始化容量,避免多次扩容,提高性能。

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

3.创建一个包含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);
}

ArrayList 之增删查

  1. ArrayList 之添加数据
// 添加元素
public boolean add(E e) {
    ensureCapacity(size + 1);  // 检查容量,如果容量不足,对数组进行扩容
    elementData[size++] = e;   // 将数据添加到数组中
    return true;
}
// 添加元素到指定位置
public void add(int index, E element) {
    if (index > size || index < 0)  // 判断指定的下标是否合理
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);

    ensureCapacity(size+1);  // 检查容量
    System.arraycopy(elementData, index, elementData, index + 1,
             size - index);// 数组复制,将index位置空出来,index的数据后移
    elementData[index] = element; // 将元素存入index位置
    size++;// List 大小自增
}

// 添加一个集合的数据到List中
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();// 获取数据数组
        int numNew = a.length; // 得到数组长度
    ensureCapacity(size + numNew);  // 检查添加这些数据,容量是否足够,不够进行扩容
        System.arraycopy(a, 0, elementData, size, numNew);// 复制集合中的数据到List
        size += numNew;// List大小增加数组长度
    return numNew != 0;
 }

//添加一个集合到指定下标
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);  // 检查添加这些数据,容量是否足够,不够进行扩容

    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                 numMoved);// 移动List中的数据,空出位置给添加进来的集合,

        System.arraycopy(a, 0, elementData, index, numNew); // 将集合中的数据复制到List
    size += numNew; // List大小增加数组长度
    return numNew != 0;
}

// 检查容量
public void ensureCapacity(int minCapacity) {
    modCount++;// 列表结构修改的次数
    int oldCapacity = elementData.length;// List 容量长度
    if (minCapacity > oldCapacity) { // 判断新增后的长度是否大于容量长度,如果大于说明List的容量不够了,需要扩容
        Object oldData[] = elementData; // 得到老的数据数组
        int newCapacity = (oldCapacity * 3)/2 + 1; //计算 新的容量=(原始容量x3)/2 + 1
            if (newCapacity < minCapacity) // 如果计算出来的容量,还是小了,则使用新增数据后的长度作为容量
        newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);// 复制List的数据到指定容量的数组中,返回新的数组
    }
}

2.ArrayList 之查询数据

// 获取指定下标的数据
public E get(int index) {
    rangeCheck(index);  // 判断指定下标是否合理

    return elementData(index);// 返回指定下标中的数据
}
// 检查下标是否合理
private void rangeCheck(int index) {
    if (index >= size) // 如果获取的下标超过了List集合的大小,就跑下标越界异常
    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// 查找元素下标
public int indexOf(Object o) {
    if (o == null) { // 如果元素为空
        for (int i = 0; i < size; i++)// 遍历List
            if (elementData[i]==null) 
                return i;// 返回下标
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1; //没有找到返回-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; // 没有找到该元素,返回-1
}

3.ArrayList 之删除数据

// 根据下标删除元素
public E remove(int index) {
    rangeCheck(index);  // 检查下标是否合理
    modCount++;// 操作数自增
    E oldValue = elementData(index);// 获取要删除的数据
    int numMoved = size - index - 1; //计算需要移动几个数据
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);// 移动数组中的数据,index后的数据往前移动
    elementData[--size] = null; //将末尾的数据置为null

    return oldValue;// 返回删除的数据
}

// 根据元素删除
public boolean remove(Object o) {
    if (o == null) { // 判断需要删除的数据是否为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;// 没找到该元素,返回false
}
// 根据下标快速删除,不返回删除的元素
private void fastRemove(int index) {
    modCount++;// 操作数自增
    int numMoved = size - index - 1;// 需要移动的数据个数
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);// 移动数组中的数据,index后的数据往前移动
    elementData[--size] = null; //将末尾的数据置为null
}

// 清空集合
public void clear() {
    modCount++;// 操作数自增

    // 遍历集合
    for (int i = 0; i < size; i++)
        elementData[i] = null;// 将所有数据置为null

    size = 0;// 将集合大小置为0
}

// 删除指定范围的数据,但该方法却是protected
protected void removeRange(int fromIndex, int toIndex) {
    modCount++;// 操作数自增
    int numMoved = size - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
                     numMoved);//移动数组中的数据,toIndex后的数据往前移动
    // Let gc do its work
    int newSize = size - (toIndex-fromIndex);// 计算删除数据后的size大小
    while (size != newSize)// 删除多少个元素,就从后往前置空多少元素
        elementData[--size] = null;
}

// 删除两个集合的差集
 public boolean removeAll(Collection<?> c) {
    return batchRemove(c, false);// false表示不包含
}

//删除两个集合的交集
public boolean retainAll(Collection<?> c) {
    return batchRemove(c, true);// true表示包含
}

// 移除数据
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                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) {
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

总结

ArrayList底层是使用数组存储数据,基于下标访问,所有查询快。
在已知数据数量的情况下,可以在创建ArrayList对象的时候指定初始化容量,避免多次扩容,提高效率。
ArrayList删除数据时会去复制数组,移动数据,所以效率较低.
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值