2013년 7월 26일 금요일

Arrays 클래스를 이용한 리스트 만들기 001

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/*
 * Array를 List로 만들 때 흔히 Arrays.asList( .. )를 사용했었는데
 * 여기에는 큰 단점(?) 이 있다.
 * 이렇게 만들어지는 List는 흔히 unmodifiable이라 하여 remove 및 add를
 * 할 수 가 없다.
 * 해서 사용되는 다른 대안이 있는데
 * 1번은 remove/add에 이 같은 Exception이 발생하고
 * 2번은 reference가 그대로 전해지는 스타일이고
 * 3번은 copy이기 때문에 reference는 없어지지만 불필요하게 2개
 * 생성되는 케이스가 될 수 있다.
 */
public class ArraysTest014 {
public static void main(String[] args) {

String[] strArrays = { "a", "b", "c", "d", "f", "g", "h", "i" };

// 1
List<String> strList1 = Arrays.asList(strArrays);

// 2
List<String> strList2 = new ArrayList<String>();
Collections.addAll(strList2, strArrays);

// 3
List<String> strList3 = new ArrayList<String>(Arrays.asList(strArrays));

System.out.println(strList3.remove(0));
}
}

댓글 없음:

댓글 쓰기