An enumerated type (enum) is a data type which contains a set of finite, unique constants, which can be used to store categories. In most languages, the set is an ordered set, meaning the order in which the constants are defined is stored in some manner.
Java
Java treats enums as class-like structures, allowing them to have methods and attributes, as well as constructors.
An enum is defined using the enum
keyword, in the syntax: enum EnumName { constants }
.
A Java enum comes with the following pre-defined functions:
- Constructor
toString()
compareTo()
ordinal()
: A method that returns the position of the a given type, i.e. the first defined type would return 1 and so on.
These methods can be overridden if needed.
For example, suits of cards:
enum Suits {
DIAMOND, HEART, CLUB, SPADE
};
//Accessing constants
System.out.println(Suits.DIAMOND);
//Find the position of a value
System.out.println(Suits.DIAMOND + " is the " + Suits.DIAMOND.ordinal() "th suit.")
C
Enums in C are pure integer constants, and cannot be any other data type.
An enum is declared with the keyword enum
, followed by the name and values of the enum (known as the enum constants):
enum colours { RED, GREEN, BLUE };