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

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

    Store the valid strings in a HashSet, and decide whether a string is a valid day or not based on Set.contains(...).

    The set can be a static final Set, and you can wrap in an unmodifiable for good measure:

    private static final Map WEEKDAY_STRINGS;
    static {
      HashSet set = new HashSet();
      for (WeekDay d : WeekDay.values()) {
        set.add(d.toString());
      }
      WEEKDAY_STRINGS = Collections.unmodifiableSet(set);
    }
    

提交回复
热议问题