环境:JDK1.8
List:
有序可重复
- ArrayList:
1、底层是数组;
2、默认容量为10;
3、最大容量为(Integer.MAX_VALUE-8);
4、扩容时新容量为旧容量的1.5倍,即新容量=旧容量*1.5;
5、非线程安全。
// 获取当前容量
public static int getArrayListCapacity(ArrayList<?> arrayList) {
Class<ArrayList> arrayListClass = ArrayList.class;
try {
Field field = arrayListClass.getDeclaredField("elementData");
field.setAccessible(true);
Object[] objects = (Object[])field.get(arrayList);
return objects.length;
} catch (NoSuchFieldException e) {
e.printStackTrace();
return -1;
} catch (IllegalAccessException e) {
e.printStackTrace();
return -1;
}
}
add方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 1️⃣
elementData[size++] = e; //2️⃣
return true;
}
add方法就两行代码,1️⃣处表示判断是否扩容;2️⃣处表示将加入的e放在数组的末尾。
当出现并发的状况时,来看下为什么ArrayList是线程不安全的
一、当底层数组还有个空位置时
1、线程1执行1️⃣,因为有一个空位置,则不扩容,此时线程1让出CPU;
2、线程2执行1️⃣时因为有一个空位置,则不扩容,当执行完2️⃣之后,数组已满;
3、然后线程1获取CPU,开始执行2️⃣,此时数据已满,再进行添加时,就会提示数组下标越界
二、即将扩容
1、线程1执行1️⃣后,数组开始扩容,然后执行2️⃣,size++的过程是 读-改-写 三个步骤,当size=10;
2、线程2执行1️⃣后,因为线程1已经进行了扩容,则不需要再进行扩容,执行2️⃣,因为线程还未执行++的操作,此时size=10;
3、所以两个线程同时向size=10的下标写数据时,就会出现 脏数据 的情况
那么是如何进行扩容的呢?
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 3️⃣
return Math.max(DEFAULT_CAPACITY, minCapacity); //4️⃣
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); //5️⃣
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
3️⃣当进行无参构造函数时,在第一次调用add方法时会进行数组的初始化,4️⃣获取两者最大值,minCapacity=0,DEFAULT_CAPACITY =10
以上步骤是初始化过程,真正扩容的源码如下:
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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:
elementData = Arrays.copyOf(elementData, newCapacity);
}
newCapacity是新数组的长度,
newCapacity=oldCapacity+(oldCapacity>>1)
这句话的意思就是老数组的长度+老数组长度右移一位,newCapacity=1.5oldCapacity.
就是如果ArrayList集合扩容,则扩容为以前的1.5倍。下面的代码就很容易理解了,大家自行观看,然后把老数组的数据复制到新数组中。
remove方法
public E remove(int index) {
rangeCheck(index); //6️⃣
modCount++;
E oldValue = elementData(index); //7️⃣
int numMoved = size - index - 1; //8️⃣
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved); //9️⃣
elementData[--size] = null; // clear to let GC do its work 1️⃣0️⃣
return oldValue;
}
6️⃣是判断index是否合法,即index >= size则抛出异常
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
7️⃣是获取将要删除的值
8️⃣是获取将要移动的下标
9️⃣是把删除位置后面的数据进行向前移动
从add方法和remove方法可以知道,插入和删除都要对数组进行复制和移动,效率相比会很低,所以ArrayList不适合插入和删除较多的业务逻辑
查询
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index); //1️⃣1️⃣
return elementData(index); //1️⃣2️⃣
}
可以发现查询很简单,1️⃣1️⃣先判断index是否合法,1️⃣2️⃣然后通过指定下标获取值,时间复杂度为O(1),查询是非常高效的
- Set:无序不可重复,只能存在一个null
- HashSet
1、底层是HashMap;
2、具体API可参照HashMap。
- HashSet