EnumSet.copyOf空集合引发IllegalArgumentException [英] EnumSet.copyOf empty collection throws IllegalArgumentException

查看:53
本文介绍了EnumSet.copyOf空集合引发IllegalArgumentException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码因IllegalArgumentException而失败

I have below code which fails with 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

if test is null , then line 2 of get function creates empty array of Test and EnumSet.copyOf(get(test)) throws IllegalArgumentException

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

I dont understand why this exception is thrown ?

推荐答案

EnumSet使用一些反射来标识其元素的类型. (该集合使用"ordinal" enum值来跟踪是否包含每个元素.)

An EnumSet uses some reflection to identify the type of its elements. (The set uses the "ordinal" of the enum values to track whether each element is included or not.)

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

When you create an EnumSet with copyOf(Collection), it checks to see if the collection is an EnumSet. If it is, it uses the same type as the source set. Otherwise, it attempts to call getClass() on the first element in the source collection. If the collection is empty, there is no first element, and nothing to query for its class. So it fails in that case ("throws IllegalArgumentException if c is not an EnumSet instance and contains no elements").

要创建一个空的EnumSet,您需要自己确定该类,并使用

To create an empty EnumSet, you need to determine the class yourself, and use noneOf().

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

这篇关于EnumSet.copyOf空集合引发IllegalArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