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

北战南征 提交于 2019-12-01 03:47:53

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()]);

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!