错误:通用阵列创建 [英] Error: Generic Array Creation

查看:106
本文介绍了错误:通用阵列创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白通用阵列创建的错误。结果
首先,我试过如下:结果

I don't understand the error of Generic Array Creation.
First I tried the following:

  public PCB[] getAll() {
       PCB[] res = new PCB[list.size()];
           for (int i = 0; i < res.length; i++) {
               res[i] = list.get(i);
            }
       list.clear();
       return res;
}

结果
然后我试着这样做:


Then I tried doing this:

PCB[] res = new PCB[100];

结果
我必须失去了一些东西的原因,似乎正确。我试图寻找它,我真的做到了。并没有什么点击。


I must be missing something cause that seems right. I tried looking it up I really did. And nothing is clicking.

结果
我的问题是:我能做些什么来解决这个问题。


My question is: What can I do to fix this?

结果
错误的是:结果


the error is :

.\Queue.java:26: generic array creation
PCB[] res = new PCB[200];
            ^
Note: U:\Senior Year\CS451- file      
uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

工具,退出code完成1

Tool completed with exit code 1

推荐答案

您不能创建一个通用的组件类型的数组。

You can't create arrays with a generic component type.

创建一个显式类型的数组,如对象[] 代替。然后,您可以施放此为 PCB [] 如果你想,但我不推荐它在大多数情况下。

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

如果你想要的类型安全,使用类似集合的java.util.List&LT; PCB方式&gt; 不是数组的

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

顺便说一句,如果列表已经是的java.util.List ,你应该使用一个其的toArray()方法,而不是在你的code复制它们。这不会让你周围的类型安全问题,但

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

这篇关于错误:通用阵列创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