Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way to compare 3+ items in an If statement?

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.

like image 964
Vesque Avatar asked Mar 20 '23 08:03

Vesque


1 Answers

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.

like image 52
Has QUIT--Anony-Mousse Avatar answered Apr 25 '23 00:04

Has QUIT--Anony-Mousse