jdk源码阅读笔记-ArrayList

1、ArrayList概述数组

首先咱们来讲一下ArrayList是什么?它解决了什么问题?ArrayList实际上是一个数组,可是有区别于通常的数组,它是一个能够动态改变大小的动态数组。ArrayList的关键特性也是这个动态的特性了,ArrayList的设计初衷就是为了解决Java数组长度不可变的问题。咱们都知道在Java中数组一旦被建立出来,那么这个数组的大小就不能够改变了,并且初始化的时候就必需要指定数组的大小。在开发的场景中不少时候咱们并不知道咱们的数据量有多少,若是数组建立得太大就会形成极大的空间资源的浪费,若是过小了又会报数组下标越界异常。这是咱们在开发的过程当中使用数组来存储数据时常常会遇到的问题,可是若是使用ArrayList的话,就能够轻易的解决这个问题,它可以根据你存放的数据的大小动态的改变数组的大小(本质建立新数组),因此咱们在写代码的时候就不须要关心数组的大小了,我以为这也是ArrayList建立出来所须要解决的问题。固然,若是在知道数组的大小且对数组的数据不增长的话,建议使用数组的存储数据,这样对性能的提高有必定的帮助。安全

那么,ArrayList是怎么动态扩展数组大小的呢?下面经过源码一步一步揭开ArrayList的神秘面纱吧。多线程

2、ArrayList全局变量app

 
/** * Default initial capacity. */ //默认的初始化大小  private static final int DEFAULT_CAPACITY = 10; /** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ //这个是用来存放数据用的数组,add进来的数据都是放到这个数组里面的  transient Object[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * * @serial */ //数组的大小  private int size;

3、ArrayList构造函数函数

ArrayList的构造函数有三个:性能

一、ArrayList(int initialCapacity):initialCapacity,数组的初始化大小,该构造器建立一个指定大小的空数组。ui

二、ArrayList():建立一个默认大小为0的空数组this

三、ArrayList(Collection<? extends E> c):建立一个与c同样大小的数组,并将c的元素赋值到数组中。线程

 
** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) {//建立一个 initialCapacity大小的空数组 if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() {//建立空数组 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public ArrayList(Collection<? extends E> c) { //将c转换成数组,toArray方法返回的数组类型有可能不是Object类型的 elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) //数组类型不是Object类型,须要将类型转换成Object类,避免后面调用方法 // 的时候出现类型转换异常 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }

这里咱们主要看一下Arrays.copyOf()方法是如何转换类型的:设计

 
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }

这个方法中,若是传入的类型为Object类型,那么就直接建立一个Object数组,不然建立一个对应类型的数组。而后调用System.arraycopy方法,将原数组赋值到新建立的数组中,强调一下,凡是使用到数组的地方就必定会使用到arraycopy的方法,这个方法我在String源码阅读有说到过,在这里我再跟你们说一下这个方法吧。

 
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

这是一个本地方法因此没法继续往下看源码了,可是从源码中能够知道每一个参数表明的含义

src:原数组

srcPos:原数组中开始复制的位置

dest:新数组,即目标数组

destPos:目标数组存放的位置,即从原数组的复制过来的元素从这个位置开始放

length:复制数组的长度

举个代码示例:

 
public static void main(String[] args) { int[] src = {1,2,3,4,5}; int[] dest = new int[6]; for (int i : dest) { System.out.print(i + " "); } System.out.println(); System.arraycopy(src,0,dest,0,src.length); for (int i : dest) { System.out.print(i + " "); } } //运行结果: //0 0 0 0 0 0  //1 2 3 4 5 0

看示例代码应该可以懂,第一次打印的时候dest只是被初始化没有赋值,因此里面每一个元素存放的都是默认值,而int的默认值为0,因此打印出来的都是0,以后arraycopy后将src的全部数据复制到dest从0位置开始,因此打印的结果是 1 2 3 4 5 0

