一、简介

ArrayList是一个数组队列,相当于动态数组。每个ArrayList实例都有自己的容量,该容量至少和所存储数据的个数一样大小,在每次添加数据时,它会使用ensureCapacity()保证容量能容纳所有数据。

1.1、ArrayList 的继承与实现接口

ArrayList继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。

  1. public class  ArrayList<E> extends AbstractList<E>
             implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  • ArrayList 继承了AbstractList,实现了List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。
  • ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
  • ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。不过它实现的是对ArrayList 实例的浅拷贝。
  • ArrayList 实现java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。

1.2、ArrayList 与Collection集合的关系

1.3、ArrayList 与Vector的区别

ArrayList 与Vector大致等同,唯一的区别就是ArrayList的操作是线程不安全的,然而Vector是线程安全的。所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector或者CopyOnWriteArrayList。

二、源码分析

对于ArrayList而言,它实现List接口、底层使用数组保存所有元素。其操作基本上是对数组的操作。

2.1、成员变量

  1. private static final long serialVersionUID = 8683452581122892189L;    // 使用serialVersionUID验证版本一致性
    private static final int DEFAULT_CAPACITY = 10;    // 容量的初始大小
    private static final Object[] EMPTY_ELEMENTDATA = {};    // Shared empty array instance used for empty instances.
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};    // Shared empty array instance used for default sized empty instances.
    // ArrayList数据的存储之地
    transient Object[] elementData;    // 存储ArrayList中元素的数组
    // ArrayList存储数据的个数
    private int size;    

2.2、构造方法

ArrayList提供了三种方式的构造器方法:

1)通过传入的initialCapacity大小构造ArrayList

  1. 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);
        }
    }

2)使用初始容量值构造ArrayList

  1. public  ArrayList()
    {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

3)通过传入的指定类集构造ArrayList

  1. public ArrayList(Collection<? extends E> c)
    {
        elementData = c.toArray();
        if ((size = elementData.length) != 0)
        {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
  2.  
  3.     } else
        {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
 

2.3、增加元素操作

1)往数组尾部添加元素

  1. public boolean add(E e)
    {
        // 1、确保容量大小
        ensureCapacityInternal(size + 1); // Increments modCount!!
        // 2、尾部添加元素
        elementData[size++] = e;
        return true;
    }

2)在指定位置添加元素

  1. public void add(int index, E element)
    {
        // 1、检验索引
        rangeCheckForAdd(index);
        // 2、确保容量
        ensureCapacityInternal(size + 1); // Increments modCount!!
        // 3、将数据后移
        System.arraycopy(elementData, index, elementData, index + 1,
        size - index);
        // 4、添加元素
        elementData[index] = element;
        // 5、数组元素个数加1
        size++;
    }
  1. ==>System.arraycopy(src, srcPos, dest, destPos, length);

3)往数组尾部添加某类集合中所有元素,针对泛型

  1. public boolean addAll(Collection<? extends E> c)
    {
        // 1、暂存集合c中数据
        Object[] a = c.toArray();
        int numNew = a.length;
        // 2、确保容量
        ensureCapacityInternal(size + numNew); // Increments modCount
        // 3、尾部添加数据
        System.arraycopy(a, 0, elementData, size, numNew);
        // 4、数组元素个数更新
        size += numNew;
        return numNew != 0;
    }
注意:The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

4)在指定位置添加某类集合中所有元素,针对泛型

  1. public boolean addAll(int index, Collection<? extends E> c)
    {
        // 1、检验索引
        rangeCheckForAdd(index);
        // 2、暂存数据
        Object[] a = c.toArray();
        int numNew = a.length;
        // 3、确保容量
        ensureCapacityInternal(size + numNew); // Increments modCount
        int numMoved = size - index;
        // 4、数据后移
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
            numMoved);
        // 5、添加元素
        System.arraycopy(a, 0, elementData, index, numNew);
        // 6、数组元素个数更新
        size += numNew;
        return numNew != 0;
    }
 

2.4、删除元素操作

1)删除ArrayList中第一个符合条件的元素

  1. public boolean remove(Object o)
    {
        // 移除值为null的元素
        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;
    }

