枚举compareTo()方法实现

时间:2015-01-14 19:48:05

标签: java

我有一个例子,我对输出感到困惑。

 enum Seasons {
    WINTER,
    SUMMER,
    SPRING,
    AUTUMN;
}
public class SeasonTest{
    public static void main(String[] args) {
    Seasons season1 = Seasons.WINTER;
    Seasons season2 = Seasons.SUMMER;
    Seasons season3 = Seasons.SPRING;
    Seasons season4 = Seasons.AUTUMN;
    System.out.println(season1.compareTo(season2));
    System.out.println(season3.compareTo(season4));
    System.out.println(season4.compareTo(season3));
    System.out.println(season2.compareTo(season1));
    System.out.println(season3.compareTo(season3));
    System.out.println(season1.compareTo(season4));
}
}

最后一行返回-3。这是为什么?它应该返回-1,因为season1小于season4。为什么它会返回-3?

感谢。

4 个答案:

答案 0 :(得分:7)

允许

compareTo()返回任何正数或负数,或者为零。

无需专门返回+/- 1。

答案 1 :(得分:3)

枚举compareTo()是减去序数值,所以在你的情况下它是WINTER.ordinal() - AUTUMN.ordinal() = 0 - 3 = -3

答案 2 :(得分:2)

假设元素按整数排序,

 enum Seasons {
    WINTER,   // 0  \
    SUMMER,   // 1   \
    SPRING,   // 2    \
    AUTUMN;   // 3   --- difference is 3 (subtraction gives -3)
}

答案 3 :(得分:0)

如果您调用compareTo()方法的对象(在本例中为枚举)大于其中的参数 - 它将返回一个正整数(1,2,...,323432,不是&#39)真的很重要)

如果它们相等,那么它将完全为0

如果调用对象小于参数,那么它将小于0(-1,-2 ......等)。

在if语句和布尔值中使用它时使用>和<针对较小和较大案例的运算符,而不是使用== 1== -1