Saving enums sorted in arraylist?

Say I had an enumeration called Planets in which there were VENUS, EARTH and MARS. I will have many lists of arrays that will contain no more than one type. I want every list of arrays always sorted using VENUS, EARTH and MARS.

Should I use a comparator for this? Is there a way to keep them sorted automatically after insertion, or do I need to call sorting after each insertion? Do I need to store an int value inside each type in order to distinguish their order?

Suggest alternative advice if you have, thanks.

+3
source share
7 answers

- TreeSet, . , " ", - , . , TreeSet Comparator .

, 3 , , EnumSet , TreeSet, , "" .

+3

, .

, , SortedSet (, TreeSet), List.

, , . , Comparator TreeSet.

EnumSet, SortedSet, , . .

+3

Java Doc

. , , , . Enum enum . , , - , .

, , , , .

+2

Arrays.asList(Planets.values())

0

enum.

0

You can just use EnumSet. It stores transfers sorted by their natural order (i.e., the order specified in the transfer declaration). This is a documented feature, you can rely on it.

0
source

Also note that Enums have an “ordinal” method that returns their position or the order in which this value is defined.

0
source

Source: https://habr.com/ru/post/1770873/


All Articles