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

前端 未结 3 1127
被撕碎了的回忆
被撕碎了的回忆 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.toArray() returns an Object[] and it has done this before generics were introduced.

提交回复
热议问题