Junior — Middle+
Converting List<T> to array T[] with type guarantee
livecode
Task condition
Implement the convert method which:
- Accepts a
Class<T>object – the class of the elements of the future array. - Accepts a
List<T>– a set of values to be placed in the array. - Returns a
T[]array containing the same elements as the list. - Ensures the array element type matches the passed class.
- The order of elements in the resulting array can be arbitrary.
import java.util.List;
import java.lang.reflect.Array;
public class GenericArray {
public static void main(String[] args) {
String[] strings = GenericArray.convert(
String.class,
List.of("Val1", "Val2", "Val3")
);
System.out.println(java.util.Arrays.toString(strings));
}
public static <T> T[] convert(Class<T> clazz, List<T> values) {
return null;
}
}