Java source code Series 1 - ArrayList

This paper briefly describes ArrayList, and expansion, add, delete source code operations for analysis. Limited capacity, please correct me.

What the ArrayList?

ArrayListArray list is mainly used to load data. The underlying implementation is an array Object[] elementData, when we loaded the basic data type int, long, boolean, shot ... when we only store their corresponding package types.

And it is similar LinkedList, and LinkedListcompared it to find and access speed faster elements, but add, delete slower.

Thread-safe?

Thread unsafe.

Normal usage scenarios, ArrayListare used to query, it does not involve too frequent additions and deletions, if it involves frequent additions and deletions can be used LinkedList. If you need to use thread-safe Vector.

VectorIs ArrayListthread-safe version, is the implementation of all the methods combined with synchronizedpoor performance.

How to expansion?

Because the size of the array is fixed, when the capacity exceeds the size of an existing array, it is necessary for expansion.

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    // 每次扩大原有容量的一半
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    // 如果扩大一半后还是无法满足,则使用minCapacity
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    // 如果超过最大size,则获取最大容量的数组
    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);
}
复制代码

Why ArrayList low insertion efficiency?

There are two reasons:

  1. New capacity will detect enough, if not need expansion
  2. New tail faster, if it is added in the middle of the array or the head will be much slower, because the latter put all the elements moved back a
  3. The element is moved back a used copy System.arraycopy(), it is the nativemethod (java defines the interface, other languages), it's faster
/**
 * 添加在尾部
 */
public boolean add(E e) {
    // 检查容量
    ensureCapacityInternal(size + 1);
    // 添加在尾部
    elementData[size++] = e;
    return true;
}

/**
 * 按指定位置添加
 */
public void add(int index, E element) {
    // 检查index
    rangeCheckForAdd(index);

    // 检查容量
    ensureCapacityInternal(size + 1);
    // index后面的元素全部往后移一位
    System.arraycopy(elementData, index, elementData, index + 1,
                        size - index);
    elementData[index] = element;
    size++;
}
复制代码

How to remove elements efficiently?

Efficiency and add almost all the elements you want to move, but do not need to check and capacity expansion.

public E remove(int index) {
    // 检查index
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index);

    int numMoved = size - index - 1;
    if (numMoved > 0)
        // index后面的元素全部往前移一位
        System.arraycopy(elementData, index+1, elementData, index,
                            numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}
复制代码

Suitable queue it?

It is not suitable.

The FIFO queue is, all data needs to move back into the tail, the head, when the efficiency is very low. More suitable list queue.

new ArrayList <> (18) will initialize the array size?

It does not initialize the array size! ! !

This is the Java Bug.

The constructor and used in conjunction with initialCapcity, then set () method throws an exception.

public static void main(String[] args) {
    ArrayList<Integer> a = new ArrayList<>(12);
    System.out.println(a.size());
    a.set(3, 3);
}
复制代码

to sum up

  1. The underlying implementation is an array Object[] elementData
  2. Find speed and faster access to the elements, but add, delete slower
  3. Thread safe
  4. Every half the original size of the array expansion

Source series

Java source code Series 1 - ArrayList

Java source code Series 2 - HashMap

Java source code Series 3 - LinkedHashMap

This article first appeared on my personal blog chaohang.top

Author Zhang super

Please indicate the source

I welcome attention to the micro-channel public number [Ultra] will not fly, get updates first time.

Guess you like

Origin juejin.im/post/5e5273d06fb9a07cb1578845