arraylist概述

  1. arraylist是可以动态扩容和动态删除冗余容量的索引序列,基于数组实现的集合。
  2. arraylist支持随机访问、克隆、序列化,元素有序且可以重复。
  3. arraylist初始默认长度10,超出扩容1.5倍,使用object[]存储各种数据类型。

arraylist数据结构

  数据结构是集合的精华所在,数据结构往往也限制了集合的作用和侧重点,了解各种数据结构是我们分析源码的必经之路。
  arraylist的数据结构如下:
arraylist源码分析--jdk1.8

arraylist源码分析

/*
 * 用数组实现的集合,支持随机访问,元素有序且可以重复
 * randomaccess(arraylist) 支持快速随机访问,使用for循环更加快速
 * linkedlist 使用 iterator迭代器更加 快速
 * randomaccess 这是一个标记接口,一般此标记接口用于 list 实现,以表明它们支持快速(通常是恒定时间)的随机访问。
 * 该接口的主要目的是允许通用算法改变其行为,以便在应用于随机或顺序访问列表时提供良好的性能
 * 包含类中的基础属性和3个构造方法
 */
public class arraylist<e> extends abstractlist<e>
        implements list<e>, randomaccess, cloneable, java.io.serializable
{
 /**
     * 默认长度  10
     */
    private static final int default_capacity = 10;
    /**
     * 默认空的数组
     */
    private static final object[] empty_elementdata = {};
    /**
     * arraylist中的元素  是object[]类型的数组
     */
    transient object[] elementdata; // non-private to simplify nested class access
    /**
     * 动态数组的实际大小 ,默认为0
     * @serial
     */
    private int size;
     /**
     * 最大数组容量2147483639
     */
    private static final int max_array_size = integer.max_value - 8;
         /**
     * 集合长度构造函数
     */
    public arraylist(int initialcapacity) {
        super();
        if (initialcapacity < 0)
            throw new illegalargumentexception("illegal capacity: "+
                                               initialcapacity);
        this.elementdata = new object[initialcapacity];
    }
         /**
     * 无参构造函数,设置元素数组为空 注意此时初始容量是0,而不是大家以为的 10
     */
    public arraylist() {
        super();
        this.elementdata = empty_elementdata;
    }
    /**
     * 集合参数构造函数
     */
    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) //是否成功转化为object类型数组
            elementdata = arrays.copyof(elementdata, size, object[].class); //不为object数组的话就进行复制
    }

arraylist继承和实现分析

arraylist源码分析--jdk1.8
   arraylist extends abstractlist
   abstractlist extends abstractcollection 
  java中所有类都继承object,所以arraylist的继承结构如上图。
   1. abstractlist是一个抽象类,实现了list<e>接口,list<e>定义了一些list通用方法,而abstractlist抽象类中可以有抽象方法,还可以有具体的实现方法,abstractlist实现接口中一些通用的方法,实现了基础的add/get/indexof/iterator/sublist/randomaccesssublist方法,arraylist再继承abstractlist,拿到通用基础的方法,然后自己在实现一些自己特有的方法,这样的好处是:让代码更简洁,继承结构最底层的类中通用的方法,减少重复代码。
   2.arraylist实现了list<e>、randomaccess、cloneable、serializable接口
     1)list<e>接口,arraylist既然继承自abstractlist抽象类,而abstractlist已 经实现了list接口,那么arraylist类为何还要再实现list接口呢?我们带着疑问往下看:

public class demo1 extends arraylist {
    public static void main(string[] args) {
                //返回[]
        system.out.println(arrays.tostring(demo1.class.getinterfaces()));
    }
public class demo2 implements serializable {
    public static void main(string[] args) {
                //返回[interface java.io.serializable]
        system.out.println(arrays.tostring(demo2.class.getinterfaces()));
    }
public class test{
    public static void main(string[] args) {
                serializable c1 = new demo1();//未显示实现接口
                serializable c2 = new demo2();//显示实现接口
                serializable proxy2 = createproxy(c2);
                proxy2.foo();
                serializable proxy1 = createproxy(c1);
                proxy1.foo();
 }

private static <t> t createproxy(final t obj) {
        final invocationhandler handler = new invocationhandler() {
            @override
            public object invoke(object proxy, method method, object[] args)
                    throws throwable {
                return method.invoke(obj, args);
            }
        };
                //实现接口代理,demo1报错,demo2成功
                //java.lang.classcastexception: $proxy1 cannot be cast to
                //example.test$serializable
        return (t) proxy.newproxyinstance(obj.getclass().getclassloader(), obj
                .getclass().getinterfaces(), handler);
    }

可以看出这样这样设计是有道理的,因此,这并不是一个错误,很可能是作者josh bloch为了便于实现代理而精心设计的。
参考与:开发collection 的作者josh说
     2)randomaccess接口,这是一个标记接口,一般此标记接口用于 list 实现,以表明它们支持快速(通常是恒定时间)的随机访问,该接口的主要目的是允许通用算法改变其行为,以便在应用于随机或顺序访问列表时提供良好的性能,实现了该接口的话使用普通的for循环来遍历,性能更高,而没有实现该接口的话,使用iterator来迭代,这样性能更高,例如linkedlist。所以这个标记性只是为了让我们知道我们用什么样的方式去获取数据性能更好
     3)cloneable接口,可以使用object.clone()方法。
     4)serializable接口,序列化接口,表明该类可以被序列化,什么是序列化?简单的说,就是能够从类变成字节流传输,反序列化,就是从字节流变成原来的类

arraylist核心方法分析

1. add方法(4种重载实现)--增    

arraylist源码分析--jdk1.8

     1)add(e);//默认直接在末尾添加元素

/**
 * 新增元素
 */
public boolean add(e e) {
    //赋值初始长度  或者扩容,新增元素,当前实际size+1的长度
        ensurecapacityinternal(size + 1);  // increments modcount!!
        //添加元素
        elementdata[size++] = e;
        return true;
}
    /**
     * 确保elemendata数组有合适的大小
     * 如果元素为空,则复制长度默认为10 或者更大
    * @author jiaxiaoxian
    * @date 2019年2月12日 
     */
    private void ensurecapacityinternal(int mincapacity) {
            if (elementdata == empty_elementdata) {//如果数组为空,则从size+1的值和默认值10中取最大的
                    mincapacity = math.max(default_capacity, mincapacity);
            }
            ensureexplicitcapacity(mincapacity);
    }
/**
* 确保elemendata数组有合适的大小
* @author jiaxiaoxian
* @date 2019年2月12日 
* 如果长度大于元素长度则扩容
 */
private void ensureexplicitcapacity(int mincapacity) {
    //记录修改次数,迭代中不一致会触发fail-fast机制,因此在遍历中删除元素的正确做法应该是使用iterator.remove()
    modcount++;
    if (mincapacity - elementdata.length > 0)
        grow(mincapacity); //扩容
}
    /**
 * 扩容
 */
private void grow(int mincapacity) {
    int oldcapacity = elementdata.length; // 旧容量
    int newcapacity = oldcapacity + (oldcapacity >> 1); // 新容量为旧容量的1.5倍
    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 就报错,如果大于最大值 则取最大值
private static int hugecapacity(int mincapacity) {
    if (mincapacity < 0) // overflow
        throw new outofmemoryerror();
    return (mincapacity > max_array_size) ?
        integer.max_value :
        max_array_size;
}

     2)add(int index, e element);//给指定下标,添加元素

/**
 * 给指定下标,添加元素
 */
public void add(int index, e element) {
    //判断下标是否越界
    rangecheckforadd(index);
    //赋值初始长度  或者扩容
    ensurecapacityinternal(size + 1);  // increments modcount!!
    //将源数组中从index位置开始后的size-index个元素统一后移一位
    system.arraycopy(elementdata, index, elementdata, index + 1,
                     size - index);
    //赋值
    elementdata[index] = element;
    size++;
}
/**
 * 判断下标是否越界
 */
private void rangecheckforadd(int index) {
    if (index > size || index < 0)
        throw new indexoutofboundsexception(outofboundsmsg(index));
}
    /**
    *     src:源数组
 *   srcpos:源数组要复制的起始位置
 *   dest:目的数组
 *   destpos:目的数组放置的起始位置
 *   length:复制的长度
 *   注意:src 和 dest都必须是同类型或者可以进行转换类型的数组
 */
