benz
benz

Reputation: 4629

Enums compareTo() method implementation

I have an example and i am confused at the output.

 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));
}
}

The last line returns -3. Why is that? It should return -1 as season1 is less than season4. Why it would return -3?

Thanks.

Upvotes: 0

Views: 1270

Answers (4)

yurgis
yurgis

Reputation: 4077

Enum compareTo() is substracting ordinal values, so in your case it is WINTER.ordinal() - AUTUMN.ordinal() = 0 - 3 = -3

Upvotes: 3

Martin Petkov
Martin Petkov

Reputation: 420

If the object (in this case enum) from which you are calling the compareTo() method is greater than the argument in it - it will return a positive integer (1, 2, ..., 323432, doesn't matter really)

If they are equal it will be exactly 0

If the calling object is smaller than the argument, then it is going to be smaller than 0 (-1, -2... etc).

When using it in if statements and booleans use the > and < operators for the smaller and greater cases, instead of using == 1 or == -1

Upvotes: 0

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

Assuming elements are ordered on integerly basis,

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

Upvotes: 2

SLaks
SLaks

Reputation: 888283

compareTo() is allowed to return any positive or negative number, or zero.

It has no need to specifically return +/- 1.

Upvotes: 7

Related Questions