자바) List
자바) List
이 글은 Tistory에서 이전된 포스팅입니다. 원본은 여기에서 확인할 수 있습니다.
List
1
2
List<Integer> list = Arrays.asList(new Integer[] {1,2,3});
List<int[]> list2 = Arrays.asList(new int[]{1, 2, 3});
Stream.of랑 비슷한 느낌으로 원시 타입은 배열을 그대로 가져간다.
1
2
3
4
5
6
7
8
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차 배열
1
2
3
4
5
6
7
8
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를 기본으로 생각하는게 편할 듯 하다.
이 기사는 저작권자의 CC BY-NC 4.0 라이센스를 따릅니다.