简体   繁体   中英

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.

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 (eg, int ), then you can write a non-generic version for the specific type.

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

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);

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM