List And Set 

: Set은 검색에 목적이 있기 때문에 순서 정보를 관리할 필요가 없어 데이터 크기에 상관없이 검색에 걸리는 시간이 매우 짧다.

반면, List는 index를 관리해야 하기 때문에 시간이 오래 걸린다.

그러므로 기능적 차이가 없다면 HashSet을 써야한다.

(검색만을 위한 기능이 필요하다면 List보다는 Set을 쓰는 것이 유리하다.)

 

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
public class ListAndSet {
    public static void main(String[] args) {
        final int SIZE = 10_000_000;    
        final List<Integer> arrayList = new ArrayList<>(SIZE);
        final Set<Integer> hashSet = new HashSet<>(SIZE);
        final int data = 9_000_000;
        
      
        IntStream.range(0, SIZE).forEach(value -> {   
            arrayList.add(value);
            hashSet.add(value);  
        });        
        
        Instant start = Instant.now();
        arrayList.contains(data);
        Instant end = Instant.now();
        long time = Duration.between(start, end).toMillis();
        System.out.println("arrayList 검색시간 : "+(time/1000.0)+"초");
        
        start = Instant.now();
        hashSet.contains(data);
        end = Instant.now();
        time = Duration.between(start, end).toMillis();
        System.out.println("hashSet 검색시간 : "+(time/1000.0)+"초");
        
    }
}
 
 
 

이클립스 실행결과

위의 실행결과와 같이 arrayList 가 hashSet 보다 처리속도가 오래 걸린 것을 확인할 수 있다.