[Java] Array, List, Set, Map 선언과 초기화
by 배부른코딩로그💡 쓸 때마다 헷갈리는 Collection들의 선언과 초기화를 동시에 해보자.
목표
- Array 및 List, Set, Map에 대한 선언과 초기화를 동시에 할 수 있다.
- 예제를 만들어 설명할 수 있다.
Array
int[] array1 = new int[] { 1, 2, 3 }; int[] array2 = { 1, 2, 3 };
두 가지 방법을 통해 선언과 초기화가 동시에 가능하다.
짧고 간결한 코드가 보기 더 좋기 때문에 아래의 방식을 주로 사용한다.
List
List<String> list1 = new ArrayList<>(Arrays.asList("1", "2", "3")); List<String> list2 = new ArrayList<>() { { add("1"); add("2"); add("3"); } };
Array를 통해 초기화 후 List로 만들어주는 방법과 List로서 선언과 초기화를 동시에 하는 방법이 존재한다.
아래의 코드가 List를 초기화한다는 것이 더 명시적이기 떄문에 이를 선호한다.
위의 방식은 선언 후 변경이 가능하다. 변경이 불가능한 immutable한 List 선언과 초기화도 가능하다.
// ① Collections.unmodifiableList method final List<Integer> list = Arrays.asList(new String[] { 1, 2, 3 }); final List<Integer> list2 = Collections.unmodifiableList( new ArrayList<>(list)); // ② Stream API List<String> alphabets = Stream .of("A", "B", "C") .collect(collectingAndThen(toList(), Collections::unmodifiableList)); // ③ List.of method (JDK 9 ↑) List<String> emptyList = List.of(); // [] final List<Integer> lastNames = List.of("KIM", "LEE", "CHOI");
일반적으로 Side Effect를 발생시키지 않게 위해 불변 컬렉션에 데이터를 담는다.
불변 컬렉션에 대해 변경을 시도하면, "UnsupportedOperationException"이 발생한다.
추가적으로, Google Guava 라이브러리도 이용할 수 있다.
Guava는 불변 리스트 생성을 단 한 줄의 코드로 만들 수 있는 빌더 클래스를 제공한다.
import com.google.common.collect.ImmutableList; List<String> fruits = ImmutableList.of("Apple", "Banana", "Cherry"); fruits.add("Lemon"); // /* [ERROR] UnsupportedOperationException ..... */
Set
Set<String> set = new HashSet<>(Arrays.asList("A", "B", "C"));
List 뿐만 아니라 Set 인터페이스에도 불편 컬랙션 생성을 위한 팩토리 메서드가 추가되었다.
// Basic Set<String> values = Collections.unmodifiableSet( new HashSet<String>(Arrays.asList("1", "2", "3"))); // List.of method (JDK 9 ↑) Set<String> fruits = Set.of("Apple", "Banana", "Cherry"); Set<String> fruits2 = Set.of("Apple", "Banana", "Cherry", "Apple"); // /* [ERROR] IllegalArgumentException */ fruits.add("NEW ONE"); // /* [ERROR] UnsupportedOperationException ..... */
Map
Map<String, String> map = new HashMap<String, String>() { { put("key1", "value1"); put("key2", "value2"); put("key3", "value3"); } };
Map 인터페이스 역시 불편 컬랙션 생성을 위한 팩토리 메서드 Map.of(...)가 추가되었다.
// Basic Map<String, String> map1 = Collections.unmodifiableMap(new HashMap<String, String>() { { put("key01", "val01"); put("key02", "val02"); put("key03", "val03"); } }); /* * JDK 9 ↑ */ Map<String, String> map2 = Map.of("key1", "value1", "key2", "value2"); map2.put("NEW_KEY", "NEW_VALUE"); // /* [ERROR] UnsupportedOperationException ..... */ Map<Integer, String> alphabets = Map.ofEntries( Map.entry(1, "A"), Map.entry(2, "B"), Map.entry(3, "C"));
번외: 빈 불편 컬렉션 생성
// JDK 5 ↑ List<String> emptyList = Collections.emptyList(); Set<String> emptySet = Collections.emptySet(); Map<String, String> emptyMap = Collections.emptyMap(); // JDK 9 ↑ List<String> emptyList = List.of(); Set<String> emptySet = Set.of(); Map<String, String> emptyMap = Map.of();
항상 더 간결하고 읽기 쉬운 코드가 유지보수 함에 좋다.
누군가에게 Collections.unmodifiable 메서드가 단어적으로 더 명시적으로 느낄 수 있지만,
Collection.of를 통해 코드를 더욱 간결하게 표현이 가능하다.
Collections.of 메서드를 애용하자!
모르면 공부하고, 배우면 된다.
Last Updated. 2021. 11. 05.
블로그의 정보
배부른코딩로그
배부른코딩로그