4、add方法

 
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { //确认当前数组大小不会发生越界异常,否者对数组进行扩容 ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { //检查传入的下标是否在数组的范围以内 rangeCheckForAdd(index); //检查数组是否须要扩容 ensureCapacityInternal(size + 1); // Increments modCount!! //在index位置的元素所有日后移一位,为添加进来的元素腾出一个位置 System.arraycopy(elementData, index, elementData, index + 1, size - index); //将元素放入到index位置上 elementData[index] = element; size++; }

添加元素以前都须要检查一下当前的数组是否已经满了,若是满了就按照添加元素后的大小进行扩容。能够说在整个ArrayList类中最核心的方法就是ensureCapacityInternal了,这个方法就是用来动态扩容的。

 
private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } private void ensureExplicitCapacity(int minCapacity) { //修改次数+1,主要实现快速失败机制的 modCount++; // overflow-conscious code //若是最小所需容量比当前数组的长度大的话就进行扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); } /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ 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: //建立一个新的数组,长度为 newCapacity,而后将原来数组的元素复制到新数组上并返回新数组,达到动态扩容数组的目的 elementData = Arrays.copyOf(elementData, newCapacity); }

在每次添加数据的时候都须要检查一下添加数据后的长度是否大于当前数组的长度,大于的话就建立一个大小为原来数组的1.5倍的新数组,而后将原数组的数据都复制到新数组中,最后将原数组的引用指向新数组,从而达到了扩容的目标。

5、get方法

 
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { rangeCheck(index); return elementData(index); } // Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; }

获取数据的方法比较简单,直接根据数组的下标index找到元素就好了,因此查找的速度比较快。

6、delete方法

 
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ 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); elementData[--size] = null; // clear to let GC do its work return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == 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 remove method that skips bounds checking and does not * return the value removed. */ 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; // clear to let GC do its work }

删除有两个重载的方法,一个是传入一个数组的下标,另外一个是传入具体的内容,可是最总仍是根据equals方法查到index,而后根据index删除元素。假设有个数组为 String[] strs = {"a","b","c","d","e"},如今调用 remove(3),那个大概流程为:

 

7、ArrayList的使用:

 
public static void main(String[] args) { List<Integer> list = new ArrayList<>(); //添加操做 list.add(1); list.add(2); list.add(3); //删除操做 list.remove(0); //查询操做 //一、随机访问: for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } //加强for循环遍历 for (Integer integer : list) { System.out.println(integer); } //使用迭代器遍历 Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()){ Integer integer = iterator.next(); System.out.println(integer); } }

8、总结:

一、ArrayList的增删改查等全部操做,其内部都是对数组进行操做。

二、ArrayList的动态扩容其本质是建立一个更大的数组。

三、每次扩容都扩大到原来的1.5倍,1.5倍是比较理想的,若是每次扩容过小的话就会频繁扩容,每次扩容都须要进行数组的复制,性能消耗比较大,应该尽可能避免。若是扩容的倍数太大可能会形成空间的浪费。

四、ArrayList容许存放null值。

9、建议:

一、在知道数据大小且后期不会在添加数据的状况下建议使用数组,而不是ArrayList;

二、初始化前估计数据量的大小,尽可能指定ArrayList的初始化容量,避免进行频繁的数组复制操做;

三、在删除比较多场景中不建议使用ArrayList;

四、在查多删少的场景中建议使用ArrayList,缘由是这个类查找的速度很是快,时间复杂度为O(1),即无论数据量有多大,查找速度都同样的,并且很是快。可是删除操做是比较慢的,上面我也有提到过,ArrayList中每一次删除一个数据,后面全部的元素都要往前挪一位。若是数据量很是大,删除的数据恰好在第一个位置,那个后面的全部元素都要前移,时间复杂度为O(N),这样是很是耗费时间的。

五、ArrayList是非线程安全的,若是在多线程环境中对安全的要求比较高的,建议使用 CopyOnWriteArrayList这个类,不懂得能够百度一下,或者将ArrayList转成线程安全得,使用这种方式就能够:List list = Collections.synchronizedList(new ArrayList());

有兴趣能够加一下854630135这个群去交流一下噢

相关文章
相关标签/搜索