zoukankan      html  css  js  c++  java
  • ArrayList源码分析

    ArrayList源码分析

    1. private static final int DEFAULT_CAPACITY = 10;
      

    添加任意一个元素之后默认容量 DEFAULT_CAPACITY = 10 如果没有添加元素 默认容量是0

    当添加元素超过容量时,会进行扩容,扩容为原来的1.5倍。

    1. transient Object[] elementData; // non-private to simplify nested class access
      

    存放元素数组 elementData

    1. private int size;
      

    实际元素个数 size 默认值为0

    1. private static final Object[] EMPTY_ELEMENTDATA = {};
      
    2. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
      
    3. 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) {
                //DEFAULT_CAPACITY:10   minCapacity:1    
                minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); //10
            }
    
            ensureExplicitCapacity(minCapacity); //10
        }
    
    
    private void ensureExplicitCapacity(int minCapacity) {  //10
            modCount++; 
    
            // overflow-conscious code
            if (minCapacity - elementData.length > 0)  //10-0 > 0
                grow(minCapacity);
        }
    
    private void grow(int minCapacity) {  //10
            // overflow-conscious code
            int oldCapacity = elementData.length; //0
            int newCapacity = oldCapacity + (oldCapacity >> 1);//0
            if (newCapacity - minCapacity < 0)  //0-10
                newCapacity = minCapacity; //10
            if (newCapacity - MAX_ARRAY_SIZE > 0)  //MAX_ARRAY_SIZE = 0x7fffffff
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);  //10
        }
    
  • 相关阅读:
    Linux 下安装 numpy 和 scipy
    排序算法总结
    机器学习&数据挖掘笔记_16(常见面试之机器学习算法思想简单梳理)
    Java读取Excel并解析文本(并格式化输出)
    快捷键记忆
    初级应该学习的
    深入理解加密、解密、数字签名和数字证书
    数据签名和验签
    POI结构与常用类
    exlipse继承反编译插件
  • 原文地址:https://www.cnblogs.com/qiudajiang/p/13261020.html
Copyright © 2011-2022 走看看