티스토리 뷰

728x90

List vs Set

List 와 Set은 크게 Ordered collection vs Unordered collection / 중복 가능 여부로 나누어 볼수 있다.

그 이유는 List는 순서가 있는 Collection이다. List에 데이터를 넣는 순서가 보장되며, 그렇기 때문에 index로 특정 아이템을 가져올 수 있다. 또한 데이터 중복이 가능하다.

Set는 순서를 보장하지 않는 Collection이다. 그렇기 때문에 index로 특정 아이템을 가져올 수 없다. 또한 데이터 중복이 불가능하다.

 

List

- 입력 순서를 유지하며, 데이터의 중복을 허용

- 인덱스를 통해 저장 데이터에 접근이 가능

 

Set

- 입력 순서를 유지하지 않으며데이터의 중복 허용하지 않음

- 데이터에 null 입력 가능하나, 한 번만 저장하고 중복 저장을 허용하지 않음

- 인덱스가 따로 존재하지 않기 때문에 Iterator를 사용하여 조회

 

List<String> list = new ArrayList<>();
list.add("banana");
list.add("apple");
list.add("watermelon");
list.add("grape");

System.out.println(list); -> [banana, apple, watermelon, grape]

HashSet<String> set = new HashSet<>();
set.add("banana");
set.add("apple");
set.add("watermelon");
set.add("grape");

System.out.println(set); -> [watermelon, banana, apple, grape]

 

위의 코드에서 볼 수 있듯이 list 는 순서가 보장이 되지만, set 은 순서가 보장이 되지 않는다.

 

List<String> list = new ArrayList<>();
list.add("banana");
list.add("apple");
list.add("apple");
list.add("watermelon");
list.add("grape");
list.add("grape");

System.out.println(list); -> [banana, apple, apple, watermelon, grape, grape]

HashSet<String> set = new HashSet<>();
set.add("banana");
set.add("apple");
set.add("apple");
set.add("watermelon");
set.add("grape");
set.add("grape");

System.out.println(set); -> [banana, apple, watermelon, grape]

 

위의 코드에서 볼 수 있듯이 list 는 중복이 가능하여 apple, grape 가 중복되서 들어간 것을 볼수 있는 반면, set 은 중복이 불가능하여 apple, grape  한개씩 들어간 것을 볼 수 있다.

 

 

 

 

Reference Link

https://living-only-today.tistory.com/233

https://hahahoho5915.tistory.com/35

 

728x90