I would like to fill a list with all possible values of an enum
Since I recently fell in love with EnumSet
, I leveraged allOf()
EnumSet<Something> all = EnumSet.allOf( Something.class);
List<Something> list = new ArrayList<>( all.size());
for (Something s : all) {
list.add( s);
}
return list;
Is there a better way (as in non obfuscated one liner) to achieve the same result?
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)
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());
List<SOME_ENUM> enumList = Arrays.asList(SOME_ENUM.class.getEnumConstants());
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
.
This is a bit more readable:
Object[] allValues = all.getDeclaringClass().getEnumConstants();
You can use also:
Collections.singletonList(Something.values())
private ComboBox gender;
private enum Selgender{Male,Famle};
ObservableList<Object> observableList =FXCollections.observableArrayList(Selgender.values());
Source: Stackoverflow.com