代碼執行結論:
/*
現象:LinkedList在指定位置採用add(index,data)方式增加數據時,位置越靠前耗時越少,越靠後耗時越多(而ArrayList採用add(index,data)方式的耗時跟位置關係不大);
原因:雖說LinkedList底層屬於鏈表數據結構,不需要開闢一塊連續的內存地址空間,邏輯上連續即可,在新增、插入和刪除操作上佔優勢(只需要修改節點的前後指向即可,不需要移動數據);
但是因爲LinkedList在插入時需要移動指針到指定節點, 才能開始插入,一旦要插入的位置比較遠,LinkedList就需要一步一步的移動指針, 直到移動到插入位置;
這就解釋了, 爲什麼節點值越大, 時間越長, 因爲指針移動需要時間。而ArrayList是數據結構, 可以根據下標直接獲得位置, 這就省去了查找特定節點的時間,所以對ArrayList的影響不是特別大。
現象:LinkedList在頭部add數據時(採用add(0,data)和addFirst(data)兩種方式耗時差不多,都很少),耗時遠遠低於ArrayList(採用add(0,data));
原因:不像指定位置一樣不需要移動指針,也不需要像ArrayList一樣由於連續地址的原因移動數據。
現象:LinkedList在尾部add數據時採用指定位置add(lastIndex,data)的方式,ArrayList在尾部add數據時採用指定位置add(index,data)的方式,則LinkedList耗時遠遠高於ArrayList;
原因:跟在指定位置add(index,data)數據類似,越靠後LinkedList需要移動指針所花費的時間越多,而ArrayList查找效率本身就很高。
現象:LinkedList在尾部add數據時,如果採用addLast(i)的方式,ArrayList在尾部add數據時採用指定位置add(i)的方式,則LinkedList與ArrayList的耗時差不多;且兩者的效率都比使用指定位置的方式有了極大提升
原因:LinkedList不像指定位置的方式那樣,不再需要移動指針到指定位置;ArrayList不再像指定位置的方式那樣,不再需要查詢索引位置。
現象:LinkedList在remove(index)指定位置的數據時,位置越靠前耗時越少,越靠後耗時越多;
原因:跟在指定位置插入數據類似,越靠後移動指針所花費的時間越多。
現象:LinkedList在remove(Object)指定的數據時,耗時遠少於ArrayList;
原因:不像指定位置一樣不需要移動指針,也不需要像ArrayList一樣由於連續地址的原因移動數據。
*/
public class TestArrayList {
private static final int index = 100000;
static List<Integer> list = null;
public static void main(String[] args) {
//測試ArrayList和LinkedList的插入效率
addElementInList(list, "ArrayList");
addElementInList(list, "LinkedList");
//測試ArrayList和LinkedList的查詢效率
}
private static void addElementInList(List<Integer> list, String type){
if(type == "ArrayList"){
list = new ArrayList();
for(int i = 0; i < index; i++){
list.add(i);
}
}
if(type == "LinkedList"){
list = new LinkedList();
for(int i = 0; i < index; i++){
list.add(i);
}
}
long begin = System.currentTimeMillis();
// int n = 20000;
int n = index;
// int n = 0;
for(int i = 0; i < index; i++){
if(type == "LinkedList"){
list.add(n,i);
// ((LinkedList)list).addLast(i);
// ((LinkedList)list).addFirst(i);
}else{
list.add(n,i);
// list.add(i);
}
}
long end = System.currentTimeMillis();
System.out.printf("在%s集合的索引爲%d的位置插入%d條數據,總耗時爲%d毫秒\n", type,n, index, end - begin);
/*long begin2 = System.currentTimeMillis();
for(int i = 0; i < index/6; i++){
if(type == "LinkedList"){
((LinkedList)list).remove(i);
// ((LinkedList)list).remove((Object)i);
// ((LinkedList)list).remove();
}else{
((ArrayList)list).remove(i);
// ((ArrayList)list).remove((Object)i);
}
}
long end2 = System.currentTimeMillis();
System.out.printf("在%s集合remove(index)%d條數據,總耗時爲%d毫秒\n", type, index, end2 - begin2);*/
long begin2 = System.currentTimeMillis();
for(int i = 0; i < index; i++){
if(type == "LinkedList"){
// ((LinkedList)list).remove(i);
((LinkedList)list).remove((Object)i);
// ((LinkedList)list).remove();
}else{
// ((ArrayList)list).remove(i);
((ArrayList)list).remove((Object)i);
}
}
long end2 = System.currentTimeMillis();
System.out.printf("在%s集合remove(Object)%d條數據,總耗時爲%d毫秒\n", type, index, end2 - begin2);
}
}