==>

  1. private void fastRemove(int index)
    {
        // 1、修改的次数更新
        modCount++;
        int numMoved = size - index - 1;
        // 2、数据前移
        if (numMoved > 0)
            System.arraycopy(elementData, index + 1, elementData, index,
            numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

2)删除ArrayList中指定位置上的元素

  1. public E remove(int index)
    {
        // 1、检验索引
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        // 2、数据前移
        if (numMoved > 0)
            System.arraycopy(elementData, index + 1, elementData, index,
            numMoved);
        elementData[--size] = null; // clear to let GC do its work
        return oldValue;
    }

3)删除ArrayList中所包含传入集合类中的所有元素,针对泛型

  1. public boolean removeAll(Collection<?> c)
    {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

4)删除某个范围的数据

  1. protected void removeRange(int fromIndex, int toIndex)
    {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
        // clear to let GC do its work
        int newSize = size - (toIndex - fromIndex);
        for (int i = newSize; i < size; i++)
        {
            elementData[i] = null;
        }
        size = newSize;
    }

5)删除ArrayList中不是所传入集合类中的所有元素,针对泛型

  1. public boolean retainAll(Collection<?> c)
    {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

2.5、修改操作

1)修改指定位置上的元素

  1. public E set(int index, E element)
    {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

2.6、查找操作

1)获取指定位置上的元素

  1. public E get(int index)
    {
        rangeCheck(index);
        return elementData(index);
    }

2)获取指定元素在列表中的第一个位置索引

  1. 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;
    }

3)获取指定元素在列表中的最后一个位置索引

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

4)返回某个范围的视图

  1. public List<E> subList(int fromIndex, int toIndex)
    {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

扩展:java List.subList方法中的超级大陷阱

 

5)迭代器

a>
  1. public Iterator<E> iterator()
    {
        return new Itr();
    }

b>

  1. public ListIterator<E> listIterator()
    {
        return new ListItr(0);
    }

扩展:JAVA中ListIterator和Iterator详解与辨析

c>

  1. public ListIterator<E> listIterator(int index)
    {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: " + index);
        return new ListItr(index);
    }

2.7、状态操作

1)是否为空

  1. public boolean isEmpty()
    {
        return size == 0;
    }

2.8、其它常用操作

1)清空列表所有元素

  1. public void clear()
    {
        modCount++;
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

2)克隆ArrayList实例的副本,浅拷贝

  1. 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);
        }
    }

3)判断是否包含某个指定元素

  1. public boolean contains(Object o)
    {
        return indexOf(o) >= 0;
    }
 

4)获取元素的个数

  1. public int size()
    {
        return size;
    }

2.9、辅助操作

1)确保容量大小

  1. public void ensureCapacity(int minCapacity)
    {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;
        if (minCapacity > minExpand)
        {
            ensureExplicitCapacity(minCapacity);
        }
    }

2)裁剪容量

  1. public void trimToSize()
    {
        modCount++;
        if (size < elementData.length)
        {
            elementData = (size == 0)
            ? EMPTY_ELEMENTDATA
            : Arrays.copyOf(elementData, size);
        }
    }

3)转换成数组

a> 该操作没有涉及到引用,属于安全操作

  1. public Object[] toArray()
    {
        return Arrays.copyOf(elementData, size);
    }
b> 针对泛型
  1. 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;
    }
 

三、扩展区

1、专题一、ArrayList增删操作技术细节详解

2、Java提高篇(三四)-----fail-fast机制(转载)

3、专题二、ArrayList序列化技术细节详解

4、专题三、ArrayList遍历方式以及效率比较

5、Java集合源码剖析(转载)

参考:

http://www.jb51.net/article/42764.htm

http://zhangshixi.iteye.com/blog/674856

