Java學習筆記31,java學習筆記
我們知道數組是以一塊連續記憶體區來儲存所有的數組元素,所以數組在隨機訪問時效能最好。所有的內部以數組作
為底層實現的集合在隨機訪問時效能較好;而內部以鏈表作為底層實現的集合在執行插入、刪除操作時效能較好;
進行迭代操作時,以鏈表作為底層實現的集合比以數組作為底層實現的集合效能好。
我們來看以下程式:
public class Main {public static void main(String[] args) {ArrayList array_list=new ArrayList();for(int i=0;i<3333333;i++){array_list.add(i);}LinkedList linked_list=new LinkedList();for(int i=0;i<3333333;i++){linked_list.add(i);}long iterator_start1=System.currentTimeMillis();for(int i=0;i<10000;i++){array_list.get(i);}System.out.println("使用get()方法遍曆ArrayList集合的元素所需時間:"+(System.currentTimeMillis()-iterator_start1));long linked_iterator_start1=System.currentTimeMillis();for(int i=0;i<10000;i++){linked_list.get(i);}System.out.println("使用get()方法遍曆LinkedList集合的元素所需時間:"+(System.currentTimeMillis()-linked_iterator_start1));Iterator array_list_iterator=array_list.iterator();long iterator_start=System.currentTimeMillis();while(array_list_iterator.hasNext()){array_list_iterator.next();}System.out.println("迭代ArrayList集合的元素所需時間:"+(System.currentTimeMillis()-iterator_start));Iterator linked_list_iterator=linked_list.iterator();long linked_iterator_start=System.currentTimeMillis();while(linked_list_iterator.hasNext()){linked_list_iterator.next();}System.out.println("迭代LinkedList集合的元素所需時間:"+(System.currentTimeMillis()-linked_iterator_start));long arraylist_remove=System.currentTimeMillis();array_list.remove(34567);System.out.println("ArrayList刪除集合元素所需時間:"+(System.currentTimeMillis()-arraylist_remove));long linkedlist_remove=System.currentTimeMillis();linked_list.remove(34567);System.out.println("LinkedList刪除集合元素所需時間:"+(System.currentTimeMillis()-linkedlist_remove));long arraylist_add=System.currentTimeMillis();array_list.add(23456,"a");System.out.println("ArrayList插入集合元素所需時間:"+(System.currentTimeMillis()-arraylist_add));long linkedlist_add=System.currentTimeMillis();linked_list.add(23456, "a");System.out.println("LinkedList插入集合元素所需時間:"+(System.currentTimeMillis()-linkedlist_add));}}
輸出結果:
使用get()方法遍曆ArrayList集合的元素所需時間:0
使用get()方法遍曆LinkedList集合的元素所需時間:1806
迭代ArrayList集合的元素所需時間:61
迭代LinkedList集合的元素所需時間:187
ArrayList刪除集合元素所需時間:10
LinkedList刪除集合元素所需時間:2
ArrayList插入集合元素所需時間:9
LinkedList插入集合元素所需時間:2
從上面的程式中可以看出:
(1)分別使用LinkedList和ArrayList來遍曆集合元素所花費的時間差別非常大,因此當我們要去遍曆List集合元素
時,使用ArrayList來遍曆效能會好很多,對於LinkedList推薦使用迭代器來遍曆集合元素。
(2)當我們需要頻繁的執行插入、刪除集合元素時,應該使用LinkedList集合,因為ArrayList集合需要經常重寫分配
內部數組的大小,其時間開銷比較大(當然這裡說的是頻繁,在實際開發中如果用的是ArrayList集合,執行插入、刪
除不是很頻繁的話,可以使用ArrayList)。
轉載請註明出處:http://blog.csdn.net/hai_qing_xu_kong/article/details/44136165 情緒控_