Conside开发者_C百科r a collection consisting of enum types. Is there some library method min
(or max
) which accepts this collection (or varargs) and returns the smallest/highest value?
EDIT: I meant the natural order of enums, as defined by their compare
implementation of Comparable
.
Enums implement Comparable<E>
(where E is Enum<E>
) and their natural order is the order in which the enum constants are declared.
You can use their default Comparable implementation to get the max and min constants as declared:
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 given to the enum has no effect in the ordering.
If you have some Set<MyEnum>
, it should already be of type EnumSet
. Sadly, this class does not provide first
and last
methods, but it does guarantee to iterate in increasing order, so you can reliably use, for example, the first and last elements in thatSet.toArray()
.
If you want custom ordering (say alphabetical), use a custom comparator on any collection
class MyComparator implements Comparator<MyEnumType>
{
public int compare(MyEnumType enum1, MyEnumType enum2)
{
return o1.toString().compareTo(o1.toString());
}
}
If you want to keep the declared order, put them into a SortedSet
SortedSet<MyEnumType> set = new TreeSet<MyEnumType>();
set.add(enum1);
精彩评论