Lur*_*ron 34 java arrays generics class object
我不明白通用阵列创建的错误.
首先我尝试了以下内容:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试这样做:
PCB[] res = new PCB[100];
Run Code Online (Sandbox Code Playgroud)
我必须遗漏一些似乎正确的事情.我试着查一下,我真的做到了.没有任何东西在点击.
我的问题是:我该怎么做才能解决这个问题?
错误是:
.\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
Run Code Online (Sandbox Code Playgroud)
工具已完成,退出代码为1
eri*_*son 40
您无法使用通用组件类型创建数组.
创建一个显式类型的数组,例如Object[].PCB[]如果需要,您可以将其转换为,但在大多数情况下我不建议使用它.
PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */
Run Code Online (Sandbox Code Playgroud)
如果您想要类型安全,请使用类似集合java.util.List<PCB>而不是数组.
顺便说一句,如果list已经是a java.util.List,你应该使用它的toArray()一种方法,而不是在你的代码中复制它们.但这并不能解决类型安全问题.
下面将为您提供所需类型的数组,同时保持类型安全。
PCB[] getAll(Class<PCB[]> arrayType) {
PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
list.clear();
return res;
}
Run Code Online (Sandbox Code Playgroud)
在我对 Kirk Woll 链接为副本的问题的回答中深入解释了这是如何工作的。