java 源码分析2 -List

1.是一个接口,继承了Collection,提供了size(),isEmpty(),contanis(),iterator(),toArray(),clear()等方法

2.分析常用的ArrayList,LinkedList,set等

 

3. ArrayList 是一个对象数组

//被transient 定义的不进行序列化
private transient Object[] elementData;

 

b  add 方法

 public boolean add(E e) {
//扩容操作,通过sytem.copy 来复制       
 ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;

//num >> 1,相当于num除以2,每次增加原数组长度的二分之一
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);
}

// get 方法

public E get(int index) {

//检查边界
rangeCheck(index);

//取出下标对应的值

return elementData(index);
}

 

 

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; // Let gc do its work

return oldValue;
}

 

public void clear() {
modCount++;

// Let gc do its work

// 把所有元素值置为null,size为0
for (int i = 0; i < size; i++)
elementData[i] = null;

size = 0;
}

 

 



 

 

3 LinkedList 本质是 

//一个单向链表 

transient Node<E> first; /** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */ transient Node<E> last;


public boolean add(E e) {
linkLast(e);
return true;
}

 

 

void linkLast(E e) {

//把最后一个元素赋值给l
final Node<E> l = last;

//新建一个节点,上一个元素为l
final Node<E> newNode = new Node<>(l, e, null);

//最后一个节点为当前节点
last = newNode;

if (l == null)

//第一个节点为当前节点
first = newNode;
else

//l指向当前节点
l.next = newNode;
size++;
modCount++;
}

 

public E get(int index) {

//检查
checkElementIndex(index);

//取值

return node(index).item;
}

 

 

Node<E> node(int index) {
// assert isElementIndex(index);

if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size – 1; i > index; i–)
x = x.prev;
return x;
}
}

 

 

 

 

    原文作者:随心2017
    原文地址: https://www.cnblogs.com/suixin84/p/6737550.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