enum in ordered list or set
I want to create an ordered set, or list, and add enums to the collection so they are inserted in enum order.
开发者_如何学Python Can I do this without creating an explicit comparator? Is there a collection that will use the inherent order of the enum to maintain the order in the collection?Example in Groovy of what I want to do (I expect it will be similar for Java with a for loop instead of a closure):
TreeSet<TransactionElement> elements = new TreeSet<TransactionElement>()
elementList.each{ element -> elements.add(element)}
TransactionElement is an enum and the elements should be added to the TreeSet in the order they are listed in the enum
UPDATE: Solution I went with:
EnumSet<TransactionElement> elements = EnumSet.noneOf(TransactionElement.class);
elementList.each{ element -> elements.add(element)}
Some great examples of how to use EnumSet and EnumMap here
If you want a Set
of enum
values, then EnumSet
is probably your best bet. Not only is it more efficient that using a non-specialized Set
, it also guarantees that the iteration will work in the natural order of the enum
.
Maybe you could tale a look at the EnumSet implementation.
By default Enums declaration order defines the natural ordering of the Enums. From javadoc of compareTo:
Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared.
精彩评论