簡體   English   中英

為什么ArrayList比java中的HashSet更快?

[英]Why ArrayList is faster than HashSet in java?

我曾經認為HashSet是一個非常快速的數據結構實現,因為它使用了哈希(並且反過來通過HashMap實現)。 我正在解決一些問題並決定檢查性能問題,所以這里是:

給你一個帶數字的數組 - [11,3,11,11,3,2,0,-2,2]你應該編寫一個函數來返回出現“奇數”次數的數字。

這是我的解決方案:

public class OddNumInArray {

public static List<Integer> oddNumList(int [] ar){
    Collection <Integer> l = new ArrayList<>();
    for (int n: ar) {
        if (l.contains(n)) {
            l.remove(n);
        }
        else {
            l.add(n);
        }
    }
    return (List) l;
}

public static Set<Integer> oddNumHSet(int [] ar){
    Set <Integer> l = new HashSet<>();
    for (int n: ar) {
        if (l.contains(n)) {
            l.remove(n);
        }
        else {
            l.add(n);
        }
    }
    return l;
}

public static void main(String [ ]arg) {
    int [] a1 = new int [10000000];
    for (int i=0; i<10; i++){
        a1[i]=(new Random()).nextInt(5);
    }
    long cur= System.nanoTime();
    System.out.println(oddNumList(a1));
    long c1 = System.nanoTime()-cur;
    System.out.println("TIME CONSUMED:" +c1);
    cur= System.nanoTime();
    System.out.println(oddNumHSet(a1));
    long c2 = System.nanoTime()-cur;
    System.out.println("TIME CONSUMED:" + c2);
    System.out.println("c1/c2*100: "+ (new Double(c1)/new Double(c2)*100));
}

}

這是一個輸出:

[1, 0]
TIME CONSUMED:101804000
[0, 1]
TIME CONSUMED:183261000
c1/c2*100: 55.55137208680516

那么,為什么使用ArrayList的實現比使用HashSet的實現快幾乎2倍? 謝謝。

ArrayList沒有用於檢查重復項的 代碼 因此,它只是添加元素以及如何嘗試添加元素。 另一方面, HashSet具有唯一元素,因此它會進行檢查以防止插入重復元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM