Java - Enum datatype

Java Conceptuel Diagram

About

The enum data type implementation in java

Because they are constants, the names of an enum type's fields are in uppercase letters.

The enum declaration defines a class (called an enum type). The enum class body can include:

  • methods
  • and other fields.

Example

  • compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
  • days of the week

Definition

An enum type is defined by using the enum keyword.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

Instantiation

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type

Enum types may not be instantiated. The following code will throw an error:

MyEnum myEnum = new MyEnum();

Method associated

The compiler automatically adds some special methods when it creates an enum.

  • a static values method that returns an array containing all of the values of the enum in the order they are declared.
  • a static ordinal method that returns the numerical position of each enum constant in its type

Conversion

toOrdinal

myEnum.ordinal()

Int to Enum

EnumClass.values()[someInt]

To joined string

Arrays.stream(TransferOperation.values())
    .map(TransferOperation::toString)
    .collect(Collectors.joining(", "))

String to enum

EnumClass.valueOf("An Enum String")

enum to String

myEnum.name()

Stream of String to Array

Transform a list of string in an enum array

MyEnum[] myEnums= listOfString.stream()
        .map(MyEnum::valueOf)
        .toArray(myEnum[]::new);

Example

Enum

public enum SimpleEnum {

    NICO("nico", 41.0),
    MADELIEF("madelief", 8.0);

    private final String name;
    private final Double age;

    SimpleEnum(String name, Double age) {
        this.name = name;
        this.age = age;
    }


    public static void main(String[] args) {
        // Get a Madelief object, print Nico
        SimpleEnum simpleEnum = SimpleEnum.MADELIEF;
        System.out.println("Print Nico as an instance method of Madelief: "+simpleEnum.getDynamicallyNico());

        // Print a static
        System.out.println("Print Nico as class method (Statically): "+SimpleEnum.getStaticallyNico());

        // Print Madelief and Nico
        System.out.println("Print all enum values ");
        for (SimpleEnum enumValue : SimpleEnum.values()) {
            System.out.printf("The age of %s is %f%n",
                    enumValue, enumValue.age);
        }


    }

    public static SimpleEnum getStaticallyNico() {
        return NICO;
    }

    public static SimpleEnum getDynamicallyNico() {
        return NICO;
    }
    
}
Print as instance method NICO
Print as class method (Statically) NICO
Print all enum values 
The age of NICO is 41.000000
The age of MADELIEF is 8.000000

Singleton

Singleton implementation.

INSTANCE is public static final field that represents the enum instance. You can get the instance of the class with the following statement EnumSingleton.INSTANCE but it's best to encapsulate it in a getter in case of you may want to change the implementation.

public enum EnumSingleton {

    INSTANCE;

    private String name; // Mandatory
    private Double age = null; // Not Mandatory

    private void build(SingletonBuilder builder) {
        this.name = builder.name;
        this.age = builder.age;
    }

    // Static getter
    public static EnumSingleton getSingleton() {
        return INSTANCE;
    }

    public void print() {
        System.out.println("Name "+name + ", age: "+age);
    }


    public static class SingletonBuilder {

        private final String name;
        private Double age = null;

        private SingletonBuilder(){
              name = null;
        }

        SingletonBuilder(String name) {
            this.name = name;
        }

        public SingletonBuilder age(double age) {
            this.age = age;
            return this;
        }

        public void build(){
            EnumSingleton.INSTANCE.build(this);
        }

    }


    public static void main(String[] args) {
        new SingletonBuilder("nico").age(41).build();
        EnumSingleton.getSingleton().print();
    }

}
Name nico, age: 41.0

Documentation / Reference





Discover More
Card Puncher Data Processing
Design Pattern - (Static) Factory

The Factory pattern creates an instance of an object according to a given specification, sometimes provided as arguments, sometimes inferred. It's a dependency resolving approach. A factory class decouples...
Card Puncher Data Processing
Design pattern - The Singleton

The singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is...
Java Conceptuel Diagram
How to use the Switch expression (case) in Java?

This article is the implementation of the Switch branching statement in Java primitive typeenumcaseintInteger The value switch is supported. Java does not support expression switch, you should...
Java Conceptuel Diagram
Java - (Data Type|Type)

data type in the java world. The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. The language supports four kinds...
Java Conceptuel Diagram
Java - Abstract Modifier

Abstract is a modifier that require override. An abstract class is a class that can't be instantiated. It's only purpose to be extended by other classes. See enum Abstract class provides a skeletal...
Simple Class
Java - Class (Definition)

A java/lang/Classclass provides the blueprint for objects; you create an object from a class. All classes are derived from the Object class. A class declaration names the class and encloses the class...
Java Conceptuel Diagram
Java - Constant

The names of constant fields are in upper-case letters. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated...
Java Conceptuel Diagram
Java - Member of a class

The members of a class are the inherited components of the class body including: fields, methods, nested classes, interfaces, and enumerated types. Since constructors are not inherited,...
Java Conceptuel Diagram
Java - Reference Data Type

Reference types in Java. Reference types all inherit from Object (the java.lang.Object class) Classes, enums, arrays, and interfaces Examples of reference types include: java.lang.String,...



Share this page:
Follow us:
Task Runner