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

Java系列-ArrayList源码

1.ArrayList的数据保存在数组里

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    private static final Object[] EMPTY_ELEMENTDATA = {};

    transient Object[] elementData;

    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.add添加数据

如果需要扩容,就对数组扩容

添加数据

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    private int size; //实际数据的个数
    private static final int DEFAULT_CAPACITY = 10;
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    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
        //如果数组的length小于minCapacity
        if (minCapacity - elementData.length > 0)
            grow(minCapacity); //扩容
    }

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果根据老数组的长度计算的新长度小于 minCapacity, 用minCapacity
        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.get是直接通过index从数据获取元素

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    public E get(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        return (E) elementData[index]; //直接从数组获取
    }
}

    

4.remove index

从index+1开始的数据都往前移动一位

最后一个数据重置为null

size减1

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    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);
        }
        //size减1
        //size-1的数据赋值为null
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
}
    

5.remove object

这里可见ArrayList允许加入null

遍历找到该元素的index

从index+1开始的数据都往前移动一位

最后一个数据重置为null

size减1

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    public boolean remove(Object o) {
        //object为null,不为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;
    }

    //这里跟remove(int index)一样,只是少了index的有效性判断和读取oldValue
    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
    }
}
    


http://www.kler.cn/a/157833.html

相关文章:

  • svn服务端安装
  • php获取本年、本月、本周时间戳和日期格式(2020)
  • 为什么每天都要做晨会?揭秘研发团队的默契背后
  • 【android开发-07】android中ImageView的用法介绍
  • 浪涌保护器参数指南:浪涌保护器行业选型方案
  • xampp环境安装
  • Visual Studio2022创建Windows服务程序
  • Ubuntu环境下使用nginx实现强制下载静态资源
  • c++ 执行系统命令system 、popen
  • 使用Python Flask搭建Web问答应用程序并发布到公网远程访问
  • 快速学习PyQt5的高级自定义控件
  • 25.Python 网络编程:TCP和UDP编程
  • python-批量调整指定目录下所有图片文件的大小
  • uniapp-hubildx配置
  • 《消息队列MyMQ》——参考RabbitMQ实现
  • leetcode做题笔记1038. 从二叉搜索树到更大和树
  • 聊聊 Jetpack Compose 的 “状态订阅自动刷新” -- mutableStateListOf
  • 25、pytest的测试报告插件allure
  • es常用查询编辑
  • 【计算机网络笔记】物理层——物理介质