public static native void arraycopy(object src,  int  srcpos,
                                    object dest, int destpos,
                                    int length);

     3)addall(collection<? extends e> c);//添加collection类型元素

/**
 * 按照指定collection的迭代器所返回的元素顺序,将该collection中的所有元素添加到此列表的尾部
 */
public boolean addall(collection<? extends e> c) {
    object[] a = c.toarray();
    int numnew = a.length;
    ensurecapacityinternal(size + numnew);  // increments modcount
    //将数组a[0,...,numnew-1]复制到数组elementdata[size,...,size+numnew-1]
    system.arraycopy(a, 0, elementdata, size, numnew);
    size += numnew;
    return numnew != 0;
}

     4)addall(int index, collection<? extends e> c);//指定位置,添加collection类型元素

/**
 * 从指定的位置开始,将指定collection中的所有元素插入到此列表中,新元素的顺序为指定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;
    //先将数组elementdata[index,...,index+nummoved-1]复制到elementdata[index+nummoved,...,index+2*nummoved-1]
    //即,将源数组中从index位置开始的后nummoved个元素统一后移numnew位
    if (nummoved > 0)
        system.arraycopy(elementdata, index, elementdata, index + numnew,
                         nummoved);
    system.arraycopy(a, 0, elementdata, index, numnew);
    size += numnew;
    return numnew != 0;
}

总结:
   正常情况下会扩容1.5倍,特殊情况下(新扩展数组大小已经达到了最大值)则只取最大值。
   

2.remove方法(4种重载实现)--删

arraylist源码分析--jdk1.8

     1)remove(int index); //根据指定下标 删除元素     

    /**
 * 根据指定下标 删除元素
 */
public e remove(int index) {
    //判断索引是否越界
    rangecheck(index);
    modcount++;
    //获取旧元素
    e oldvalue = elementdata(index);
    //将数组elementdata中index位置之后的所有元素向前移一位
    int nummoved = size - index - 1;
    if (nummoved > 0)
        system.arraycopy(elementdata, index+1, elementdata, index,
                         nummoved);
    //将原数组最后一个位置置为null,由gc清理
    elementdata[--size] = null; // clear to let gc do its work
    return oldvalue;
}       

     2)remove(object o); //根据指定元素 删除元素 

 /**
 * 移除arraylist中首次出现的指定元素(如果存在),arraylist中允许存放重复的元素
 */
public boolean remove(object o) {
    // 由于arraylist中允许存放null,因此下面通过两种情况来分别处理。
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementdata[index] == null) {
                //私有的移除方法,跳过index参数的边界检查以及不返回任何值
                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++;
    //将数组elementdata中index位置之后的所有元素向前移一位
    int nummoved = size - index - 1;
    if (nummoved > 0)
        system.arraycopy(elementdata, index+1, elementdata, index,
                         nummoved);
    elementdata[--size] = null; // clear to let gc do its work
}
     /**
 * 清空arraylist,将全部的元素设为null,等待垃圾回收将这个给回收掉,所以叫clear
 */
public void clear() {
    modcount++;
    // clear to let gc do its work
    for (int i = 0; i < size; i++)
        elementdata[i] = null;
    size = 0;
}

     3)removeall(collection<?> c); //删除包含在指定容器c中的所有元素 

/**
 * 删除arraylist中包含在指定容器c中的所有元素
 */
public boolean removeall(collection<?> c) {
    //检查指定的对象c是否为空
    objects.requirenonnull(c);
    return batchremove(c, false);
}
     /**
 * 删除全部
* @author jiaxiaoxian
* @date 2019年2月12日 
 */
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) //判断指定容器c中是否含有elementdata[r]元素
                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 += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

     4)removeif(predicate<? super e> filter); //按照一定规则过滤(删除)集合中的元素 

/**
 * 按照一定规则过滤(删除)集合中的元素
 * 如:idlist.removeif(id -> id == nul);
    *   去掉 list idlist 集合中id 为 null 的
 * @param filter
 * @return
 */
