java List

cornpip·2023년 5월 26일
0

자바

목록 보기
3/19

List

List<Integer> list = Arrays.asList(new Integer[] {1,2,3});
List<int[]> list2 = Arrays.asList(new int[]{1, 2, 3});

Stream.of랑 비슷한 느낌으로 원시 타입은 배열을 그대로 가져간다.

List<Integer> a1 = Arrays.asList(1,2,3);
List<Integer> a2 = List.of(1,2,3);
a1.add(4); //UnsupportedOperationException
a2.add(4); //UnsupportedOperationException

//아래처럼 작성하자.
List<Integer> a = new ArrayList<>(Arrays.asList(1,2,3));
a.add(4);

둘 다 Immutable List 를 생성하고 요소를 추가하면 Exception을 던진다.
컴파일 에러는 아니므로 작성에 주의하자.

2차 배열

    public static void main(String[] args) {
        List<List<Integer>> a = new ArrayList<>();
        int num = 0;
        for(int i=0; i<5; i++){
            a.add(new ArrayList<>(Arrays.asList(num++, num++, num++)));
        }
        System.out.println(a);
    }

2차 배열도 안까지 List로 하자.
배열로 문제를 접근하겠다하면 List를 기본으로 생각하는게 편할 듯 하다.

profile
https://cornpip.tistory.com 티스토리로 이전했습니다!

0개의 댓글