Algorithm/Programmers

[Programmers] Lv.0 / 할 일 목록 / Java

unknownomad 2024. 1. 9. 22:17

문제

 

풀이

import java.util.*;

class Solution {
    public String[] solution(String[] todo_list, boolean[] finished) {
        
        List<String> unfinishedTasks = new ArrayList<>();
        
        for(int i = 0; i < todo_list.length; i++) {
            if(!finished[i]) {
                unfinishedTasks.add(todo_list[i]);
            }
        }
        String[] answer = unfinishedTasks.toArray(new String[0]);
        return answer;
    }
}
In Java, when using the toArray method with an argument, the argument is supposed to be a type-safe array that will be used as the destination of the elements from the collection. The size of this array is not critical because it will be replaced by a new array of the correct size if necessary.
In the case of toArray(new String[0]), the argument new String[0] is an empty array of type String. This is a common idiom used to indicate the type of the resulting array. The purpose of using an empty array is to let the toArray method create a new array of the correct type (in this case, String[]) with the correct size to accommodate the elements of the list.
So, in essence, toArray(new String[0]) is just a way of saying "convert the list of strings to a string array." The empty array is just a placeholder for the type information, and the method will create a new array with the correct size based on the number of elements in the list.
class Solution {
    public String[] solution(String[] todo_list, boolean[] finished) {
    
        String str = "";
        
        for(int i = 0; i < finished.length; i++) {
            str = finished[i] == false ? str + todo_list[i] + "," : str;
        }
        return str.split(",");
    }
}

 

출처

https://school.programmers.co.kr/learn/courses/30/lessons/181885