I am writing a program for a class assignment and I want to compare multiple items in an array for equivalence. My statement basically looks like:
if (a == b && b == c && c == d && d == e && e == f) {
// do stuff
}
This condition seems incredibly verbose, and I am wondering if there's a shorter way to write this.
This may appear to be verbose, but at least it is reasonably efficient and clear.
Don't overdo it with optimizing code for brevity.
You could easily make a helper function
boolean allEqual(Object ... objs) {
for(int i = 1; i < obj.length; i++) {
if (!objs[i].equals(objs[0])) {
return false;
}
}
return true;
}
But this will create additional objects; in particular with primitive values:
if (allEqual(1.1,2.1,3.1,4.1))
will create 5 objects, that need to be garbage collected.
Make sure you actually want ==
and not equals
.
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