有没有更简单的方法来检查if语句中的一个值的多个值? [英] Is there a simpler way to check multiple values against one value in an if-statement?

查看:113
本文介绍了有没有更简单的方法来检查if语句中的一个值的多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想要做的是检查一个给定值的两个整数,因此,通常你会做的是这样的:

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 values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);

//the actual thing in question
if(a == 0 || b == 0)
{
//Then do something
}

但是有更简洁的格式吗?可能与此类似(返回错误的操作数类型):

But is there a more concise format to do this? Possibly similar to this (which returns a bad operand type):

//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);

//the actual thing in question
if((a||b) == 0)
{
//Then do something
}


推荐答案

不幸的是,Java中没有这样的构造。

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)) {
    // ...
}

如果您不想将yourselft限制为整数,可以将上述函数设为通用:

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

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

请注意,在这种情况下,Java运行时将执行自动装箱和拆箱用于原始类型(如 int ),这是性能损失。

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

这篇关于有没有更简单的方法来检查if语句中的一个值的多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