文章目录
ArrayList继承关系
ArrayList概述
- ArrayList底层是数组,数组在内存中是一块连续的内存空间,等于知道元素的内存地址,可以随机访问。
- ArrayList的默认容量是10,每次扩容新容量是旧容量的1.5倍,最终调用
System.arraycopy()
实现底层扩容和增删等操作。 - ArrayList查询效率高,增删效率低,线程不安全。
c.toArray might (incorrectly) not return Object[]问题
String[] ss = {"a", "b", "c"};
List<String> strings = Arrays.asList(ss);//保存了原有类型,不推荐使用
Object[] objs = strings.toArray();//仍然是原有类型
System.out.println(objs.getClass() == Object[].class);//false
推荐使用:
List<Object> l = new ArrayList<Object>(Arrays.asList("a", "b","c"));
ArrayList源码分析
属性
//序列化版本号
private static final long serialVersionUID = 8683452581122892189L;
//默认容量为10
private static final int DEFAULT_CAPACITY = 10;
//空数组,容量为0时调用
private static final Object[] EMPTY_ELEMENTDATA = {};
//空数组,默认初始化时调用
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//对象数组,用于存储数据,ArrayList的核心
transient Object[] elementData;
//集合大小,不一定等于elementData长度
private int size;
//最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//修改计数,指列表在结构上的修改次数,如:add() remove()
protected transient int modCount = 0;
构造函数
//指定容量的构造函数
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//若初始化容量大于0,则创建指定容量的数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//若初始化容量为0,则使用默认的EMPTY_ELEMENTDATA数组
this.elementData = EMPTY_ELEMENTDATA;
} else {
//初始化容量小于0,抛出异常
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
}
//默认容量的构造函数
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//传入一个集合的构造函数
public ArrayList(Collection<? extends E> c) {
//集合转数组
elementData = c.toArray();
if ((size = elementData.length) != 0) {
//c.toArray可能不能返回Object[]类型
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
this.elementData = EMPTY_ELEMENTDATA;
}
}
size()
//返回集合大小
public int size() {
return size;
}
isEmpty()
//集合是否为空,size=0表示ArrayList为空
public boolean isEmpty() {
return size == 0;
}
get() & set()
//返回指定下标的元素
public E get(int index) {
//检测是否越界
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
//替换指定下标的元素,并返回旧元素
public E set(int index, E element) {
//检测是否越界
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
add()
//添加指定元素在集合末尾
public boolean add(E e) {
//检查容量,容量不够扩容处理
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
//添加指定元素在指定位置处
public void add(int index, E element) {
//下标检测
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//扩容检测
ensureCapacityInternal(size + 1);
//elementData赋值操作
System.arraycopy(elementData, index, elementData, index + 1, size - index);
//将指定位置设置元素
elementData[index] = element;
//集合大小加1
size++;
}
//检测容量,若容量不够则扩容
private void ensureCapacityInternal(int minCapacity) {
//如果elementData为默认空数组,则默认容量和传入容量取最大值
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//检测是否扩容
ensureExplicitCapacity(minCapacity);
}
//检测是否扩容
private void ensureExplicitCapacity(int minCapacity) {
//修改计数加1
modCount++;
//若所需容量大于elementData长度则作扩容处理
if (minCapacity - elementData.length > 0)
//扩容
grow(minCapacity);
}
//扩容,重点
private void grow(int minCapacity) {
//获取旧容量
int oldCapacity = elementData.length;
//获取新容量,新容量为旧容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//若新容量小于传入容量,则将新容量设为传入容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//若新容量大于最大容量限制,则进行容量检查,并返回新容量
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//使用Arrays#copyOf进行扩容生成新数组
elementData = Arrays.copyOf(elementData, newCapacity);
}
//最大容量检查
private static int hugeCapacity(int minCapacity) {
//传入容量小于0抛出异常
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
//若传入容量大于Integer.MAX_VALUE,则返回Integer.MAX_VALUE;否则返回MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
remove()
//移除指定下标的元素,并返回旧值
public E remove(int index) {
//下标检测
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//修改计数加1
modCount++;
//获取旧值
E oldValue = (E) elementData[index];
//计算需要移动的数量
int numMoved = size - index - 1;
if (numMoved > 0)
//重新赋值elementData数组
System.arraycopy(elementData, index+1, elementData, index, numMoved);
//将末尾元素设null,size减1
elementData[--size] = null;
//返回旧值
return oldValue;
}
//删除指定元素,并返回删除是否成功
public boolean remove(Object o) {
if (o == null) {
//指定对象为null时,遍历数组元素用==比较
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
//指定对象不为null时,遍历数组用equals比较
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//删除指定下标元素,不作下标校验
private void fastRemove(int index) {
//修改计数加1
modCount++;
//计算移动数量
int numMoved = size - index - 1;
if (numMoved > 0)
//重新复杂elementData数组
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null;
}
addAll()
//添加指定集合在末尾
public boolean addAll(Collection<? extends E> c) {
//将指定集合转数组
Object[] a = c.toArray();
//需要扩容大小
int numNew = a.length;
//检查扩容并扩容
ensureCapacityInternal(size + numNew);
//elementData赋值操作
System.arraycopy(a, 0, elementData, size, numNew);
//集合大小增加
size += numNew;
return numNew != 0;
}
//添加指定集合在指定位置
public boolean addAll(int index, Collection<? extends E> c) {
//下标检查
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//和addAll()类似
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
removeAll()
//删除指定集合的元素
public boolean removeAll(Collection<?> c) {
//检测对象是否为null
Objects.requireNonNull(c);
//批量删除
return batchRemove(c, false);
}
//批量删除
private boolean batchRemove(Collection<?> c, boolean complement) {
//拷贝elementData
final Object[] elementData = this.elementData;
//r表示遍历的值的下标,w表示符合条件的元素数量
int r = 0, w = 0;
//是否被修改
boolean modified = false;
try {
//遍历elementData
for (; r < size; r++)
//当complement为false时,c中不包含的元素放入elementData
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
//当存在并发修改,r不等于size抛出了异常
if (r != size) {
//若存在并发删除,则size-r为负数,抛出ArrayIndexOutOfBoundsException异常
//若存在并发添加,则将添加的元素追加到w索引后
System.arraycopy(elementData, r, elementData, w, size - r);
w += size - r;
}
//成功删除了元素,将后面空间置空
if (w != size) {
//将w后面的元素置空
for (int i = w; i < size; i++)
elementData[i] = null;
//重新设置修改计数
modCount += size - w;
//集合大小重新设置
size = w;
//设置为被修改
modified = true;
}
}
return modified;
}
sort()
//集合排序
public void sort(Comparator<? super E> c) {
//复制一份modCount用fianl修饰,防止ArrayList不被外部修改
final int expectedModCount = modCount;
//调用Arrays.sort()排序
Arrays.sort((E[]) elementData, 0, size, c);
//排序时修改抛出异常
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
clear()
//清空集合
public void clear() {
//修改计数加1
modCount++;
//遍历清空元素
for (int i = 0; i < size; i++)
elementData[i] = null;
//集合大小设为0
size = 0;
}
indexOf()
//返回元素的下标
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
//通过equals()判断
if (o.equals(elementData[i]))
return i;
}
return -1;
}
contains()
//是否包含该元素
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
clone()
//clone出新的对象
public Object clone() {
try {
//使用clone(),该克隆为浅拷贝,如果是引用类型只拷贝引用
ArrayList<?> v = (ArrayList<?>) super.clone();
//elementData数组赋值
v.elementData = Arrays.copyOf(elementData, size);
//将修改计数设为0
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
toArray()
//ArrayList转数组,调用Arrays#copyOf()生成新的数组
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public <T> T[] toArray(T[] a) {
if (a.length < size)
//当数组的大小小于集合的大小时,调用Arrays#copyof()生成新的数组
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
//当大于等于集合时,调用System#arraycopy复制数据
System.arraycopy(elementData, 0, a, 0, size);
//当大于集合时,多余的空间存入null
if (a.length > size)
a[size] = null;
return a;
}
推荐使用:
- 当数组长度等于集合size时,会动态创建和集合size相同的数组,性能最优。
- 当数组长度大于0且小于size时,会扩容重建数组,同时原数组也白白浪费空间。
- 当数组长度等于集合size时,情况和第二条相同。
- 当数组长度大于集合size时,多余的空间会传入null。
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("111");
arrayList.add("222");
arrayList.add("333");
arrayList.add("444");
String[] strings = arrayList.toArray(new String[0]);