Collection ArrayList

一、 源码分析

1.  ArrayList 类组成

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable    // 1. 实现了List接口,List继承Collection接口,Collection接口继承Iterable接口
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;        // 2. 默认数组容量大小(最小为10)  

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] 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 = {};   // 3. 共享空数组,不用赋值

    /**
     * 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.
     */
    transient Object[] elementData;        // 4. !!!存储数据数组(transient防止序列化,用自定义序列化方法,防止浪费多余空间) 

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * 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) {
        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;   // 5. 构造函数
    }

  

2. add(E)方法

* 1. 自动判断是否需要增加存储空间,如果需要,增加数组长度的一半(oldSize + oldSize>>1);
 * 2. mouCount++,如果在迭代器遍历是数据结构发生变化,报异常;
 * 3. Arrays.copyOf(data,newSize) 生成新数组;
 * 4. 赋值&Size++;

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        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;
        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);
    }

3. add(index,element)&remove(index)方法

耗时操作

System.arraycopy(Object src,

int srcPos,

Object dest,

int destPost,

int length);

 /**
     * 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!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

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

df

df

原文地址:https://www.cnblogs.com/qishuai/p/9049115.html

时间: 2024-08-08 04:04:06

Collection ArrayList的相关文章

安卓Kotlin单元测试/ Collection, ArrayList依赖的解耦/ MockK

本来这种依赖的解耦很复杂,以为不能实现. 原来,要了解for的运行机制,然后进行mock,就可以实现单元测试. 1. 这里是通过迭代遍历Collection. 需要的是.size和.iterator.hasNext(). fun getBeaconsInfo(beacons:Collection<Beacon>):HashMap<Int,Double>{ var infos = HashMap<Int,Double>() if (beacons.size > 0)

集合类Collection

数组与集合的区别:数组虽然也可以存储对象,但长度是固定的:集合的长度是可变的,数组中可以存储基本数据类型,集合只能存储对象. 集合特点:1.用于存储对象:  2.长度可变: 3.可存储不同对象: 一.Collection ArrayList<Object> list=new ArrayList<Object>(); list.add("A");//添加对象A; list.add(index,A);//在角标index位置上插入对象 A; list.addAll(

Java 集合--ArrayList

ArrayList构造函数 // 默认构造函数 ArrayList() // capacity是ArrayList的默认容量大小.当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半. ArrayList(int capacity) // 创建一个包含collection的ArrayList ArrayList(Collection<? extends E> collection) ArrayList的API // Collection中定义的API boolean add(E obj

Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例

概要 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具体实现类进行讲解:首先,讲解List,而List中ArrayList又最为常用.因此,本章我们讲解ArrayList.先对ArrayList有个整体认识,再学习它的源码,最后再通过例子来学习如何使用它.内容包括:第1部分 ArrayList简介第2部分 ArrayList数据结构第3部分 ArrayList源码解析(基于JDK1.6.0_45)第4部分 ArrayList遍历方式第5部分 toArray

Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例

java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java 集合系列 04 LinkedList详细介绍(源码解析)和使用示例 概要 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具体实现类进行讲解:首先,讲解List,而List中ArrayList又最为常用.因此,本章我们讲解ArrayList.先对ArrayLis

【转】Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例

概要 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具体实现类进行讲解:首先,讲解List,而List中ArrayList又最为常用.因此,本章我们讲解ArrayList.先对ArrayList有个整体认识,再学习它的源码,最后再通过例子来学习如何使用它.内容包括:第1部分 ArrayList简介第2部分 ArrayList数据结构第3部分 ArrayList源码解析(基于JDK1.6.0_45)第4部分 ArrayList遍历方式第5部分 toArray

C#中的ArrayList

ArrayList非常类似于数组,也有人称它为数组列表,ArrayList可以动态维护 提示: 和数组相似,ArrayList中存储的数据称为元素,ArrayList可以保存的元素数就是ArrayList容量,其默认初始容量为0,可以通过索引访问ArrayList中的元素,索引从0开始 ArrayList属于System.Collections命名空间,是集合的一种 using System.Collection ArrayList arr=new ArrayList(); ArrayList常

Difference between ArrayList and Vector In java

Reference: http://beginnersbook.com/2013/12/difference-between-arraylist-and-vector-in-java/ JAVA COLLECTIONS ArrayList and Vector both use Array as a data structure internally. However there are few differences in the way they store and process the

第十一课 集合类Collection和Map

集合类 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的方式. 数组和集合类都是容器,他们有什么不同? 数组虽然也可以存储对象,但长度是固定的:集合的长度是可变的,数组中可以存储基本数据类型,集合只能存储对象. 集合类的特点: 集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象. 注意:每一个容器的存储方式都有不同,这个存储方式称之为:数据结构 一.Collection ArrayList list = new Ar