Convert a generic list to an array

前端 未结 13 1253
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 17:13

I have searched for this, but unfortunately, I don\'t get the correct answer.

class Helper {
    public static  T[] toArray(List list) {
           


        
相关标签:
13条回答
  • 2020-12-05 17:56

    When you have a generic List<T> you will be able to know the class of the object at the runtime. Therefore, the best way to implement it is like this:

    public static <T> T[] list2Array(Class<T[]> clazz, List<T> elements)
    {
        T[] array = clazz.cast(Array.newInstance(clazz.getComponentType(), elements.size()));
        return elements.toArray(array);
    }
    

    Why do you need the Class<T[]> parameter?

    Because, we have a generic list and it will not provide the information necessary to get an array of precisely the type we are looking for, of course, while preserving type safety. As opposed to the other answers, which will either give you back an Object array or result in warnings at compile time. This approach will gives you a clean solution. The "hack" here is the clazz.cast() call, which compiles without warnings for whatever type you declare an instance of list2Array().

    Now, how can you use it?

    Simple, just call it like this:

    List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());
    String[] numbers = list2Array(String[].class, list);
    System.out.println(Arrays.toString(numbers));
    

    Here is the compiling sample of this: https://ideone.com/wcEPNI

    Why does it work?

    It works because class literals are treated by the compiler as instances of java.lang.Class. This also works for interfaces, enums, any-dimensional arrays (e.g. String[].class), primitives and the keyword void.

    Class itself is generic (declared as Class<T[]>, where T[] stands for the type that the Class object is representing), meaning that the type of String[].class is Class<String[]>.

    Note: You won't be able to get an array of primitives, since primitives can't be used for type variables.

    0 讨论(0)
提交回复
热议问题