I have an EnumSet
public static Set<T> getTypes() {
return EnumSet.of(
TYPE_1,
TYPE_2,
TYPE_3
);
}
And i want to get the values from it with a getter method
When i try to get the values in my program with a foreach loop they always come in wrong order. Is there a way to get them in correct order as written above? Thanks!
The order of elements in the
EnumSet
is the same as the natural ordering of the enum constants (i.e. the order of their declaration).Output:
If you need the order that differs from the natural ordering, you can switch to using a
List
instead of aSet
:Output:
Or if you need
Set
as a type, you can introduce a property responsible for ordering in yourenum
and make use of theTreeSet
providing aComparator
which is based on this property.Consider the following dummy
enum
:Example of storing the enum members into a
TreeSet
:Output: