Enumeration Classes Core Java

Previously how to define enumerated types in Java SE 5.0 and beyond. Here is a typical example:

The type defined by this declaration is actually a class. The class has exactly four instances —it is not possible to construct new objects.

Therefore, you never need to use equals for values of enumerated types. Simply use == to compare them. You can, if you like, add constructors, methods, and fields to an enumerated type. Of course, the constructors are only invoked when the enumerated constants are constructed.

Here is an example.

All enumerated types are subclasses of the class Enum. They inherit a number of methods from that class. The most useful one is toString, which returns the name of the enumerated constant. For example, Size .SMALL .toString() returns the string "SMALL".

The converse of toString is the static valueOf method. For example, the statement

sets s to Size.SMALL.

Each enumerated type has a static values method that returns an array of all values of the enumeration. For example, the call

returns the array with elements Size.SMALL, Size .MEDIUM, Size .LARGE, and Size .EXTRA _LARGE.

The ordinal method yields the position of an enumerated constant in the enum declaration, counting from zero. For example, Size.MEDIUM.ordinal() returns 1.

The short program in Listing below demonstrates how to work with enumerated types.

NOTE: The Enum class has a type parameter that we have ignored for simplicity. For example, the enumerated type Size actually extends Enum<Size>. The type parameter is used in the compareTo method


java.lang.Enum<E> 5.0

  • static Enum valueOf(Class enumClass, String name)
    returns the enumerated constant of the given class with the given name.
  • String toString()
    returns the name of this enumerated constant.
  • int ordinal()
    returns the zero-based position of this enumerated constant in the enum declaration.
  • int compareTo(E other)
    returns a negative integer if this enumerated constant comes before other, zero if

this == other, and a positive integer otherwise. The ordering of the constants is given by the enum declaration.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics