Sobes.tech
Junior — Middle+

Converting List<T> to array T[] with type guarantee

livecode

Task condition

Implement the convert method which:

  1. Accepts a Class<T> object – the class of the elements of the future array.
  2. Accepts a List<T> – a set of values to be placed in the array.
  3. Returns a T[] array containing the same elements as the list.
  4. Ensures the array element type matches the passed class.
  5. 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;
    }
}