Array 와 ArrayList 사이의 변환


1. Array -> ArrayList 변환시 유의할 점

 - Arrays.asList() 를 사용한다.

 - 하지만 Arrays.asList() 의 리턴형은 fixed-size의 List이므로 add()를 사용할 수 없다.(get(), set(), contains()는 사용가능) 

 - 리턴되는 객체가 java.util.ArrayList가 아니라 java.util.Arrays.ArrayList 이기 때문이다.

 - 그러므로 다음 예시처럼 사용해야 한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Test01 {
    public static void main(String[] args) {
        
        String strArr[] = {"가","나","다"};
        ArrayList<String> strArrayList = new ArrayList<String>();

        // 1. Array -> ArrayList
        strArrayList = new ArrayList<String>(Arrays.asList(strArr));
        System.out.println(strArrayList);
        
        // 2. ArrayList -> Array
        String strArr2[] = strArrayList.toArray(new String[strArrayList.size()]);
        for(int i=0;i<strArr2.length;i++){
            System.out.print(strArr2[i] + " ");
        }
        
    }
}
cs


'개발 > JAVA' 카테고리의 다른 글

LocalDateTime, ZonedDateTime  (0) 2019.10.11
Collections를 이용한 정렬(sort method) 활용  (0) 2017.05.09
BigDecimal & BigInteger  (0) 2017.04.18
9. 생성자와 가비지 컬렉션  (0) 2017.02.22
8. 인터페이스와 추상 클래스  (0) 2017.02.21

+ Recent posts