자바에서는 적은 요소를 포함하는 리스트를 어떻게 만들까?
친구 이름을 포함하는 그룹을 만드는 예제
List<String> friends = new ArrayList<>();
friends.add("Raphael");
friends.add("Olivia");
friends.add("Thibaut");
Arrays.asList()
팩토리 메서드를 이용해 코드를 간단히 줄이기
List<String> friends = Arrays.asList("Raphael", "Olivia", "Thibaut");
UnsupportedOperationException
발생!내부적으로 고정된 크기의 변환할 수 있는 배열로 구현되었기 때문에 발생하는 예외아다.
리스트를 인수로 받는 HashSet 생성자를 사용하기!
Set<String> friends
= new HashSet<>(Arrays.asList("Raphael", "Olivia", "Thibaut"));
스트림 API 이용하기
Set<String> friends
= Stream.of("Raphael", "Olivia", "Thibaut")
.collect(Collectors.toSet());
두 방법 모두 매끄럽지 못하며, 내부적으로 불필요한 객체 할당을 필요로 한다!
→ Java 9에서 제공하는 리스트, 집합, 맵을 쉽게 만들 수 있도록 팩토리 메서드를 알아보자.
*List.of
팩토리 메소드를 이용하면 간단하게 리스트를 만들 수 있다!*
예제 코드
List<String> friends = List.of("Raphael", "Olivia", "Thibaut");
System.out.println(friends); // [Raphael, Olivia, Thibaut]
UnsupportedOperationException
가 발생한다.
List.of
는 변경할 수 없는 리스트를 만들어내기 때문!