简体   繁体   English

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

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

I used to thing that HashSet is a pretty fast data structure implementation because it uses hashes (and is implemented via HashMap in its turn). 我曾经认为HashSet是一个非常快速的数据结构实现,因为它使用了哈希(并且反过来通过HashMap实现)。 I was solving some problems and decided to check performance issue, so here it is: 我正在解决一些问题并决定检查性能问题,所以这里是:

You are given an array with numbers - [11, 3, 11, 11, 3, 2, 0, -2, 2] You are supposed to write a function that returns the number that appears "odd" number of times. 给你一个带数字的数组 - [11,3,11,11,3,2,0,-2,2]你应该编写一个函数来返回出现“奇数”次数的数字。

Here is my solution: 这是我的解决方案:

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));
}

}

And here is an output: 这是一个输出:

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

So, why is implementation with ArrayList is quicker than one with HashSet by almost 2 times? 那么,为什么使用ArrayList的实现比使用HashSet的实现快几乎2倍? Thank you. 谢谢。

ArrayList doesn't have code to check for duplicates . ArrayList没有用于检查重复项的 代码 So, it just adds elements as and how you try to add them. 因此,它只是添加元素以及如何尝试添加元素。 A HashSet on the other hand is meant to have only unique elements, so it makes a check to prevent insertion of duplicate elements. 另一方面, HashSet具有唯一元素,因此它会进行检查以防止插入重复元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM