用 Java 中的所有枚举值填充 List

我想用枚举的所有可能值填充列表
因为我最近爱上了 EnumSet,所以我利用了 allOf() < br >

EnumSet<Something> all = EnumSet.allOf( Something.class);
List<Something> list = new ArrayList<>( all.size());
for (Something s : all) {
list.add( s);
}
return list;

是否有更好的方法 (如在非混淆的一行中)来达到同样的结果?

202192 次浏览

This is a bit more readable:

Object[] allValues = all.getDeclaringClass().getEnumConstants();

There is a constructor for ArrayList which is

ArrayList(Collection<? extends E> c)

Now, EnumSet extends AbstractCollection so you can just do

ArrayList<Something> all = new ArrayList<Something>(enumSet)

I wouldn't use a List in the first places as an EnumSet is more approriate but you can do

List<Something> somethingList = Arrays.asList(Something.values());

or

List<Something> somethingList =
new ArrayList<Something>(EnumSet.allOf(Something.class));
List<Something> result = new ArrayList<Something>(all);

EnumSet is a Java Collection, as it implements the Set interface:

public interface Set<E> extends Collection<E>

So anything you can do with a Collection you can do with an EnumSet.

try

enum E {
E1, E2, E3
}


public static void main(String[] args) throws Exception {
List<E> list = Arrays.asList(E.values());
System.out.println(list);
}

Try this:

... = new ArrayList<Something>(EnumSet.allOf(Something.class));

as ArrayList has a constructor with Collection<? extends E>. But use this method only if you really want to use EnumSet.

All enums have access to the method values(). It returns an array of all enum values:

... = Arrays.asList(Something.values());

Class.getEnumConstants()

List<SOME_ENUM> enumList = Arrays.asList(SOME_ENUM.class.getEnumConstants());

You can use also:

Collections.singletonList(Something.values())
private ComboBox gender;
private enum Selgender{Male,Famle};
ObservableList<Object> observableList  =FXCollections.observableArrayList(Selgender.values());