Enums implement Comparable<E>
(where E is Enum<E>
), and their natural order is the order in which enumeration constants are declared. You can use your default Comparable implementation to get the max and min constants as announced:
public enum BigCountries { USA(312), INDIA(1210), CHINA(1330), BRAZIL (190); private int population; private BigCountries(int population) { this.population = population; } }
Then you can use:
BigCountries first = Collections.min(Arrays.asList(BigCountries.values())); // USA BigCountries last = Collections.max(Arrays.asList(BigCountries.values())); //BRAZIL
Probably a faster way would be to use direct access to the array returned by the values()
method:
BigCountries[] values = BigCountries.values(); System.out.println(values[0]); // USA; System.out.println(values[values.length-1]); // BRAZIL;
Note that the parameter assigned to the enumeration does not affect the order.
maasg source share