[Testdome] Merge Names

whitehousechef·2023년 12월 5일

easy peezy its just a basic set question

but set.toArray(new String[0]) what is this new String? Since array needs to be initialised with a predefined length, if we dont know the length we just create emtpy array of String.

import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class MergeNames {
    
    public static String[] uniqueNames(String[] names1, String[] names2) {
        Set<String> set1= new HashSet<>(Arrays.asList(names1));
        for(String name:names2){
            set1.add(name);
        }
        return set1.toArray(new String[0]);
    }
    
    public static void main(String[] args) {
        String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
        String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
        System.out.println(String.join(", ", MergeNames.uniqueNames(names1, names2))); // should print Ava, Emma, Olivia, Sophia
    }
}

0개의 댓글