java(1.8)集合中的HashSet
Java(1.8)集合類中的HashMap
Java(1.8) 集合中的LinkedList
List 接口繼承于Collection 接口,Collection接口又繼承與Iterable接口。
List的所有接口如下:
List的所有接口
查看源碼,分析
ArrayList
實現最常用的add
和get
, 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;
}