java arraylist 常用方法_分享ArrayList中的几个常用方法的源码
jdk1.7.0_79
上文里解析了有關ArrayList中的幾個常用方法的源碼——《有關ArrayList常用方法的源碼解析》,本文將對LinkedList的常用方法做簡要解析。
LinkedList是基于鏈表實現的,也就是說它具備了鏈表的優點和缺點,隨機訪問慢、插入刪除速度快。既然是鏈表,那么它就存在節點數據結構,也不存在容量大小的問題,來一個在尾部添加一個。
//LinkedList$Nodeprivate static class Node {
E item;
Node next;
Node prev;
Node(Node prev, E element, Node next) {this.item = element;this.next = next;this.prev = prev;
}
}
第一個默認不帶參數的構造方法,構造一個空鏈表。
//1.LinkedList,默認構造方法public LinkedList() {
}
第二個構造方法能把一個集合作為一個參數傳遞,同時集合中的元素需要是LinkedList的子類。
//2.LinkedList,能將一個集合作為參數的構造方法public LinkedList(Collection extends E> c) {this();
addAll(c);
}
兩個構造方法都比較簡單,接下來看元素的插入及刪除等方法。
public boolean add(E e) {
linkLast(e); //將元素添加到鏈表尾部return true;
}
//LinkedList#linkLastvoid linkLast(E e) {final Node l = last; //鏈表尾指針引用暫存final Node newNode = new Node<>(l, e, null); //構造新節點last = newNode; //將鏈表的尾指針指向新節點if (l == null) //此時為第一次插入元素first = newNode;elsel.next = newNode;
size++; //鏈表數據總數+1modCount++; //modCount變量在《有關ArrayList常用方法的源碼解析》提到過,增刪都會+1,防止一個線程在用迭代器遍歷的時候,另一個線程在對其進行修改。}
學過《數據結構》的同學相信看到鏈表的操作不會感到陌生,接著來看看刪除指定位置的元素remove(int)方法。
//LinkedList#removepublic E remove(int index) {
checkElementIndex(index); //檢查是否越界 index >= 0 && index <= sizereturn unlink(node(index)); //調用node方法查找并返回指定索引位置的Node節點}
//LinkedList#node,根據索引位置返回Node節點Node node(int index) {if (index < (size >> 1)) { //size >> 1 = size / 2,如果索引位于鏈表前半部分,則移動fisrt頭指針進行查找Node x = first;for (int i = 0; i < index; i++)
x = x.next;return x;
} else { //如果索引位于鏈表后半部分,則移動last尾指針進行查找Node x = last;for (int i = size - 1; i > index; i--)
x = x.prev;return x;
}
}
查找到index位置的Node后,調用unlink方法摘掉該節點。
//LinkedList#unlink,一看即懂E unlink(Node x) {// assert x != null;final E element = x.item;final Node next = x.next;final Node prev = x.prev;if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;return element;
}
從代碼中就能看出LinkedList和ArrayList兩者的優缺點,由于只涉及簡單的鏈表數據結構,所以不再對其他方法進行解析。
總結
以上是生活随笔為你收集整理的java arraylist 常用方法_分享ArrayList中的几个常用方法的源码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java serializable 源码
- 下一篇: java spring eventbus