Java(1.8)集合中的ArrayList

来源:互联网 发布:sql语句 添加字段 编辑:程序博客网 时间:2024/05/29 04:27

java(1.8)集合中的HashSet
Java(1.8)集合类中的HashMap
Java(1.8) 集合中的LinkedList

List 接口继承于Collection 接口,Collection接口又继承与Iterable接口。
List的所有接口如下:

List的所有接口
查看源码,分析ArrayList实现最常用的addget, remove方法.
ArrayList 的底层实现是用数组存储数据的,

transient Object[] elementData;

add方法:

public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }

首先保证数组长度,如果长度加1后,大于了原数组的长度,系统会增加原来长度的一半,再把需要添加的元素放到上个元素的后面。

 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);    }

指定位置的添加元素的方法add(int index, E element)

    public void add(int index, E element) {        rangeCheckForAdd(index);        ensureCapacityInternal(size + 1);  // Increments modCount!!        System.arraycopy(elementData, index, elementData, index + 1,                         size - index);        elementData[index] = element;        size++;    }

确保了数组够用后,直接把index 后面的拷贝到原数组index+1后面,留给当前要插入的index位置。
System.arraycopy 方法调用的是Native 的方法,因此效率比较高。
get方法直接返回数据中的指定位置的元素,remove 和add差不多,原始通过System.arraycopy来移动数据,把最后的元素设置成null.

 public E remove(int index) {        rangeCheck(index);        modCount++;        E oldValue = elementData(index);        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        elementData[--size] = null; // clear to let GC do its work        return oldValue;    }
原创粉丝点击