ArrayList源码分析

一、构造函数 一个无参构造,两个有参构造
1.无参构造
当调用无参构造的时候,默认返回一个空数组,从这里可以看出ArrayList集合的底层是数据。

//当调用空参构造时  返回一个空的数组
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
  /**  译:用于默认大小的空实例的共享空数组实例。我们将其与EMPTY_ELEMENTDATA区分开来,以了解添加第一个元素时的膨胀程度
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

2.有参构造

//当调用参数为int类型的有参构造时
 public ArrayList(int initialCapacity) {
 		//1-判断传入的参数 如果大于0 创建一个大小固定的数组,数组的大小和传入的参数大小一致
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        //2-如果等于0 创建一个空数组
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        //3-如果小于0 抛出异常
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }   
//当调用参数为集合类型的有参构造时
public ArrayList(Collection<? extends E> c) {
    	//1-把传入的集合转换成数组
        elementData = c.toArray();
       	//2-如果转化为数组 长度不为空
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            //2-1-这句话表示c.toArray方法可能返回的不是一个数组类型 
            //这是一个官方bug,说的就是public Object[] toArray() 返回的类型不一定就是 Object[],其类型取决于其返回的实际类型
            if (elementData.getClass() != Object[].class)
            	//2-2-拷贝这个数组
                elementData = Arrays.copyOf(elementData, size, Object[].class);
       //3-转化为数组 长度为空  创建一个空数组
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

二、.添加元素 四个方法 add()两个 addAll()两个
1.两个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})
     */
    //当调用add方法传入单个元素时
    public boolean add(E e) {
    	//1-检测是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //2-在数组的最后位置  把元素放进去
        elementData[size++] = e;
        return true;
    }

    /**
     * 译:用于默认大小的空实例的共享空数组实例。我们将其与EMPTY_ELEMENTDATA区分开来,以了解添加第一个元素时的膨胀程度。将指定元素插入其中		     
     * 的指定位置列表。移动当前处于该位置的元素(如果有)并任何向右的后续元素(将一个元素添加到它们的索引中)
     * 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}
     */
    //当调用addAll方法在指定位置插入元素时
    public void add(int index, E element) {
    	//1-判断index索引值是否越界
        rangeCheckForAdd(index);
        //2-检查是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //3-将index之后的元素都往后移动一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //4-把index位置赋上新值                 
        elementData[index] = element;
        //5-数组大小加1
        size++;
    }

2.两个addAll方法

