探析ArrayList源码
一. ArrayList字段
1. 默认初始容量DEFAULT_CAPACITY为10
2. Object数组,存放元素的地方
3. 当前ArrayList的大小
4. 空数组,容量为0
二.ArrayList构造器
1. 生成指定容量的ArrayList
2. 生成默认容量的ArrayList(开始容量为0,在第一次添加元素容量变为10)
三.ArrayList核心方法
1. add方法
其中,ensureCapacityInternal方法
calculateCapacity方法
ensureExplicitCapacity方法
grow方法
2. get方法
3. remove方法
remove方法主要查看remove(int index)与remove(Object o)这两个重载方法
remove(int index)方法
remove(Object o)方法
4. clear方法
5. contains方法
indexOf方法
四.小结
ArrayList是基于数组实现的容器类,当需扩容时,扩容为旧容量的1.5倍。由于ArrayList是基于数组实现,所以具有随机访问的特点,但是增加与删除操作比较耗时,因为需要平均移动一半的数组元素。