2

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;
    }
}
Reuben Sanders
  • 370
  • 1
  • 2
  • 11
the133448
  • 75
  • 7

2 Answers2

7

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
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
Reuben Sanders
  • 370
  • 1
  • 2
  • 11
  • Those examples that you have, do they have to be in the Enum, or can they be in any Class? – the133448 Dec 11 '14 at 07:42
  • You can call them from any class, as long as you import `Test`. If you want to use `compareTo(T)` in another class you have to implement the `Comparable` interface. It lets you specify a natural ordering for the class. See: https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html – Reuben Sanders Dec 11 '14 at 07:59
0

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.

Phat H. VU
  • 2,350
  • 1
  • 21
  • 30