我正在尝试使以下代码正常工作,而不会出现警告或错误。问题是,如果我保留类型通用,它会在 Eclipse 中返回警告。当我思考删除警告的代码时,我使用了显式类,并遇到了 Architecture.getValues()
必须返回 Architecture[]
的问题,而我可以'似乎没有转换它。我读到,如果我将一个空的 Architecture[]
传递给集合方法 (.toArray()
),它会填充它,但我似乎无法正确执行它,我得到由于 java.lang.NullPointerException
异常,注释行上出现运行时错误。我怎样才能做到这一点?
Main.java
//snippet
private JComboBox<Architecture> comboBox_3;
//snippet
comboBox_3.setModel(new DefaultComboBoxModel<Architecture>(Architecture.getValues(perf)));
架构.Java
public enum Architecture {
CATEGORYb, CATEGORY1, CATEGORY2, CATEGORY3, CATEGORY4;
public static Architecture[] getValues(Performance perf) {
ArrayList<Architecture> categories = new ArrayList<Architecture>();
Architecture[] empty = null;
switch (perf) {
case PLa:
categories.add(CATEGORYb);
categories.add(CATEGORY2);
break;
case PLb:
categories.add(CATEGORYb);
categories.add(CATEGORY2);
categories.add(CATEGORY3);
break;
case PLc:
categories.add(CATEGORY1);
categories.add(CATEGORY2);
categories.add(CATEGORY3);
break;
case PLd:
categories.add(CATEGORY2);
categories.add(CATEGORY3);
break;
case PLe:
categories.add(CATEGORY4);
break;
}
return categories.toArray(empty); //runtime error
}
}
性能.java
public enum Performance {
PLa, PLb, PLc, PLd, PLe;
}
最佳答案
传入的数组不仅仅提供类型。如果它足够大,那么该数组将被填充并返回。如果它不够大,则会分配、填充并返回一个相同类型的新数组。因为它是 null
,所以会抛出 NullPointerException
。 toArray
Javadocs 中描述了此行为:
If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
和
NullPointerException - if the specified array is null
无需传递 null
数组,只需初始化一个长度为列表大小的数组即可。
return categories.toArray(new Architecture[categories.size()]);
关于java - 在 Java 中将 Enum ArrayList 方法转换为 T[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35208456/