Java中ArrayList源码分析的更多相关文章

  1. Java基础 ArrayList源码分析 JDK1.8

    一.概述 本篇文章记录通过阅读JDK1.8 ArrayList源码,结合自身理解分析其实现原理. ArrayList容器类的使用频率十分频繁,它具有以下特性: 其本质是一个数组,因此它是有序集合 通过 ...

  2. Java中HashMap源码分析

    一.HashMap概述 HashMap基于哈希表的Map接口的实现.此实现提供所有可选的映射操作,并允许使用null值和null键.(除了不同步和允许使用null之外,HashMap类与Hashtab ...

  3. 【thinking in java】ArrayList源码分析

    简介 ArrayList底层是数组实现的,可以自增扩容的数组,此外它是非线程安全的,一般多用于单线程环境下(Vector是线程安全的,所以ArrayList 性能相对Vector 会好些) Array ...

  4. java中LinkedList源码分析

    ArrayList是动态数组,其实本质就是对数组的操作.那么LinkedList实现原理和ArrayList是完全不一样的.现在就来分析一下ArrayList和LinkeList的优劣吧LinkedL ...

  5. Java集合-ArrayList源码分析

    目录 1.结构特性 2.构造函数 3.成员变量 4.常用的成员方法 5.底层数组扩容原理 6.序列化原理 7.集合元素排序 8.迭代器的实现 9.总结 1.结构特性 Java ArrayList类使用 ...

  6. java.util.ArrayList源码分析

    public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess ...

  7. java中AQS源码分析

    AQS内部采用CLH队列.CLH队列是由节点组成.内部的Node节点包含的状态有 static final int CANCELLED =  1; static final int SIGNAL    ...

  8. Java集合干货——ArrayList源码分析

    ArrayList源码分析 前言 在之前的文章中我们提到过ArrayList,ArrayList可以说是每一个学java的人使用最多最熟练的集合了,但是知其然不知其所以然.关于ArrayList的具体 ...

  9. Java - ArrayList源码分析

    java提高篇(二一)-----ArrayList 一.ArrayList概述 ArrayList是实现List接口的动态数组,所谓动态就是它的大小是可变的.实现了所有可选列表操作,并允许包括 nul ...

随机推荐

  1. 解决android锁屏或解锁后activity重启的问题

    If your target build version is Honeycomb 3.2 (API Level 13) or higher you must put the screenSize f ...

  2. POJ2184Cow Exhibition (01背包变形)

    思路一下子就想到了,转移方程却没想好,看到网上一个的思路相同的代码,改的转移方程. 同时dp全部初始化为负无穷,需要注意一下. AC代码如下: /*************************** ...

  3. oc学习之路----QQ聊天界面

    用到的技术:自定义cell,通知机制,代理模式 transform 1.自定义cell(通过代码自定义cell) ①首先新建一个类继承UITableViewCell ②重写initWithStyle: ...

  4. mmsql查看最近操作日志

    SELECT TOP 2000 query_stats.query_hash AS "Query Hash", Sum(Query_Stats.total_logical_Read ...

  5. 【面试虐菜】—— MongoDB知识整理

    为什么我们要使用MongoDB? 特点: 高性能.易部署.易使用,存储数据非常方便.主要功能特性有: 面向集合存储,易存储对象类型的数据. 模式自由. 支持动态查询. 支持完全索引,包含内部对象. 支 ...

  6. 解决div和父div不上对齐

    加一个vertical-align: top;就好了.原因就是inline-block会使元素向下对齐.这和padding-top,margin-top没有关系的.使用浮动就不会有这种情况了,当然会带 ...

  7. [Whole Web, Node.js, PM2] Configuring PM2 for Node applications

    In this lesson, you will learn how to configure node apps using pm2 and a json config file. Let's sa ...

  8. iOS数据库之查找功能的实现

    首先引入文件: libsqlite3. FMDB(包含Global.m,Global.h文件) 关闭arc 用mesaSqlite创建一个数据库,引入文件中 其次: 首先,在Global.h文件中找到 ...

  9. Referenced file contains errors (http://www.springframework.org/schema...错误--转载

    Referenced file contains errors (http://www.springframework.org/schema/beans/spring-beans-3.0.xsd). ...

  10. iOS开发UI篇-tableView在编辑状态下的批量操作(多选)

    先看下效果图 直接上代码 #import "MyController.h" @interface MyController () { UIButton *button; } @pr ...