배열 원소의 길이

이윤설·2024년 2월 5일

제출 코드

class Solution {
    public int[] solution(String[] strlist) {
        int[] answer = new int[strlist.length];

        for (int i = 0; i < strlist.length; i++) {
            int length = strlist[i].length();
            answer[i] = length;
        }
        return answer;
    }
}

다 좋은데 answer를 선언하는 부분에서 막혔었다.
int[] answer = {}; 로 선언하면 ArrayIndexOutOfBoundsException이 발생하기 때문이다. 배열의 크기를 0으로 선언하면 해당 배열은 비어있기 때문에 어떤 인덱스에도 접근할 수 없다.

모범답안

import java.util.Arrays;

class Solution {
    public int[] solution(String[] strList) {
        return Arrays.stream(strList).mapToInt(String::length).toArray();
    }
}

스트림을 사용하니까 코드가 훨씬 간결해졌다.
하나씩 분석해보자.

모범답안 분석

  • Arrays.stream(strList): strList 배열을 스트림으로 변환하라.
  • .mapToInt(String::length): 각 문자열의 길이를 매핑하여 IntStream을 생성하라
  • .toArray(): IntStream을 int 배열로 변환하여 반환하라

정리

1) 배열을 선언할 때 값을 넣거나 크기를 선언하는 절차를 잊지말자.

profile
화려한 외면이 아닌 단단한 내면

0개의 댓글