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

前端 未结 3 1129
被撕碎了的回忆
被撕碎了的回忆 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: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()]);
    

提交回复
热议问题