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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With