[JAVA] enum definition

Why do you use ENUM?

→ Coding becomes easier to understand

Code example)

① Definition of ENUM

import java.util.HashMap;
import java.util.Map;

public enum FLAG {
    YES("1", "YES", "Yes"),
    NO("2", "NO", "No");

    public String v;
    public String nE;
    public String nJ;

    private FLAG(String v, String nE, String nJ) {
        this.v = v; this.nE = nE; this.nJ = nJ;
    }

    private static Map<String, FLAG> vMap = new HashMap<String, FLAG>();

    static {
        for(FLAG e : FLAG.values()) {
            vMap.put(e.v, e);
        }
    }

    public static FLAG vToE(String value) {
        return vMap.get(value);
    }

    public String getV() { return this.v; }
    public String getNE() { return this.nE; }
    public String getNJ() { return this.nJ; }
}

(2) How to call the ENUM value for the function


    FLAG.YES.getV()   //result:"1"
    FLAG.NO.getV()    //result:"2"

    FLAG.YES.getNJ()  //result:"Yes"
    FLAG.NO.getNJ()   //result:"No"

③ Comparison of ENUM When comparing, it is easier to understand by comparing ENUM instead of comparing strings.

    //Convert to ENUM
    ENUM YES_FLAG = FLAG.vToE("1"); // "1" :Yes
    ENUM NO_FLAG  = FLAG.vToE("2"); // "2" :No
    //ENUM comparison
    if(YES_FLAG == FLAG.YES) {
        // todo
    }

    if(NO_FLAG == FLAG.NO) {
        // todo
    }
    //For JSP, value comparison
    <c:if test="${FLAG.YES.getV() == '1'}">
    <c:if>

    //Or
    <c:if test="${FLAG.NO.getV() == '2'}">
    <c:if>

that's all

Recommended Posts

enum definition
About enum
[Java] enum
Enum (enumeration type)
Enum review notes
Java constant definition