HashSet vs. TreeSet vs. LinkedHashSet

Set集合不包含重複的元素,這是使用Set的主要緣由。有三種常見的Set實現——HashSet, TreeSet和LinkedHashSet。何時使用它們,使用哪一個是個重要的問題。整體而言,若是你須要一個訪問快速的Set,你應該使用HashSet;當你須要一個排序的Set,你應該使用TreeSet;當你須要記錄下插入時的順序時,你應該使用LinedHashSet。 html

1. Set接口

Set接口繼承了Collection接口。Set集合中不能包含重複的元素,每一個元素必須是惟一的。你只需將元素加入set中,重複的元素會自動移除。 java

2. HashSet vs. TreeSet vs. LinkedHashSet

HashSet是採用hash表來實現的。其中的元素沒有按順序排列,add()、remove()以及contains()等方法都是複雜度爲O(1)的方法。 git

TreeSet是採用樹結構實現(紅黑樹算法)。元素是按順序進行排列,可是add()、remove()以及contains()等方法都是複雜度爲O(log (n))的方法。它還提供了一些方法來處理排序的set,如first(), last(), headSet(), tailSet()等等。 github

LinkedHashSet介於HashSet和TreeSet之間。它也是一個hash表,可是同時維護了一個雙鏈表來記錄插入的順序。基本方法的複雜度爲O(1)。 算法

3. TreeSet的例子

1
2
3
4
5
6
7
8
9
10
11
TreeSet tree =newTreeSet();
tree.add(12);
tree.add(63);
tree.add(34);
tree.add(45);
 
Iterator iterator = tree.iterator();
System.out.print("Tree set data: ");
while(iterator.hasNext()) {
    System.out.print(iterator.next() +" ");
}

輸出以下: dom

1
Tree set data: 12 34 45 63

如今讓咱們定義一個Dog類: ide

1
2
3
4
5
6
7
8
9
10
11
classDog {
    intsize;
 
    publicDog(ints) {
        size = s;
    }
 
    publicString toString() {
        returnsize +"";
    }
}

咱們將「dog」添加到TreeSet中: 性能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
importjava.util.Iterator;
importjava.util.TreeSet;
 
publicclassTestTreeSet {
    publicstaticvoidmain(String[] args) {
        TreeSet dset =newTreeSet();
        dset.add(newDog(2));
        dset.add(newDog(1));
        dset.add(newDog(3));
 
        Iterator iterator = dset.iterator();
 
        while(iterator.hasNext()) {
            System.out.print(iterator.next() +" ");
        }
    }
}

編譯正常,可是運行時出錯: 測試

1
2
3
4

Exception in thread "main" java.lang.ClassCastException:  spa

collection.Dog cannot be cast to java.lang.Comparable

    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)
    at collection.TestTreeSet.main(TestTreeSet.java:22)

由於TreeSet是有序的,Dog類必須實現java.lang.Comparable的compareTo()方法才行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classDogimplementsComparable{
    intsize;
 
    publicDog(ints) {
        size = s;
    }
 
    publicString toString() {
        returnsize +"";
    }
 
    @Override
    publicintcompareTo(Dog o) {
            returnsize - o.size;
    }
}

輸出:

1
1 2 3

4. HashSet的例子

1
2
3
4
5
6
7
8
9
10
HashSet dset =newHashSet();
dset.add(newDog(2));
dset.add(newDog(1));
dset.add(newDog(3));
dset.add(newDog(5));
dset.add(newDog(4));
Iterator iterator = dset.iterator();
while(iterator.hasNext()) {
    System.out.print(iterator.next() +" ");
}

輸出:

1
5 3 2 1 4

注意輸出順序是不肯定的。

5. LinkedHashSet的例子

1
2
3
4
5
6
7
8
9
10
LinkedHashSet dset =newLinkedHashSet();
dset.add(newDog(2));
dset.add(newDog(1));
dset.add(newDog(3));
dset.add(newDog(5));
dset.add(newDog(4));
Iterator iterator = dset.iterator();
while(iterator.hasNext()) {
    System.out.print(iterator.next() +" ");
}

輸出的順序時肯定的,就是插入的順序。

1
2 1 3 5 4

6. 性能測試

下面的代碼測試了以上三個類的add()方法的性能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
publicstaticvoidmain(String[] args) {
 
    Random r =newRandom();
 
    HashSet<Dog> hashSet =newHashSet<Dog>();
    TreeSet<Dog> treeSet =newTreeSet<Dog>();
    LinkedHashSet<Dog> linkedSet =newLinkedHashSet<Dog>();
 
    // start time
    longstartTime = System.nanoTime();
 
    for(inti =0; i <1000; i++) {
        intx = r.nextInt(1000-10) +10;
        hashSet.add(newDog(x));
    }
    // end time
    longendTime = System.nanoTime();
    longduration = endTime - startTime;
    System.out.println("HashSet: "+ duration);
 
    // start time
    startTime = System.nanoTime();
    for(inti =0; i <1000; i++) {
        intx = r.nextInt(1000-10) +10;
        treeSet.add(newDog(x));
    }
    // end time
    endTime = System.nanoTime();
    duration = endTime - startTime;
    System.out.println("TreeSet: "+ duration);
 
    // start time
    startTime = System.nanoTime();
    for(inti =0; i <1000; i++) {
        intx = r.nextInt(1000-10) +10;
        linkedSet.add(newDog(x));
    }
    // end time
    endTime = System.nanoTime();
    duration = endTime - startTime;
    System.out.println("LinkedHashSet: "+ duration);
 
}

從輸出看來,HashSet是最快的:

1
2
3
HashSet: 2244768
TreeSet: 3549314
LinkedHashSet: 2263320

*這個測試並非很是精確,但足以反映基本的狀況。

相關文章
相關標籤/搜索