[java] List.toArray()

한지개·2023년 1월 17일

java

목록 보기
3/9

List.toArray()

리턴 타입메서드내용
Object[]toArray()List의 모든 요소를 포함하는 배열 리턴

사용 예시

	public static void main(String[] args) {
    	List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        
        // 1
        String[] str1 = list.toArray();
        
        // 2
        String[] str2 = list.toArray(new String[0]);
        
        // 3
        String[] str2 = list.toArray(new String[5]);
    }

// 1

  • 오류

// 2

  • str2.length == 3
  • str2의 크기는 3이다.
  • List의 크기(3)가 인자로 넘어가는 배열 객체의 크기(0)보다 클 경우, List의 크기로 배열이 만들어진다.(List.size() > 0)
  • 즉, List의 크기가 3이고, 인자로 넘어가는 배열의 크기가 0이므로, List의 크기로 배열이 생성된다.

// 3

  • str3.length == 5
  • str3의 크기는 5이다.
  • List의 크기(3)가 인자로 넘어가는 배열 객체의 크기(5)보다 작을 경우, 인자로 넘어가는 배열의 크기로 배열이 만들어진다. (List.size() < 5)
  • 즉, List의 크기가 3이고, 인자로 넘어가는 배열의 크기가 5이므로, 인자로 넘어가는 배열의 크기로 배열이 생성된다.

List를 기본 타입 배열로 변환

	public static void main(String[] args) {
    	List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        
        // 1
        int[] int1 = new int[list.size()];
        for(int i = 0; i<list.size(); i++){
        	int1[i] = list.get(i).intValue();
        }
        
        // 2
        int[] int2 = list.stream()
        			 .mapToInt(i -> i)
                     .toArray();
        
        // 3
        int[] int3 = list.stream()
        			 .mapToInt(Integer::intValue)
                     .toArray();
                     
        // 4
        int[] int4 = list.stream()
        			 .filter(i -> i != null)
                     .mapToInt(i -> i)
                     .toArray();
    }

// 1

  • 반복문을 통해 각 요소에 접근하여 intValue() 메서드를 사용해 int형으로 만든 후 배열에 넣은 형식이다.

// 2, 3

  • list를 스트림으로 변환 후, map을 이용해서 intStream을 가져오고, 그 후에 toArray()를 통해 배열로 만드는 형식이다.
  • // 2는 .mapToInt(i -> i) 자동으로 각 요소의 Integer 요소를 int형으로 언박싱 해준다.
  • // 3는 .mapToInt(Integer::intValue) intValue 메서드를 통해 각 요소를 int형으로 변경해준다.

// 4

  • //2에 .filter(i -> i != null) 를 추가하여 리스트의 null을 걸러내는 방법이다.

profile
평생 소원이 누룽지

0개의 댓글