Java ArrayList源码分析

Java ArrayList源码分析

1. ArrayList默认大小 10

private static final int DEFAULT_CAPACITY = 10;

ArrayList 底层实现Object[]数组

transient Object[] elementData;

2. 扩容方式

//扩容函数
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;   //原数组长度
    //新容量扩容  原数组右移一位除以2,扩容1.5倍
    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:
    //采用系统的Arrays.copyOf函数进行内存分配
    elementData = Arrays.copyOf(elementData, newCapacity);
}

2.1 系统arraycopy方法

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
  1. src: 待复制的数组
  2. srcPos: 待复制的数组起始索引 从0开始
  3. dest: 目标数组
  4. destPos: 目标数组起始下标
  5. length: 待复制数组复制元素个数
Object[] object = new Object[6];
object[0] = "name";
object[1] = "age";
object[2]= "grade";
System.arraycopy(object,0,object,3,3);

==> object = {"name","age","grade","name","age","grade"}

3. 是否同步

4. 是否允许null值

底层是Objec[]实现, 数组可以保存null

5. 对应的同步集合

Vector

猜你喜欢

转载自blog.csdn.net/rambokitty/article/details/80547885