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

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

    The loop doesn't do anything that calling valueof doesn't, they have the same functionality : checking whether your string is valid enum. What do you think you gain from the first option ?

    The second option is best:

     try {
         WeekDay weekDay = WeekDay.valueOf(day); // might throw exception
            ...
        } catch (IllegalArgumentException e) {
            throw new InvalidWeekDayException(day);
        }
    

提交回复
热议问题