그거/Java

구분자로 되어 있는 문자열을 List 로 넣는 방법

뽀기 2011. 3. 16. 13:47

1. 문자열을 배열로 만든 후 for 문을 이용해서 List 에 add 하는 방법
2. Arrays.asList() 를 이용하는 방법

1번 예제 코드
  String str = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
  ArrayList<String> list = new ArrayList<String>();  
  String [] toColumnNm = str.split(",");
  for( int i = 0; i < toColumnNm.length; i++ ) {
   list.add(toColumnNm[i]);
  }

2번 예제 코드
String str = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
List<String> obj = Arrays.asList(str.split(","));

2번이 확실히 깔끔함.

그렇다면, 성능 비교.

성능 비교용 테스트 코드
public class ArrayToListTest {
 public static void main(String[] args) {
  StopWatch watch = new StopWatch();

  // 1번 방법 100만번 호출
  for(int i = 0 ; i < 1000000 ; i++) {
   doIt("1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
  }
  // 소요 시간 출력
  System.out.println(watch.getDuration());

  // 2번 방법 100만번 호출
  for(int i = 0 ; i < 1000000 ; i++) {
   doIt2("1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
  }
  // 소요 시간 출력
  System.out.println(watch.getDuration());
 }

 // 1번 방법
 public static void doIt(String str) {
  ArrayList<String> list = new ArrayList<String>();  
  String [] toColumnNm = str.split(",");
  for( int i = 0; i < toColumnNm.length; i++ ) {
   list.add(toColumnNm[i]);
  }
 }
 
 // 2번 방법
 public static void doIt2(String str) {
  List<String> obj = Arrays.asList(str.split(","));
 }
}

결과
2829
2625

2번이 쪼끔 빠르다.

끝.