Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    public static void main(String[] args) {
        MyEnum enum1 = MyEnum.Choice1;
        System.out.println("enum1==>" + String.valueOf(enum1));
        MyEnum enum2 = MyEnum.getByValue(enum1.getValue());
        System.out.println("enum2==>" + String.valueOf(enum2));
        MyEnum enum3 = MyEnum.getByValue(4);
        System.out.println("enum3==>" + String.valueOf(enum3));
    }
}

enum MyEnum {
    Choice1(1), Choice2(2), Choice3(3);
    private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
    static {
        for (MyEnum myEnum : values()) {
            MY_MAP.put(myEnum.getValue(), myEnum);
        }
    }
    private int value;

    private MyEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static MyEnum getByValue(int value) {
        return MY_MAP.get(value);
    }

    public String toString() {
        return name() + "=" + value;
    }

}