Keeping enums sorted in an arraylist?
Say I had a an enum called Planets that contained VENUS, EARTH, and MARS. I will have a lot of array lists that will hold at most one of each type. I want to keep each array list sorted at all times in order from VENUS, EARTH, and MARS.
Would I need to use a comparator for this? Is there a way to keep them sorted automatically after an insert, or will I need to call sort after each insert? Will I need to keep an int value within 开发者_高级运维each type to distinguish their order?
Offer alternative advice if you have any, thank you.
The most general solution is to use a TreeSet, which keeps items in sorted order as you insert. If you don't provide a comparator, then it'll maintain "natural ordering", which for enums is the order they were declared in. Since that order is susceptible to change, your best bet is to declare the TreeSet with a custom Comparator that orders them as necessary.
Of course, if you only have 3 enums, and each collection has at most one of each, you could be lazy and manually put them in an EnumSet in the proper order, but the TreeSet is probably the "proper" approach for the long term.
I will have a lot of array lists that will hold at most one of each type. I want to keep each array list sorted at all times
What you describe is a SortedSet
(such as a TreeSet
), not a List
.
To determine the sort order, you just have to put the enum constants in the correct order when you define them. If you don't want to do that or need a varying sort order, you can use a Comparator
as constructor argument for the TreeSet
.
Alternatively, you can use an EnumSet
, which does not implement SortedSet
, but also iterates over the contents in the order in which the enum constants are declared. It's also very fast and memory-efficient.
From the Java Doc
Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 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.
So if that is fine you wont need to implement a Comparator, but if you want alphabetical you will need to.
What about Arrays.asList(Planets.values())
The order is maintained by the enum fascility.
You can just use EnumSet. It keeps enums sorted by their natural ordering (i.e. order you specify in your enum declaration). This is documented feature, you can rely on it.
Also note that Enums have an "ordinal" method which returns their position or order in which that value is defined.
精彩评论