List.of 메서드
List.of() 데모
1. 소개
이 문서는 Java 9 이상에서 제공되는 List.of() 메서드를 사용하여 간단하고 명확하게 리스트 개체를 생성하는 방법을 설명합니다. List.of()는 불변(immutable) 리스트를 생성하며, 데이터 초기화나 단순 조회 목적의 리스트 구성에 적합합니다.
2. 따라하기
다음 예제는 List.of()를 사용하여 문자열 목록을 생성하고 출력하는 방법을 보여줍니다.
ListOfDemo.java
public class ListOfDemo {
public static void main(String[] args) {
System.out.println("=== 기존 방식으로 List 생성하기 ===");
java.util.List<String> oldList = new java.util.ArrayList<>();
oldList.add("Apple");
oldList.add("Blueberry");
oldList.add("Pumpkin");
System.out.println(oldList);
System.out.println();
System.out.println("=== List.of() 메서드로 List 생성하기 ===");
java.util.List<String> newList = java.util.List.of(
"Apple", "Blueberry", "Pumpkin"
);
System.out.println(newList);
}
}
3. 결과
=== 기존 방식으로 List 생성하기 ===
[Apple, Blueberry, Pumpkin]
=== List.of() 메서드로 List 생성하기 ===
[Apple, Blueberry, Pumpkin]
4. 마무리
List.of()는 짧은 코드로 리스트를 생성하는 데 유용한 메서드입니다.- 반환된 리스트는 불변이므로 수정할 수 없습니다.
- Java 9 이상에서 사용할 수 있습니다.
추천 자료: ASP.NET Core 인증 및 권한 부여
추천 자료: .NET Blazor에 대해 알아보시겠어요? .NET Blazor 알아보기를 확인해보세요!