Java Enum.valueOf() efficiency when value does not exist

后端 未结 7 3452
深忆病人
深忆病人 2021-02-20 17:58

Which would you consider more efficient?

The use of \'WeekDay\' is just an example:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDA         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 18:43

    Or you could create a lookup of enum values inside your enum when the class first loads(see static modifier) and validate using get() as shown below:

    private String dayName;
    private static final Map lookup = new HashMap();
    static{
        for (Weekday day: values()){
            lookup.put(day.dayName, d);
        }
    }
    public static Weekday get(String _name){
        return lookup.get(_name);
    }
    

    Let me know if you need more details

提交回复
热议问题