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
EnumSetis 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
Listinstead of aSet:Output:
Or if you need
Setas a type, you can introduce a property responsible for ordering in yourenumand make use of theTreeSetproviding aComparatorwhich is based on this property.Consider the following dummy
enum:Example of storing the enum members into a
TreeSet:Output: