Java enum reverse look-up best practice

前端 未结 7 701
感情败类
感情败类 2020-12-04 15:07

I saw it suggested on a blog that the following was a reasonable way to do a \"reverse-lookup\" using the getCode(int) in a Java enum:

public en         


        
7条回答
  •  庸人自扰
    2020-12-04 15:42

    Though it has higher overhead, the static map is nice because it offers constant-time lookup by code. Your implementation's lookup time increases linearly with the number of elements in the enum. For small enums, this simply will not contribute significantly.

    One issue with both implementations (and, arguably, with Java enums in general) is that there's really a hidden extra value that a Status can take on: null. Depending on the rules of the business logic, it may make sense to return an actual enum value, or throw an Exception, when the lookup "fails."

提交回复
热议问题