Java 中列表类的 toArray - 为什么我不能将“整数”列表转换为“整数”列表?到“整数”大批?

发布于 2024-12-02 21:41:55 字数 817 浏览 7 评论 0原文

我定义了 List; stack = new ArrayList();

当我尝试通过以下方式将其转换为数组时:

Integer[] array= stack.toArray();

我收到此异常:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from Object[] to Integer[].

为什么?它是完全相同的类型——整数到整数。这不像在这种一般情况下,类是 父子关系

我尝试进行转换:

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

但在这里我收到此错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

问题是什么?

I defined List<Integer> stack = new ArrayList<Integer>();

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

Integer[] array= stack.toArray();

I get this exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from Object[] to Integer[].

Why? It is exactly the same type- Integer to Integer. It's not like in this generic case when the classes are father-and-son relation

I tried to do casting:

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

But here I get this error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

What is the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无风消散 2024-12-09 21:41:55

由于类型擦除,ArrayList在运行时不知道它的泛型类型,因此它只能给你最通用的Object[]。您需要使用 另一个 toArray 方法 它允许您指定所需的数组类型。

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

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()]);
淑女气质 2024-12-09 21:41:55

这样做的方法是这样的:

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

根据记录,您的代码无法编译的原因不仅仅是类型擦除。问题是 List.toArray() 返回一个 Object[] 并且它在引入泛型之前就已经这样做了。

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.

屋顶上的小猫咪 2024-12-09 21:41:55

这样做:

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

我们需要将“种子”数组作为参数传递给 toArray 方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文