user2372445
user2372445

Reputation: 101

How to combine equality operators in an if statement in java?

In python, you can do

if(a!=b!=c)

How can you do the same thing in Java without having to separate them and write all the "&&" operators? I'm trying to check that all 10 elements are not equal, and I don't want to have to write the equality statement 45 times.

Upvotes: 0

Views: 285

Answers (5)

MadProgrammer
MadProgrammer

Reputation: 347334

I agree that Set is probably the most efficient solution, but if you need to supply some kind of customization to the comparison, you could use something like...

Comparable[] values = new Comparable[]{1, 2, 3, 4, 5};
boolean matches = true;
for (int outter = 0; outter < values.length; outter++) {
    for (int inner = outter + 1; inner < values.length; inner++) {
        matches &= values[outter].compareTo(values[inner]) == 0;
    }
}
System.out.println(matches);

Upvotes: 0

Makoto
Makoto

Reputation: 106508

Honestly, no, there's no native way to do this in Java.

But, why don't we implement the syntactic sugar for Python's all method instead? With varargs, it's not difficult. It does have an O(n) runtime cost, though.

public static boolean all(Boolean... theBools) {
    Boolean result = Boolean.TRUE;
    for(Boolean b : theBools) {
        if(null == b || !b) {
            result = Boolean.FALSE;
            break;
        }
    }
    return result;
}

You can use it then like this:

if(YourClass.all(a, b, c, d, e, f, g, h, i, j)) {
    // something to do if ALL of them are true
}

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

You cannot do that operation in Java. Note furthermore that if a, b, etc., are not primitives, then you should probably be using equals instead of == (or !=). The latter only check for object identity, not equality of values.

If you want to check whether 10 elements are all distinct, you can throw them into a Set implementation (such as HashSet) and check that the set contains 10 elements. Or better (thanks to @allonhadaya for the comment), check that each element was added. Here's a generic method that works for an arbitrary number of objects of arbitrary type:

public static <T> boolean areDistinct(T... elements) {
    Set<T> set = new HashSet<T>();
    for (T element : elements) {
        if (!set.add(element)) {
            return false;
        }
    }
    return true;
}

If your elements are primitives (e.g., int), then you can write a non-generic version for the specific type.

Upvotes: 4

gluckonavt
gluckonavt

Reputation: 236

Something wrong in your program, if you need to compare 45 variables. Try to use arrays and cycles.

Upvotes: 1

vishal_aim
vishal_aim

Reputation: 7854

There's no such option in java (you cannot do such thing without using &&). Java is not Python

Upvotes: 0

Related Questions