1. 程式人生 > >ArrayList、LinkedList和Vector區別

ArrayList、LinkedList和Vector區別

最近刷面試題,做個隨筆。。。查資料看見下面這圖不錯就偷來了。
這圖不錯就偷來了

一、區別

如圖,三個實現了Java.util.List介面。

  • Vector和ArrayList底層都是Object[]儲存的動態陣列,LinkedList是基於連結串列的資料結構
  • Vector的方法都是同步的(Synchronized),而ArrayList的方法不是,因此,ArrayList的效能比Vector好
  • 當Vector或ArrayList中的元素超過它的初始大小時,Vector會將它的容量翻倍,而ArrayList只增加50%的大小,這樣,ArrayList就有利於節約記憶體空間
  • LinkedList適合增刪,ArrayList和Vector適合尾部增加和查詢

二、面試題:去除[1,100000]之間的偶數

ArrayList在刪除或新增其中的一個數據的時候,會建立一個新的ArrayList,把原來的list切開,再在新的list中拼接上,所以巨耗時,之前看到過圖片,但找不到了。。。。
這道題目我想到三種方法:
準備一個ArrayList

 public static ArrayList<Integer> preList(){
        ArrayList<Integer> arrayList=new ArrayList<>(100001);
        for(int i=1;i<100001;i++){
            arrayList.add(new
Integer(i)); } return arrayList; }

1.ArrayList+迭代器+if+remove

 public static void arrayRemove(){
        ArrayList<Integer> arrayList=preList();
        Long start=System.currentTimeMillis();
        Iterator<Integer> iterator=arrayList.iterator();
        while(iterator.hasNext()){
            Integer i=iterator.next();
            if
(i%2==0){ iterator.remove(); } } Long end=System.currentTimeMillis(); System.out.println("普通刪除消耗時間"+(end-start)); }

2.ArrayList*2+迭代器+if+add

    public static void arrayAdd(){
        ArrayList<Integer> arrayList1=new ArrayList<>();
        List<Integer> arrayList=preList();
        Long start=System.currentTimeMillis();
        Iterator<Integer> iterator=arrayList.iterator();
        while(iterator.hasNext()){
            Integer i=iterator.next();
            if(i%2!=0){
                arrayList1.add(new Integer(i));
            }

        }
        Long end=System.currentTimeMillis();

        System.out.println("第二種方法時間"+(end-start));
    }

3.LinkedList

 public static void linkedremove(){
        LinkedList<Integer> linkedList=new LinkedList<>();
        for(int i=1;i<100001;i++){
            linkedList.add(new Integer(i));
        }
        Long start=System.currentTimeMillis();
        Iterator<Integer> iterator=linkedList.iterator();
        while(iterator.hasNext()){
            Integer i=iterator.next();
            if(i%2==0){
                iterator.remove();
            }
        }
        Long end=System.currentTimeMillis();
        System.out.println("linked刪除消耗時間"+(end-start));
    }

總結:
三者時間比較3<2<1,分別是10,20,1800,經過多次測試都在這三個數字上下跳動,吊還是linkedlist吊啊。