echox
echox

Reputation: 9860

compareTo and nested Enums

in "A Programmers Guide to Java SCJP Certification" I found an example which I can't follow.

This the given enum:

enum Scale3 {
    GOOD(Grade.C), BETTER(Grade.B), BEST(Grade.A);

    enum Grade {A, B, C}

    private Grade grade;

    Scale3(Grade grade) {
        this.grade = grade;
    }

    public Grade getGrade() { return grade; }
}

This is the given expression:

Scale3.GOOD.getGrade().compareTo(Scale3.Grade.A) > 0;

I don't understand why this expression will be true?
The return value will be 2.

compareTo() will return a value > 0 if the given object is "less" than the object.

Scale3.Grade.A is the "biggest" element of Grades, its ordinal number is 0.

Scale3.GOOD is the "biggest" element of Scale3, its ordinal number is also 0.

The constructor of Scale3 is called with Scale3.Grade.C, which ordinal number is 2.

So the given expression is equal to the following code:

Scale3.Grade.C.compareTo(Scale3.Grade.A) > 0;

A is "bigger" than C, so shouldn't be the result < 0?

Upvotes: 1

Views: 384

Answers (2)

aioobe
aioobe

Reputation: 421020

A is "bigger" than C, so shouldn't be the result < 0?

No, A is smaller than C since it comes before C in enum Grade {A, B, C}

Note that the order of A, B and C is reversed in

GOOD(Grade.C), BETTER(Grade.B), BEST(Grade.A);

Upvotes: 2

Eyal Schneider
Eyal Schneider

Reputation: 22446

Enums implement the Comparable interface, and the comparison is based on their ordinal number (their position in the enum declaration).

The ordinal value of Scale3.Grade.A is 0, and the ordinal value of Scale3.Grade.C is 2. Therefore, C is "bigger" than A.

See the implementation of Enum.compareTo(E o).

Upvotes: 5

Related Questions