错误:通用数组创建
我不明白通用数组创建的错误。
首先我尝试了以下方法:
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;
}
然后我尝试这样做:
PCB[] res = new PCB[100];
我一定错过了一些看起来正确的东西。我试着查了一下,确实是这样。没有任何反应。
我的问题是:我能做些什么来解决这个问题?
错误是:
.\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
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
Tool completed with exit code 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法使用通用组件类型创建数组。
相反,创建一个显式类型的数组,例如
Object[]
。如果需要,您可以将其转换为PCB[]
,但在大多数情况下我不建议这样做。如果您想要类型安全,请使用像 java.util.List这样的集合而不是数组。
顺便说一句,如果
list
已经是java.util.List
,您应该使用它的toArray()
方法之一,而不是重复它们在你的代码中。但这并不能解决类型安全问题。You can't create arrays with a generic component type.
Create an array of an explicit type, like
Object[]
, instead. You can then cast this toPCB[]
if you want, but I don't recommend it in most cases.If you want type safety, use a collection like
java.util.List<PCB>
instead of an array.By the way, if
list
is already ajava.util.List
, you should use one of itstoArray()
methods, instead of duplicating them in your code. This doesn't get you around the type-safety problem though.下面将为您提供所需类型的数组,同时保持类型安全。
我的回答深入解释了它的工作原理柯克·沃尔作为重复项链接的问题。
The following will give you an array of the type you want while preserving type safety.
How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.
除了“可能的重复”中建议的方法之外,解决此问题的另一种主要方法是由调用者提供数组本身(或至少一个模板),调用者希望知道具体类型并且可以从而安全地创建数组。
这是
ArrayList.toArray(T[])
等方法的实现方式。我建议您看一下该方法以获取灵感。更好的是,正如其他人指出的那样,您可能应该使用该方法。Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.
This is the way methods like
ArrayList.toArray(T[])
are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.