@override
public boolean removeif(predicate<? super e> filter) {
    objects.requirenonnull(filter);
    // figure out which elements are to be removed
    // any exception thrown from the filter predicate at this stage
    // will leave the collection unmodified
    int removecount = 0;
    final bitset removeset = new bitset(size);
    final int expectedmodcount = modcount;
    final int size = this.size;
    for (int i=0; modcount == expectedmodcount && i < size; i++) {
        @suppresswarnings("unchecked")
        final e element = (e) elementdata[i];
        if (filter.test(element)) {
            removeset.set(i);
            removecount++;
        }
    }
    if (modcount != expectedmodcount) {
        throw new concurrentmodificationexception();
    }

    // shift surviving elements left over the spaces left by removed elements
    final boolean anytoremove = removecount > 0;
    if (anytoremove) {
        final int newsize = size - removecount;
        for (int i=0, j=0; (i < size) && (j < newsize); i++, j++) {
            i = removeset.nextclearbit(i);
            elementdata[j] = elementdata[i];
        }
        for (int k=newsize; k < size; k++) {
            elementdata[k] = null;  // let gc do its work
        }
        this.size = newsize;
        if (modcount != expectedmodcount) {
            throw new concurrentmodificationexception();
        }
        modcount++;
    }

    return anytoremove;
}

总结:
   remove函数用户移除指定下标的元素,此时会把指定下标到数组末尾的元素向前移动一个单位,并且会把数组最后一个元素设置为null,这样是为了方便之后将整个数组不被使用时,会被gc,可以作为小的技巧使用。

3.set方法--改

/**
 * 覆盖指定下标元素
 */
public e set(int index, e element) {
    //判断索引是否越界
    rangecheck(index);
    //获取旧元素
    e oldvalue = elementdata(index);
    //覆盖为新元素
    elementdata[index] = element;
    //返回旧元素
    return oldvalue;
}
     /**
 * 判断下标是否越界
 */
private void rangecheck(int index) {
    if (index >= size)
        throw new indexoutofboundsexception(outofboundsmsg(index));
}

4.get方法--查

 /**
 * 返回指定索引的值
 */
public e get(int index) {
    //判断索引是否越界
    rangecheck(index);
    return elementdata(index);
}
    /**
* @author jiaxiaoxian
* @date 2019年2月12日 
* 返回下标元素的 值
 */
@suppresswarnings("unchecked")
e elementdata(int index) {
    return (e) elementdata[index];
}

5.indexof方法--查找下标

/**
 * 查找下标, 如果为null,直接和null比较,返回下标
 */
public int indexof(object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementdata[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementdata[i]))
                return i;
    }
    return -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;
}

6.clone方法--克隆

 /**
 * 复制,返回此arraylist 的浅拷贝
 */
public object clone() {
    try {
        arraylist<?> v = (arraylist<?>) super.clone();
        v.elementdata = arrays.copyof(elementdata, size);
        v.modcount = 0;
        return v;
    } catch (clonenotsupportedexception e) {
        // this shouldn't happen, since we are cloneable
        throw new internalerror(e);
    }
}

7.trimtosize方法--删除冗余容量

/**
 * 判断数据实际容量大小,删除自动增长后冗余的容量
 * 该方法用于回收多余的内存。也就是说一旦我们确定集合不在添加多余的元素之后,调用 trimtosize() 方法会将实现集合的数组大小刚好调整为集合元素的大小。
 *   注意:该方法会花时间来复制数组元素,所以应该在确定不会添加元素之后在调用
 */
public void trimtosize() {
    modcount++;
    if (size < elementdata.length) {
        elementdata = arrays.copyof(elementdata, size);
    }
}

arraylist总结

1)arraylist可以存放null,本质是object[]类型的数组。
2)arraylist区别于数组的地方在于能够自动扩展大小,其中关键的方法就是gorw()方法。
3)arraylist由于本质是数组,所以它在数据的查询方面会很快,而在插入删除这些方面,性能下降很多,有移动很多数据才能达到应有的效果,而linkedlist则相反。
4)arraylist实现了randomaccess,所以在遍历它的时候推荐使用for循环。
5)初始化数组时推荐给初始长度,反复扩容会增加时耗,影响性能效率。