EnumSet.copyOf 空集合抛出 IllegalArgumentException

我有以下代码失败并出现 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)) throws IllegalArgumentException


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


青春有我
浏览 70回答 1
1回答

慕少森

AnEnumSet使用一些反射来识别其元素的类型。(该集合使用值的“序数”来enum跟踪是否包含每个元素。)当您创建一个EnumSetwith 时copyOf(Collection),它会检查该集合是否是一个EnumSet.&nbsp;如果是,它使用与源集相同的类型。否则,它会尝试调用getClass()源集合中的第一个元素。如果集合为空,则没有第一个元素,也没有任何可查询的类。所以在这种情况下它会失败(“IllegalArgumentException如果c不是EnumSet实例并且不包含元素则抛出”)。要创建一个空的EnumSet,您需要自己确定类,并使用noneOf().Collection<Test>&nbsp;tests&nbsp;=&nbsp;get(test); return&nbsp;tests.isEmpty()&nbsp;?&nbsp;EnumSet.noneOf(Test.class)&nbsp;:&nbsp;EnumSet.copyOf(tests);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java