当前位置: 首页 > news >正文

ArrayList的源码分析

我们平时创建列表的时候会经常使用ArrayList,它的源码究竟是什么样的,下面就来看一下我们常用的一些方法中的源码分析:

ArrayList继承了AbstractList,实现的接口有List、RandomAccess、Cloneable(可被克隆)、Serializable(支持序列化)

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    ……
}

ArrayList 内部使用的动态数组来存储元素 ,初始化默认数组的大小是10。

1)初始化时候可以用默认大小来创建:ArrayList<Object> a = new ArrayList<>();

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

 2)也可以根据实际大概的大小设定一个接近的初始大小:ArrayList<Object> b = new ArrayList<>(15); 其中15就是设置的一个初始大小值,根据实际可更改。设置这个初始大小如果实际够用就避免了扩容,当size的长度大于当前数组的长度时,就会进行一个扩容为当前长度的1.5倍,可能会浪费内存空间,扩容也会存在一定的耗时,后面说到扩容时候再细讲。

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

ArrayList的常用方法:

(1)get(int index)方法,根据下标在列表中查找指定位置的元素。当要查找位置超过列表大小,会报异常,否则直接返回指定位置元素,这个是直接从底层数组根据下标获取的,它的时间复杂度是O(1)

    /**
     * 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) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        return (E) elementData[index];
    }

 (2)add(E e)方法,将指定元素追加到此列表的末尾。当不需要扩容时,时间复杂度为O(1)

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

首先要判断是否需要扩容

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

如果需要扩容,以确保它至少可以容纳由最小容量参数指定的元素数量,扩容的时候,执行Arrays.copyOf()方法,把原有数组中的元素复制到扩容后的新数组当中,原数组被抛弃,会被GC回收。下面是扩容机制:

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

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

(3)另一个add(int index, E element)方法,将指定元素插入到此列表中的指定位置。将当前位于该位置的元素(如果有的话)和所有后续元素向右移动(向它们的索引添加1)。

    /**
     * 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) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

根据前面需要判断是否需要扩容,还要执行System.arraycopy()的拷贝方法,在数组中插入元素的时候,会把插入位置以后的元素依次往后复制,之后再通过 elementData[index] = element 将下标为index 的元素赋值为新的元素;随后执行 size = s + 1,得到新的数组的长度。时间复杂度为O(n)

(4)indexOf(Object o),返回指定元素在列表中第一次出现的索引,如果列表中不包含该元素,则返回-1。因为要遍历列表,所以时间复杂度为O(n)

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    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;
    }

 (5)set(int index, E element),用指定的元素替换此列表中指定位置的元素。直接从底层数组根据下标替换,时间复杂度为O(1)

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }

(6)contains(Object o),如果这个列表包含指定的元素,返回true。也用到了上面(4)中的ndexOf(Object o)方法遍历列表查找。时间复杂度为O(n)

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

(7)remove(int index),移除此列表中指定位置的元素。将所有后续元素向左移动(从它们的索引中减去1)。当移除最后一个元素的时候,时间复杂度为O(1);当移除其它元素时,考虑到需要复制底层数组,所以时间复杂度为O(n)

    /**
     * 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) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        modCount++;
        E oldValue = (E) 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;
    }

(8)remove(Object o),如果指定元素出现,则从此列表中删除第一个出现的元素。如果列表不包含该元素,则保持不变。

    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
    }

先要循环遍历列表找到要移除的元素,此时的时间复杂度已为O(n),当找到要移除的元素时,调用fastRemove()方法时,还要考虑到需要复制底层数组,时间复杂度还是O(n),整合在一起就是O(n)*O(n),也就是O(n²)

(9)clear(),从此列表中删除所有元素。此调用返回后,列表将为空。要遍历整个列表,因此时间复杂度为O(n)

    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

 

相关文章:

  • 不支持TLS的设备如何实现游客登录加密通信方案
  • 【Pandas 数据分析3-2】Pandas 数据读取与输出 - Excel
  • TiDB Dashboard 实例性能分析 - 持续分析页面
  • Spring Boot 集成 Redis 配置 MyBatis 二级缓存
  • 9 二叉树-添加
  • SSM进阶-搭建Dubbo
  • STM32F103 CAN通讯实操
  • JAVA-----注释、字面量、关键字、制表符
  • numpy数组的变形、级联操作、聚合操作、常用的数学函数以及矩阵相关
  • ActiveMQ(二)
  • 某大学ipv6和ipv4结合的校园网规划设计
  • 【程序员表白大师】html七夕脱单必看源码制作
  • 车载VPA形象发展史:谁是第一个吃螃蟹的人?
  • 22.9.30 喜迎暑假多校联赛第二场(欢乐AK找回自信)ABDEFH
  • C++----智能指针
  • 【许晓笛】 EOS 智能合约案例解析(3)
  • react 代码优化(一) ——事件处理
  • Shell编程
  • supervisor 永不挂掉的进程 安装以及使用
  • Vue 动态创建 component
  • vue从创建到完整的饿了么(18)购物车详细信息的展示与删除
  • web标准化(下)
  • 翻译 | 老司机带你秒懂内存管理 - 第一部(共三部)
  • 如何合理的规划jvm性能调优
  • 跳前端坑前,先看看这个!!
  • 移动互联网+智能运营体系搭建=你家有金矿啊!
  • 用jquery写贪吃蛇
  • $(selector).each()和$.each()的区别
  • (1)Android开发优化---------UI优化
  • (1综述)从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练
  • (android 地图实战开发)3 在地图上显示当前位置和自定义银行位置
  • (C#)一个最简单的链表类
  • (js)循环条件满足时终止循环
  • (Redis使用系列) Springboot 在redis中使用BloomFilter布隆过滤器机制 六
  • (ZT)薛涌:谈贫说富
  • (十六)一篇文章学会Java的常用API
  • (四)搭建容器云管理平台笔记—安装ETCD(不使用证书)
  • (五)c52学习之旅-静态数码管
  • (转)可以带来幸福的一本书
  • (转)树状数组
  • ..回顾17,展望18
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .gitattributes 文件
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .Net Redis的秒杀Dome和异步执行
  • .NET/C# 在代码中测量代码执行耗时的建议(比较系统性能计数器和系统时间)...
  • .net用HTML开发怎么调试,如何使用ASP.NET MVC在调试中查看控制器生成的html?
  • @media screen 针对不同移动设备
  • @Transactional 详解
  • [20150321]索引空块的问题.txt
  • [20150707]外部表与rowid.txt
  • [AI]文心一言出圈的同时,NLP处理下的ChatGPT-4.5最新资讯
  • [Android Pro] android 混淆文件project.properties和proguard-project.txt
  • [C#] 如何调用Python脚本程序