강의 | 대외활동 | 개인플젝/TDD N CleanCode_강의
Arrays.asList 와 ArrayList 의 차이?
Sky_Developer
2018. 11. 17. 12:39
둘의 차이는 타입의 차이(List vs ArrayList) 로도 볼 수 있다.
예제로 보는 것이 더 쉬울 거 같아서 예제로 살펴본다.
List<Integer> list1, list2 = null;
Integer[] array = { 5, 7, 9 };
list1 = new ArrayList<Integer>(Arrays.asList(array));
list1.add(11);
list2 = Arrays.asList(array);
list2.add(11) // error !
와 같은 예제가 있다고 해보자
먼저 list1은 Integer 타입이고 ArrayList 타입이다.
list2는 Integer 타입이고 List 타입이다.
그럼 List 타입과 ArrayList의 차이점은 무엇인가?
간단하다.
List는 Interface 이고, ArrayList는 List Interface를 사용하는 클래스이다.
list1 은 add 라는 메소드를 사용해 인자를 대입할 수 있다.
하지만 list2는 List view로 return 되고, interface 에 붙어있는 메소드 만 사용할 수 있어 add를 사용하려고 하면 에러가 발생한다.
출처 : https://crunchify.com/difference-between-arrays-aslistarray-vs-arraylistarrays-aslistarray-in-java/