차근차근/JAVA JSP

Arrays.asList의 UnsupportedOperationException

예쁜꽃이피었으면 2014. 11. 11. 11:05

http://stewie38.tistory.com/89


Array를 List로 만들 때 흔히 Arrays.asList( .. )를 사용했었는데 여기에는 큰 단점(?) 이 있다.

이렇게 만들어지는 List는 흔히 unmodifiable이라 하여 remove 및 add를 할 수 가 없다.

해서 사용되는 다른 대안이 있는데


1번은 remove/add에 이 같은 Exception이 발생하고

2번은 reference가 그대로 전해지는 스타일이고

3번은 copy이기 때문에 reference는 없어지지만 불필요하게 2개 생성되는 케이스가 될 수 있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
public class ArraysTest {
    public static void main(String[] args) {
        String[] strArrays = {"a", "b", "c", "d", "f", "g", "h", "i"};
        // 1
        List<string> strList = Arrays.asList(strArrays);
        // 2
        List<string> strList = new ArrayList<string>();
        Collections.addAll(strList, strArrays);
        // 3
        List<string> strList = new ArrayList<string>(Arrays.asList(strArrays));
        System.out.println(strList.remove(0));
    }
}</string></string></string></string></string>


반응형