我有以下代码因 IllegalArgumentException 而失败
public EnumSet<test> getData(){ // Line 1
return EnumSet.copyOf(get(test))) // Line 2
}
private Collection<Test> get(Test[] test){ //Line 1
test= test==null ? new Test[0] : test; // line 2
return Array.asList(test) //Line 3
}
如果 test 为 null ,则 get 的第 2 行 函数创建空的 Test 数组
和 EnumSet.copyOf(get(test)) 抛出 IllegalArgumentException
我不明白为什么抛出这个异常?
最佳答案
EnumSet
使用一些反射来识别其元素的类型。 (该集合使用 enum
值的 "ordinal" 来跟踪是否包含每个元素。)
当您使用 copyOf(Collection)
创建一个 EnumSet
时,它会检查该集合是否是一个 EnumSet
。如果是,它使用与源集相同的类型。否则,它会尝试对源集合中的第一个元素调用 getClass()
。如果集合为空,则没有第一个元素,也没有可查询其类的内容。所以在这种情况下它会失败(“如果 c
不是 EnumSet
实例并且不包含任何元素,则抛出 IllegalArgumentException
”)。
要创建一个空的EnumSet
,您需要自己确定类,并使用noneOf()
.。
Collection<Test> tests = get(test);
return tests.isEmpty() ? EnumSet.noneOf(Test.class) : EnumSet.copyOf(tests);
关于java - EnumSet.copyOf 空集合抛出 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924784/