the133448
the133448

Reputation: 75

Using compareTo in an Enum

I have seen this code, an am unsure how it works with the compareTo. Could someone guide me through how it works?

public enum Test
{
    POTATO("Potato"), 
    TOMATO("Tomato"), 
    CARROT("Carrot")

    public String Name;

    private Test(String name) {
        this.Name = name;
    }

    public boolean testFor(Test t)
    {
        if (compareTo(t) <= 0) {
            return true;
        }
        return false;
    }
}

Upvotes: 2

Views: 1841

Answers (2)

Reuben Sanders
Reuben Sanders

Reputation: 370

Enum values are compared by the order they are created. So POTATO is less than CARROT because the ordinal is less for POTATO than for CARROT.

A few examples:

Test.POTATO.compareTo(Test.TOMATO); // returns -1, is less
Test.POTATO.compareTo(Test.POTATO); // returns 0, is equal
Test.CARROT.compareTo(Test.POTATO); // returns 2, is bigger

Upvotes: 7

Phat H. VU
Phat H. VU

Reputation: 2360

compareTo is the final method from the Enum abstract class. According to this docs

compareTo(E o) : Compares this enum with the specified object for order.

Upvotes: 0

Related Questions