본문 바로가기
개발/Java

[Java] Arrays.asList / 특징 / 배열을 List 컬렉션으로 바꾸기

by Allonsy 2022. 4. 13.
반응형

자바 컬렉션에는 유용한 API들이 많이 있다

배열을 사용하는 것보다 자바 컬렉션 API를 사용하는 것이 편할 때 배열을 List로 변경해서 사용하면 편리하다

1. 예제 코드(배열->List)

String[] stringArr = {"A","B","C"};

List<String> stringList = Arrays.asList(stringArr);

2. Arrays.asList 특징

- Arrays.asList를 이용하면 고정된 사이즈의 리스트로 반환 -> 추가,삭제 불가

new ArrayList<>() 로 새로운 리스트를 생성하면 추가, 삭제 가능

String[] stringArr = {"A","B","C"};

List<String> stringList = new ArrayList<>(Arrays.asList(stringArr));

 

- Reference Type(주소값을 가진 타입)만 인자로 받아서 리스트로 반환됨

asList는 generic 메서드이기 때문에 reference type 만을 인자로 받는다

primitive 배열을 asList로 변환하려고 할 때 배열의 요소가 리스트의 요소로 바뀌어 변환될거라고 착각할 수 있으나,

배열도 Reference Type이기 때문에 primitive 배열을 요소로 가지는 리스트가 반환된다

ex. int[] 을 asList를 이용해서 리스트로 변환하려고 할 때 List<Integer> 가 아닌 List<int[]>이 반환된다

int[] intArr = {1,2,3};

List<int[]> intArrList = Arrays.asList(intArr);
// intArrList.size() = 1
// intArrList.get(0) = {int[3]@2579} [1,2,3]

 

- 가변인수를 받음

인수를 여러개 받는다

여러 타입의 인수를 받을 수도 있지만, 그렇게 사용하지 않는 걸 권하고 싶다

자세한 내용은 이펙티브 자바책의 목차 아이템32번을 읽어보시는 걸 추천한다!

(이펙티브 자바 - 아이템 32. 제네릭과 가변인수를 함께 쓸 때는 신중하라)

// A,B,C 를 요소로 하는 리스트

String[] stringArr = {"A","B","C"};
List<String> stringList = Arrays.asList(stringArr);

List<String> variableArgumentList = Arrays.asList("A","B","C");

 

[참고] JDK 11 문서

 

@SafeVarargs public static <T> List<T> asList​(T... a)
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
 

Type Parameters:T - the class of the objects in the arrayParameters:a - the array by which the list will be backedReturns:a list view of the specified array

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html

 

Arrays (Java SE 11 & JDK 11 )

Compares two int arrays lexicographically over the specified ranges. If the two arrays, over the specified ranges, share a common prefix then the lexicographic comparison is the result of comparing two elements, as if by Integer.compare(int, int), at a rel

docs.oracle.com

 

반응형

댓글