[英]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.