Home / Java Patterns and Pitfalls     frequal.com

Comparing Java Enums (Enumerations)

Sometimes you will need to compare enumerations to one another. Unfortunately Java doesn't support comparing enums using < and >. You can't do this:
  if (debugLevel < LogLevel.ERROR) {
    // Informational or debug info here
  }
Instead, use compareTo():
  if (debugLevel.compareTo(LogLevel.ERROR) < 0) {
    // Informational or debug info here
  }
compareTo() returns a negative number if the first enum is less than the one passed as a parameter.
Last modified on 6 Mar 2009 by AO

Copyright © 2024 Andrew Oliver