Java:EnumSet.copyOf-是否有改进的空间? [英] Java: EnumSet.copyOf -- is there a room for improvement?

查看:118
本文介绍了Java:EnumSet.copyOf-是否有改进的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个 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:

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);

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方法的集合的成员的正确类型确实存在局限性,但我无法克服这样的感觉,我不得不依靠上述方法来满足空集合.然后是我的问题:

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:

  1. 究竟在这里不能接受空集合的局限性是什么?

  1. Exactly what is the limitation that the empty collection can't be accepted here?

copyOf(Collection<Enum<E>>)这样的方法签名是否可以解决此问题?

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屋!

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