错误:通用数组创建 [英] Error: Generic Array Creation
问题描述
我不明白通用数组创建的错误.
首先,我尝试了以下操作:
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
工具完成,退出代码 1
Tool completed with exit code 1
推荐答案
您不能创建具有通用组件类型的数组.
You can't create arrays with a generic component type.
改为创建一个显式类型的数组,例如 Object[]
.如果需要,您可以将其转换为 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
之类的集合而不是数组.
If you want type safety, use a collection like java.util.List<PCB>
instead of an array.
顺便说一下,如果 list
已经是 java.util.List
,你应该使用它的 toArray()
方法之一,而不是在您的代码中复制它们.但这并不能解决您的类型安全问题.
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屋!