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.