以下是示例代码:
Set<Integer> hashSet = new HashSet<>();
Set<Integer> linkedHashSet = new HashSet<>();
for(int i = 0; i < 1000; i++){
hashSet.add(i);
linkedHashSet.add(i);
}
Long startTimeHashSet = System.nanoTime();
for(Integer i: hashSet){
}
Long endTimeHashSet = System.nanoTime();
System.out.println("HashSet Time:" + (endTimeHashSet - startTimeHashSet));
Long startTimeLinkedHashSet = System.nanoTime();
for(Integer i: linkedHashSet){
}
Long endTimeLinkedHashSet = System.nanoTime();
System.out.println("Linked HashSet Time:" + (endTimeLinkedHashSet - startTimeLinkedHashSet));
输出结果为:
HashSet Time:721774
Linked HashSet Time:132613
为什么会这样?