EnumSet从阵列,最短的变种? [英] EnumSet from array, shortest variant?

查看:108
本文介绍了EnumSet从阵列,最短的变种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 EnumSet 从数组(这是通过一个可变参数的方法参数给出)。首先,我很惊讶,没有在 EnumSet 没有可变参数的构造方法(有 EnumSet#(E首先,E ...... REST)的)。作为一种变通方法,我用下面的变量:

I need an EnumSet from an array (which is given through a varargs method parameter). First, I was surprised that there is no varargs constructor method in EnumSet (there is EnumSet#of(E first, E... rest)). As a workaround, I used the following variant:

EnumSet<Options> temp = EnumSet.copyOf(Arrays.asList(options));

不过,这会触发 java.lang.IllegalArgumentException异常:集合为空。所以,现在我结束了以下,这看起来有点荒谬:

However, this triggers a java.lang.IllegalArgumentException: Collection is empty. So, now I ended up with the following, which looks somewhat ridiculous:

EnumSet<Options> temp = options.length > 0 ? 
                        EnumSet.copyOf(Arrays.asList(options)) : 
                        EnumSet.noneOf(Options.class);

如果这当然可以,如果有使用现有的方法更简单的方式转移到一些实用的方法,不过,我在问自己?

If course this could be moved to some utility method, but still, I'm asking myself if there is a simpler way using existing methods?

推荐答案

这是两条线,但稍微不太复杂的:

This is two lines, but slightly less complex:

    EnumSet<Options> temp = EnumSet.noneOf(Options.class); // make an empty enumset
    temp.addAll(Arrays.asList(options)); // add varargs to it

我不认为这是比任何其他种类的一类变量声明不拥有你想要的构造更糟糕的:

I don't consider this worse than any other kind of variable declaration for a class which doesn't have the constructor you want:

    SomeClass variable = new SomeClass(); // make an empty object
    variable.addStuff(stuff); // add stuff to it

这篇关于EnumSet从阵列,最短的变种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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