How to check if a parameter value is in a list of constants

I have a list of constants and want to check if a value passed to a method equals one of the constants. I know Enums which would be fine, but I need an int value here for performance reasons. Enum values can have a value, but I'm afraid the getting the int value is slower than using an int directly. public static final int a = Integer.parseInt("1"), // parseInt is necessary in my application b = Integer.parseInt("2"), c = Integer.parseInt("3"); public void doIt(int param) { checkIfDefined(param); ... } The question is about `checkIfDefined`. I could use `if`: if(param == a) return; if(param == b) return; if(param == c) return throw new IllegalArgumentException("not defined"); Or I could use a `Arrays.binarySearch(int[] a, int key)`, or ... any better idea? Maybe enums would be better not only in elegance but also in speed, because I don't need the runtime checks. **Solution** Since whether `enum` nor `switch` worked in my special case with `parseInt`, I use plain old int constants together with `Arrays.binarySearch` now.

以上就是How to check if a parameter value is in a list of constants的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