Efficiently converting java string to its equivalent enum

前端 未结 3 1808
离开以前
离开以前 2021-01-26 02:26

Given a string i want to get the enum equivalent of it in constant time. I have a enum defined like the one shown in the question. Best way to create enum of strings?

         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-26 03:26

    Is Enum.valueOf() not sufficient? How would you imagine being more efficient than that? There's (usually) no need to have an enum STRING_ONE("ONE") - just call enum value ONE and you get .valueOf() lookup for free.

    Otherwise, just create a private static Map and provide a similar valueOf() method that looks up against the Map.

提交回复
热议问题