/**
	 *译:将指定集合中的所有元素按照指定集合的迭代器返回它们的顺序追加到此列表的末尾。如果在操作过程中修改了指定的集合,则此操作的行为未定义。
	 *(这意味着,如果指定的集合是这个列表,而这个列表不是空的,则此调用的行为是未定义的。)
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    //当调用addAll方法传入参数是集合类型时
    public boolean addAll(Collection<? extends E> c) {
    	//1-把传入的集合转化成数组形式
        Object[] a = c.toArray();
        //2-得到转化后数组的长度
        int numNew = a.length;
        //3-检测是否需要扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //4-将转化的数组copy到原来的数组中
        System.arraycopy(a, 0, elementData, size, numNew);
        //5-把原来的数组大小加上新增数组大小长度
        size += numNew;
        //6-传入数组大小不为o返回true
        return numNew != 0;
    }

    /**
     *从指定位置开始,将指定集合中的所有元素插入此列表。将当前位于该位置的元素(如果有)和任何后续元素向右移动(增加它们的索引)。
     *新元素将按照指定集合的迭代器返回它们的顺序出现在列表中
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
    	//1-检查传入的index索引值是否合法
        rangeCheckForAdd(index);
        //2-将传入的集合转化成数组
        Object[] a = c.toArray();
        //3-得到转化后数组长度
        int numNew = a.length;
        //4-检测是否需要扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //5-判断index索引是否在原来数组的末尾
        int numMoved = size - index;
        if (numMoved > 0)
        	//5-1-如果不是在原来数组的末尾添加,那么原来数据索引之后的全部后移,后移要插入数组长度大小(numNew)位
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
		//6-如果在数组末尾添加,直接拷贝
        System.arraycopy(a, 0, elementData, index, numNew);
        //5-把原来的数组大小加上新增数组大小长度
        size += numNew;
        //6-传入数组大小不为o返回true
        return numNew != 0;
    }

3.扩容方法(ensureCapacityInternal(…))和数组拷贝方法(System.arraycopy(…))剖析

a.扩容方法(ensureCapacityInternal(…))
ArrayList类中的几个静态成员变量
在这里插入图片描述

    private void ensureCapacityInternal(int minCapacity) {
    	//1-如果是一个空数组
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        	//1-1-默认它的最小容量是10
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        //2-这个方法的grow才是真正执行扩容操作
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        //1-如果传入的数组容量大于原来数组的长度  调用grow()方法进行扩容
        if (minCapacity - elementData.length > 0)
               grow(minCapacity);
    }
    
    /** 译:要分配的数组的最大大小。一些vm在数组中保留一些标题词。
    	试图分配更大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
     //这个表示一个大数
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 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
        //1-得到原来数组的容量
        int oldCapacity = elementData.length;
        //2-新数组容量 = 原来的数组容量 + 原来数组容量的1/2
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //3-如果扩容之后的数组容量小于传入的数组容量   新的数组容量等于传入的数组容量大小
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //4-如果新的容量大小比MAX_ARRAY_SIZE 这个值大,调hugeCapacity方法增加容量
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
	    // 译:minCapacity通常接近于size,所以这是一个优势:
        // minCapacity is usually close to size, so this is a win:
        //5-将数组拷贝newCapacity个元素到原来的数组中
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
     //疯狂扩容
     private static int hugeCapacity(int minCapacity) {
     	//1-传入容量小于0,抛出内存溢出异常
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        //2-如果传入的容量大于这个大数,那么这个容量为Integer.MAX_VALUE(一个很大的数),
       	//如果小于那么这个容量为MAX_ARRAY_SIZE(也是一个很大的数)
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

*b.*数组拷贝方法(System.arraycopy(…)) 这是java本地一个方法参数具体描述如下,具体代码讲解点击链接学习
java的system.arraycpoy()方法详细介绍

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

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代码解释:
  Object src : 原数组
int srcPos : 从元数据的起始位置开始
  Object dest : 目标数组
  int destPos : 目标数组的开始起始位置
  int length : 要copy的数组的长度

  public static void main(String[] args) {


        String[] str1 = new String[]{"A","B","C","D","E"};//原数组
        String[] str2 = new String[10];//目标数组

        /*
        Object src : 原数组
        int srcPos : 从元数据的起始位置开始
       Object dest : 目标数组
      int destPos : 目标数组的开始起始位置
      int length  : 要copy的数组的长度
         */

        //第一个参数  原来的数组-要拷贝的数组
        //第二个参数
        //第三个参数
        //第四个参数
        System.arraycopy(str1,0,str2,1,str1.length);


        for (String ss :str2) {
            System.out.println(ss);
        }

    }

