Search code examples
javaenumscompareto

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

Solution

  • 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