Java:EnumSet.copyOf——还有改进的余地吗? [英] Java: EnumSet.copyOf -- is there a room for improvement?
问题描述
我需要创建一个 EnumSet从一个集合.我决定使用 EnumSet#copyOf 方法.但是,由于此方法的限制:
I need to create an EnumSet from a Set. I decided to use the EnumSet#copyOf method. However, because of a restriction on this method:
the specified collection must contain at least one element (in order to determine the new enum set's element type)
我需要确保集合不为空.然后代码变成:
I need to ensure that the collection is not empty. The code then becomes:
<代码>枚举颜色{红色,绿色,蓝色};设置<颜色>set = ...//从某处获取它如果(set.isEmpty()){返回 EnumSet.noneOf(Color.class);别的返回 EnumSet.copyOf(set);
也许 javac 在确定传递给 copyOf
方法的集合成员的正确类型方面存在真正的限制,但我无法克服必须求助于类似方法的感觉以上,以迎合空集合.下面是我的问题:
Perhaps there is a real limitation on javac to determine the correct type of members of the collection passed to copyOf
method, but I can't get over the feeling that I have to resort to something like above to cater for the empty collection. Here are my questions then:
这里不能接受空集合的具体限制是什么?
Exactly what is the limitation that the empty collection can't be accepted here?
像 copyOf(Collection
这样的方法签名能解决这个问题吗?
Would a method signature like copyOf(Collection<Enum<E>>)
have solved this problem?
如果是,它会造成哪些其他问题?
If yes, what other problems would it have created?
推荐答案
鉴于 EnumSet.copyOf 空集合抛出 IllegalArgumentException,似乎有用的是接受元素类型参数的复制构造函数,这是创建新 EnumSet 时所必需的:
In light of EnumSet.copyOf empty collection throws IllegalArgumentException, what would seem to be of use would be a copy constructor which accepted an element type parameter, as is necessary when creating a new EnumSet:
EnumSet(Class<E>elementType, Enum<?>[] universe)
public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c, Class<E> elementType);
虽然节省的空间很小,但清晰度的提高是显着的.对比:
While the savings are small, the gain in clarity is significant. Contrast:
if ( set.isEmpty() )
return EnumSet.noneOf(Color.class);
else
return EnumSet.copyOf(set);
return EnumSet.copyOf(set, Color.class);
意图 只是将给定的集合复制为 EnumSet.对该意图的简单、直接的表达似乎最合适.
The intent is simply to copy a given set as an EnumSet. A simple, direct, expression of that intent seems most appropriate.
这篇关于Java:EnumSet.copyOf——还有改进的余地吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!