EnumSet.copyOf 空集合抛出 IllegalArgumentException

5 java java-8

我有以下代码因 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
}
Run Code Online (Sandbox Code Playgroud)

如果 test 为 null ,则get函数的第 2 行创建空的 Test 数组和EnumSet.copyOf(get(test)) throws IllegalArgumentException

我不明白为什么会抛出这个异常?

eri*_*son 7

AnEnumSet使用一些反射来识别其元素的类型。(该组使用“序数”的的enum值,以跟踪每个元素是否包含或没有。)

创建EnumSetwith 时copyOf(Collection),它会检查集合是否为EnumSet. 如果是,则使用与源集相同的类型。否则,它会尝试调用getClass()源集合中的第一个元素。如果集合为空,则没有第一个元素,也没有可查询其类的内容。所以在这种情况下它会失败(“IllegalArgumentException如果c不是EnumSet实例并且不包含任何元素,则抛出”)。

要创建一个空的EnumSet,您需要自己确定类,并使用noneOf().

Collection<Test> tests = get(test);
return tests.isEmpty() ? EnumSet.noneOf(Test.class) : EnumSet.copyOf(tests);
Run Code Online (Sandbox Code Playgroud)