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);
- src: 待复制的数组
- srcPos: 待复制的数组起始索引 从0开始
- dest: 目标数组
- destPos: 目标数组起始下标
- 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
本文详细解析了 Java 中 ArrayList 的源码实现,包括默认大小、扩容机制、内存复制方法、同步特性及 null 值处理等内容。此外,还介绍了与 ArrayList 相对应的同步集合 Vector。
1039

被折叠的 条评论
为什么被折叠?



