Java/컬렉션

[Java]ArrayList 초기화 방법

DevStory 2022. 6. 20.

ArrayList 초기화 방법

이번 포스팅은 Java의 ArrayList를 초기화하는 방법을 소개합니다.


add() 메서드

add() 메서드를 사용하여 ArrayList를 초기화할 수 있습니다.

public static void main(String args[]) {
  ArrayList<String> stringArrayList = new ArrayList<>();
  stringArrayList.add("One");
  stringArrayList.add("Two");
  stringArrayList.add("Three");

  ArrayList<Integer> integerArrayList = new ArrayList<>();
  integerArrayList.add(1);
  integerArrayList.add(2);
  integerArrayList.add(3);

  System.out.println(stringArrayList);
  System.out.println(integerArrayList);
}

실행 결과

[One, Two, Three]
[1, 2, 3]

Arrays.asList() 메서드

Arrays.asList() 메서드를 ArrayList 생성자에 전달하여 값을 초기화합니다.

public static void main(String args[]) {
  ArrayList<String> stringArrayList = new ArrayList<>(
        Arrays.asList("One", "Two", "Three")
  );

  ArrayList<Integer> integerArrayList = new ArrayList<>(
        Arrays.asList(1, 2, 3)
  );

  System.out.println(stringArrayList);
  System.out.println(integerArrayList);
}

실행 결과

[One, Two, Three]
[1, 2, 3]

익명의 내부 클래스 메서드

익명의 내부 클래스 메서드를 사용하여 ArrayList를 초기화할 수 있습니다.

public static void main(String args[]) {
  ArrayList<String> stringArrayList = new ArrayList(){{
    add("One");
    add("Two");
    add("Three");
  }};

  ArrayList<Integer> integerArrayList = new ArrayList(){{
    add(1);
    add(2);
    add(3);
  }};

  System.out.println(stringArrayList);
  System.out.println(integerArrayList);
}

실행 결과

[One, Two, Three]
[1, 2, 3]

Stream API

Java 8 이상의 버전을 사용하는 경우 Stream을 사용할 수 있습니다. Stream을 사용하여 모든 종류의 Collection으로 변환할 수 있습니다.

public static void main(String args[]) {
  ArrayList<String> stringArrayList = new ArrayList<>(
        Stream.of("One", "Two", "Three")
        .collect(Collectors.toList())
  );

  ArrayList<Integer> integerArrayList = new ArrayList<>(
        Stream.of(1, 2, 3)
        .collect(Collectors.toList())
  );

  System.out.println(stringArrayList);
  System.out.println(integerArrayList);
}

실행 결과

[One, Two, Three]
[1, 2, 3]

Collections.nCopies() 메서드

Collections.nCopies() 메서드는 지정된 객체를 n개의 요소로 구성된 List 객체를 반환합니다. 지정된 객체를 n개만큼 생성해야 하는 경우 유용하게 사용할 수 있습니다.

public static void main(String args[]) {
  // "One"이라는 요소를 3개 생성
  ArrayList<String> stringArrayList = new ArrayList(
        Collections.nCopies(3, "One")
  );

  // 1이라는 요소를 5개 생성
  ArrayList<Integer> integerArrayList = new ArrayList(
        Collections.nCopies(5, 1)
  );

  System.out.println(stringArrayList);
  System.out.println(integerArrayList);
}

실행 결과

[One, One, One]
[1, 1, 1, 1, 1]

정리

  • ArrayList를 초기화하는 방법으로 add(), Arrays.asList(), 익명의 내부 클래스 메서드, Stream, Collections.nCopies()를 사용할 수 있습니다.
  • Collections.nCopies() 메서드는 지정된 객체를 n개의 요소로 구성된 List 객체를 반환합니다.
반응형

댓글