soc*_*soc 4 java collections enums compare max
考虑一个由枚举类型组成的集合.是否有一些库方法min
(或max
)接受此集合(或varargs)并返回最小/最高值?
编辑:我的意思是枚举的自然顺序,由它们的compare
实现定义Comparable
.
枚举实现Comparable<E>
(where E is Enum<E>
),它们的自然顺序是枚举常量的顺序.您可以使用其默认的Comparable实现来获取声明的max和min常量:
public enum BigCountries {
USA(312), INDIA(1210), CHINA(1330), BRAZIL (190);
private int population;
private BigCountries(int population) {
this.population = population;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
BigCountries first = Collections.min(Arrays.asList(BigCountries.values())); // USA
BigCountries last = Collections.max(Arrays.asList(BigCountries.values())); //BRAZIL
Run Code Online (Sandbox Code Playgroud)
可能更快的方法是使用直接访问values()
方法返回的数组:
BigCountries[] values = BigCountries.values();
System.out.println(values[0]); // USA;
System.out.println(values[values.length-1]); // BRAZIL;
Run Code Online (Sandbox Code Playgroud)
请注意,给予枚举的参数对顺序没有影响.