我需要从一个集合中创建一个EnumSet 。我决定使用EnumSet#copyOf方法。但是,由于此方法的限制:
the specified collection must contain at least one element (in order to determine the new enum set's element type)
我需要确保集合不为空。然后代码变为:
enum Color {RED, GREEN, BLUE};
Set<Color> set = ... // get it from somewhere
if (set.isEmpty()) {
return EnumSet.noneOf(Color.class);
else
return EnumSet.copyOf(set);
也许 javac 在确定传递给方法的集合成员的正确类型方面存在真正的限制copyOf
,但我无法克服我必须诉诸上述方法来满足空集合的感觉。这是我的问题:
究竟是什么限制,这里不能接受空集合?
像这样的方法签名
copyOf(Collection<Enum<E>>)
会解决这个问题吗?如果是,它还会产生什么其他问题?