Let's say I want to compare a bunch of variables to one static variable, normally I would do it like this:
int w = 0;
int x = 1;
int y = 1;
int z = 2;
if(w == x || w == y || w == z){/*more code here*/}
But that can get extremely long and doesn't seem necessary, are there any ways to do something more like:
if(w == (x || y || z)){/*more code here*/}
I would like to think that there is a way to do it like this.
Efficient if-else StatementsWhile in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.
The mnemonic DRY (Don't Repeat Yourself) vs. WET (Write Everything Twice) is a cute way to remember this.
Instead of:
if(w == x || w == y || w == z)
you can do:
if(Arrays.asList(x, y, z).contains(w))
Though there is an answer accepted, I would want to share my ways too:
Method 1 is similar to the accepted answer. However, instead of using List, I use a Set. In such case, it may be even faster than doing ==
individually if there are lots of values to check against:
// make it a static final member if semantically possible
Set<Integer> ALL_VALUES = new HashSet<Integer>(Arrays.asList(a,b,c,d,e,f,g,h));
//.....
if (ALL_VALUES.contains(w)) {
//... do something
}
Method 2 is to write a little utility function, something like
public static <T> boolean sameAsAny(T value, T... possibleValues) {
for (T p : possibleValues) {
if (value == p) {
return true;
}
}
return false;
}
with such util you can do something like:
if (sameAsAny(w, x, y, z))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With