Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How values method work in enum

Tags:

java

In Enum how values() method work ?

what logic behind values() method ?

In my project we cache all enum data in Map as follow :

public enum Actions {
CREATE("create"),
UPDATE("update"),
DELETE("delete"),
ACTIVE("active"),
INACTIVE("inactive"),
MANAGE_ORDER("manage"),
;


private static Map<String, Actions> actionMap;
static {
    actionMap = new HashMap<String, Actions>(values().length);
    for(Actions action : values()) {
        actionMap.put(action.getName(), action);
    }
}

public static Actions fromName(String name) {
    if(name == null) 
        throw new IllegalArgumentException();
    return actionMap.get(name);
}
private String name;

private Actions(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

}

Is this best practice for use enum ?

like image 898
Punit Patel Avatar asked Feb 04 '26 01:02

Punit Patel


2 Answers

In Enum how values() method work ?

Read the Oracle tutorial:

The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

Another thing to note is that , if you use enum as keys , better to use EnumMap.

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

like image 172
AllTooSir Avatar answered Feb 05 '26 13:02

AllTooSir


Not great practice. Apart from MANAGE_ORDER, you could replace all that crap with this:

public static Action fromName(String name) {
    try {
        return valueOf(name.toUpperCase());
    } catch (IllegalArgumentException e) {
        return null;
    } 
}

Also, naming your field name is a poor choice, because all enums implicitly have:

public String name();

which returns the enum constant name as a String.

like image 25
Bohemian Avatar answered Feb 05 '26 13:02

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!