Java Enum compareTo

In this chapter you will learn:

  1. How to use Java Enum compareTo
  2. Syntax for Java Enum compareTo
  3. Return value from Java Enum compareTo
  4. Example - compare the ordinal value of two constants of enum

Description

You can compare the ordinal value of two constants of the same enumeration by using the compareTo() method.

Syntax


final int compareTo(enum-type e)

enum-type is the type of the enumeration, and e is the constant being compared to the invoking constant.

Return

If the two ordinal values are the same, then zero is returned. If the invoking constant has an ordinal value greater than e's, then a positive value is returned.

Example

Compare the ordinal value of two constants of enum


enum Direction {/*from  w w  w  .ja va 2 s . c o m*/
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {
    Direction ap = Direction.West;
    Direction ap2 = Direction.South;
    Direction ap3 = Direction.West;

    if (ap.compareTo(ap2) < 0){
      System.out.println(ap + " comes before " + ap2);
    }
      
    if (ap.compareTo(ap2) > 0){
      System.out.println(ap2 + " comes before " + ap);
    }
      
    if (ap.compareTo(ap3) == 0){
      System.out.println(ap + " equals " + ap3);
    }
      
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Java Enum equals
  2. Example - Compare for equality an enumeration constant with any other object
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour