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();
}
}
스트림을 사용하니까 코드가 훨씬 간결해졌다.
하나씩 분석해보자.
1) 배열을 선언할 때 값을 넣거나 크기를 선언하는 절차를 잊지말자.