简体   繁体   中英

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.
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 .

也许你可以看看EnumSet实现。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM