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

后端 未结 7 3460
深忆病人
深忆病人 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:39

    As has been commented, you will have to profile to find out for sure. Even in your own parsing approach, you can make it faster by returning the enum when you parse the list.

    private WeekDay getValidWeekDay(String day) {
        for (WeekDay weekDay : WeekDay.values()) {
            if(weekDay.toString().equals(day))
               return weekDay;
        }
        return null;
    }
    

    Unless this is a time critical piece of an application, I wouldn't worry about it in either case and simply take the most readable approach. I think that would be using the WeekDay.valueOf() method.

    If you would rather not have to deal with exceptions, then create a Map of your values within the enum and effectively do the equivalent of valueOf() from a lookup which returns null if it is not found.

    public enum WeekDay {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
    
        private static Map valueMap;
    
        public static WeekDay getValue(String possibleName)
        {
            if (valueMap == null)
            {
                valueMap = new HashMap();
                for(WeedDay day: values())
                    valueMap.put(day.toString(), day);
            }
            return valueMap.get(possibleName);
    
        }
     }
    

    This is effectively what the valueOf() method is doing anyway, except it throws the IllegalArgumentException when it is not found. This approach will simply return null, thus not generating the stacktrace.

提交回复
热议问题