List class's toArray in Java- Why can't I convert a list of “Integer” to an “Integer” array?

前端 未结 3 1128
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 07:15

I defined List stack = new ArrayList();

When I\'m trying to convert it to an array in the following way:

         


        
相关标签:
3条回答
  • 2021-01-12 07:31

    The way to do it is this:

    Integer[] array = stack.toArray(new Integer[stack.size()]);
    

    For the record, the reason that your code doesn't compile is not just type erasure. The problem is that List<T>.toArray() returns an Object[] and it has done this before generics were introduced.

    0 讨论(0)
  • 2021-01-12 07:33

    Because of type erasure, the ArrayList does not know its generic type at runtime, so it can only give you the most general Object[]. You need to use the other toArray method which allows you to specify the type of the array that you want.

    Integer[] array= stack.toArray(new Integer[stack.size()]);
    
    0 讨论(0)
  • 2021-01-12 07:51

    Do this instead:

    Integer[] array = stack.toArray(new Integer[stack.size()]);
    

    We need to pass the "seed" array as an argument to the toArray method.

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