你知道Enum怎么比较大小吗?
1、Enum实现Comparable接口,可使用compareTo方法来比较大小
先来个遍历enum的代码
Code:
package chapter4;
/**
* Created by MyWorld on 2016/3/21.
*/
enum Season {
Spring,
Summer,
Autumn,
Winter
}public class EnumCompare {
public static void main(String[] args) {
for (Season season : Season.values()) {
System.out.println(season + " " + season.ordinal());
}
}
}
2、执行上面的代码看看结果:
Spring 0
Summer 1
Autumn 2
Winter 3
3、看到了没,每个枚举值都有一个ordinal()方法,这个方法的执行结果是返回一个数。
这个数据是什么意义呢?
看看源码呢
源码:
/**
* Returns the ordinal of this enumeration constant (its position
* in its enum declaration, where the initial constant is assigned
* an ordinal of zero).
*
* Most programmers will have no use for this method. It is
* designed for use by sophisticated enum-based data structures, such
* as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
*
* @return the ordinal of this enumeration constant
*/
public final int ordinal() {
return ordinal;
}
4、直接使用枚举对象进行比较大小,就是使用这个值
使用Compare比较大小
Code:
System.out.println("Compare to autumn:" + season.compareTo(Season.Autumn));
5、执行下,
看看结果与预期的是否一致
是一致的!!
Output:
Spring 0
Compare to autumn:-2
Summer 1
Compare to autumn:-1
Autumn 2
Compare to autumn:0
Winter 3
Compare to autumn:1
6、既然有ordinal()方法,能不能使用==运算符呢
改下代码
Code:
System.out.println("Compare to autumn:" + (season == Season.Autumn));
7、执行下,
看看结果是否与预期一致
一致的.
枚举值之间是可以使用==来比较大小的
Output:
Spring 0
Compare to autumn:-2
Compare to autumn:false
Summer 1
Compare to autumn:-1
Compare to autumn:false
Autumn 2
Compare to autumn:0
Compare to autumn:true
Winter 3
Compare to autumn:1
Compare to autumn:false