Thursday, February 7, 2013

Efficient mapping of Java Enums

The idea is to create Enum out of some other type like string or int - this is the method valueOfRole in examples below. I've seen few code examples which are based on this approach:
public enum RoleWithLoop {
    SU(0), ADMIN(1), USER(1000);

    private final int state;

    RoleWithLoop(int state) {
        this.state = state;
    }

    public static RoleWithLoop valueOfRole(int state) {
        for (RoleWithLoop role : RoleWithLoop.values()) {
            if (role.state == state) {
                return role;
            }
        }
        return null;
    }
}
Each mapping call iterates over all Enum entries - this is fine if it contains only few elements. But more efficient solution is to use Map lookup instead of loop:
public enum RoleWithMap {
    SU(0), ADMIN(1), USER(1000);

    private final int state;

    private final static Map<Integer, RoleWithMap> MAPPING = 
          new HashMap<Integer, RoleWithMap>(RoleWithMap.values().length);
    RoleWithMap(int state) {
        this.state = state;
    }

    static {
        for (RoleWithMap role : RoleWithMap.values()) {
            MAPPING.put(role.state, role);
        }
    }

    public static RoleWithMap valueOfRole(int state) {
        return MAPPING.get(state);
    }
}


No comments:

Post a Comment