Programming 3

University of Alicante, 2024–2025

Enumerated types in Java

An enumerated type is a child class of java.lang.Enum. Constant values in an enumerated type are actually instances (i.e. objects).

enum Color {
  none, black, silver
}

Color c = Color.black;

Method toString()

System.out.println(c); // equivalent to System.out.println(c.toString());

Methods equals() and compareTo()

if ( c.equals(Color.silver) ) ...
if ( c == Color.silver ) ...

c.compareTo(Color.black) --> 0
c.compareTo(Color.silver) --> -1
c.compareTo(Color.none) --> 1

##More methods

  • ordinal(): returns the integer value assigned by Java to the Enum constant.

  • static values(): generates an array with the different values for the Enum constants:

for (Color c : Color.values()) ...

  System.out.println(c.ordinal()); // it usually starts from zero
  • static valueOf(String)
Color c = Color.valueOf("black");

Switch statements

Enumerated types can be used in switch statements.

switch(c) {
  case none: ...
  case black:
}

Importing enumerated types

To avoid qualifying the names of the Enum constants, import can be used:

import static modelo.Color.*;
...
Color c = black;