三、删除元素
1、remove(int index)方法

    /**
     * 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) {
    	//1-索引校验  判断删除索引是否合法
        rangeCheck(index);
		//2- ....	
        modCount++;
        //3-得到要删除的元素
        E oldValue = elementData(index);
		//4-判断从要删除位置要往后移几位
        int numMoved = size - index - 1;
        //5-如果不是删除最后一个元素
        if (numMoved > 0)
        	//5-1-将原来的数组从第index+1个位置开始,取numMoved个元素,从index位置开始放置
        	//简单的说就是说把index给从数组中去除
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //6-将删除的元素赋值为null  垃圾回收机制会将其回收
        elementData[--size] = null; // clear to let GC do its work
		//7-返回要删除的元素
        return oldValue;
    }

2、fastRemove(int index),这个方法其实和上面那个删除方法大致类似,从方法名字上我们可以知道这个是快速删除方法,这个和上述方法不同的调用这个方法没有边界校验,而且使用这个方法删除元素不会返回元素。

  /*   译:私有移除方法,该方法跳过边界检查且不返回被移除的值
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;
        //1-判断从要删除位置要往后移几位
        int numMoved = size - index - 1;
        //2-如果不是从集合的末尾删除元素
        if (numMoved > 0)
        	//2-1-将原来的数组从第index+1个位置开始,取numMoved个元素,从index位置开始放置---覆盖掉index位置元素
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //3-维护底层数组大小,指向null交给垃圾回收机制处理
        elementData[--size] = null; // clear to let GC do its work
    }

3、remove(Object o)方法 因为集合都是用来存放数组的,所以这个方法的意思就是删除指定元素。

   /**
     * 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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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) {
    	//1-如果传入的对象为null
        if (o == null) {
        	//1-1-遍历这个集合把为null的情况使用fastRemove方法全部删除
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        //2-如果传入的对象为null
        } else {
        	//2-1-遍历这个集合把这个集合中与传入对象内容相同的使用fastRemove方法全部删除
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        //3-否则返回false
        return false;
    }

4、clear()方法,清空集合

    /** 译:从列表中删除所有元素。该调用返回后,列表将为空。
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;
		//1-遍历集合的全部,将全部元素都指向null,交给垃圾回收机制回收
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
		//2-把清空集合把size值赋值为0
        size = 0;
    }

四、其它方法
1、将数组转换成集合,两个toArray方法

 /**  译:返回一个数组,该数组按正确的顺序(从第一个元素到最后一个元素)包含列表中的所有元素。
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     *译:返回的数组将是“安全的”,因为这个列表不维护对它的引用。(换句话说,这个方法必须分配一个新数组)。因此,调用者可以自由地修改返回的数组。
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     * 
     * 译:此方法充当基于数组和基于集合的api之间的桥梁。
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     *译:返回一个包含列表中所有元素的数组正确的序列
     * @return an array containing all of the elements in this list in
     *         proper sequence
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     *译:返回一个数组,该数组按适当的顺序包含列表中的所有元素(从第一个元素到最后一个元素);返回的*数组的运行时类型是指定数组的运行时类型。
     *如果列表符合指定的数组,则返回该列表。否则,将使用指定数组的运行时类型和此列表的大小分配新数组。
     * Returns an array containing all of the elements in this list in proper
     * sequence (from first to last element); the runtime type of the returned
     * array is that of the specified array.  If the list fits in the
     * specified array, it is returned therein.  Otherwise, a new array is
     * allocated with the runtime type of the specified array and the size of
     * this list.
     *
     * <p>If the list fits in the specified array with room to spare
     * (i.e., the array has more elements than the list), the element in
     * the array immediately following the end of the collection is set to
     * <tt>null</tt>.  (This is useful in determining the length of the
     * list <i>only</i> if the caller knows that the list does not contain
     * any null elements.)
     *
     *译:如果数组足够大,则将列表的元素存储到该数组中;否则,将为此分配相同运行时类型的新数组。
     * @param a the array into which the elements of the list are to
     *          be stored, if it is big enough; otherwise, a new array of the
     *          same runtime type is allocated for this purpose.
     * 
     * 译:返回一个包含列表元素的数组
     * @return an array containing the elements of the list
     * 
     * 译:如果指定数组的运行时类型为,则抛出ArrayStoreException不是每个元素的运行时类型的超类型这个列表
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this list
     * 
     * 译:如果指定的数组为空那么将抛出空指针异常
     * @throws NullPointerException if the specified array is null
     */
    @SuppressWarnings("unchecked")
    //使用泛型表示传入一个什么类型的数组,就返回一个什么类型的集合
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值