Is there a simpler way to check multiple values against one value in an if-statement?

前端 未结 12 873
名媛妹妹
名媛妹妹 2020-11-27 07:55

Basically, what I want to do is check two integers against a given value, therefore, classically what you would do is something like this:

//just to get some         


        
12条回答
  •  遥遥无期
    2020-11-27 08:16

    Unfortunately there is no such construct in Java.

    It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:

    public boolean oneOfEquals(int a, int b, int expected) {
        return (a == expected) || (b == expected);
    }
    

    Then you could use it like this:

    if(oneOfEquals(a, b, 0)) {
        // ...
    }
    

    If you don't want to restrict yourselft to integers, you can make the above function generic:

    public  boolean oneOfEquals(T a, T b, T expected) {
        return a.equals(expected) || b.equals(expected);
    }
    

    Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.

提交回复
热议问题