The following example shows how to perform basic operation with enum.
All enum types implicitly implements java.io.Serializable and java.lang.Comparable.
Enum provides the following APIs,
public static <E extends Enum<E>> E[] values();
- Returns all enum constants of this element type.
public final String name()
- Returns name of enum constant.
public final int ordinal()
- Returns position in its enum declaration starting with index ZERO.
public static <T extends Enum<T>> T valueOf(String name)
- Returns the enum constant of this enum type with the specified name.
If no match found throws IllegalArgumentException.
public static <T extends Enum<T>> T valueOf(Class enumType, String name)
- Returns the enum constant of the specified enum type with the specified name.
If no match found throws IllegalArgumentException.
/**
* Get all enum constants of this type as array
*/
Fruit [] fruits = Fruit.values();
System.out.println(Arrays.toString(fruits));
System.out.println();
for (int i = 0 ; i < fruits.length ; i ++) {
System.out.println(fruits[i].name() + "->" + fruits[i].ordinal());
}
/**
* Get enum constant from Fruit enum class
*/
System.out.println();
Fruit fruit = Fruit.valueOf("MANGO");
System.out.println(fruit);
/**
* Get enum constant from static method of Enum class
*/
fruit = Enum.valueOf(Fruit.class, "APPLE");
System.out.println(fruit);
System.out.println();
public enum Fruit {
APPLE,
ORANGE,
BANANA,
CHERRY,
MANGO
}
It gives the following output,
[APPLE, ORANGE, BANANA, CHERRY, MANGO]
APPLE->0
ORANGE->1
BANANA->2
CHERRY->3
MANGO->4
MANGO
APPLE
java.lang.IllegalArgumentException:
No enum const class com.bethecoder.tutorials.utils.enums.Fruit.MANGO_BAD
java.lang.IllegalArgumentException:
No enum const class com.bethecoder.tutorials.utils.enums.Fruit.APPLE_BAD