JDK source 之 ArrayList 需要注意事项

线程安全

ArrayList内部没有实现原子性操作,所以是非线程安全的。如果需要在线程安全的环境下使用List的话,需要使用Vector 或者CopyOnWriteArrayList,具体场景,自行深入了解。

扩容算法

// minCapacity 为需要的最小容量
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);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}
  1. 如代码所示,先在原来容量的基础上进行 1.5 倍的扩容;
  2. 如果扩容之后的值小于最小的容量需求,则使用最小容量需求;
  3. 如果扩容之后超出数组的限制长度,则根据最小容量需求判断使用Integer最大值还是数组限制长度。

indexOf 或者 lastIndexOf 的使用

这两个方法内部都是遍历实现的,所以在数组很大的时候尽量不要使用这两个方法,以免影响效率。

时间复杂度相关

  1. get 方法为 O(1);
  2. add(E e) 方法在尾部添加,为 O(1),add(int index, E element)方法在中间添加,时间复杂度最坏情况为O(n);
  3. remove 方法时间复杂度最坏情况为O(n)。

GC 相关的借鉴

remove 和 clear 操作之后都会做一次释放资源的操作,目的是释放资源,以便GC回收。

原文地址:https://www.cnblogs.com/liushijie/p/5273073.html