具有多重比较的更清洁的 if 语句 [英] A cleaner if statement with multiple comparisons
问题描述
当你有很多术语时,下面的语句看起来很混乱:
The following statement just looks very messy when you have a lot of terms:
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
是否有更简洁的方法来执行相同的操作,我希望我的代码尽可能具有可读性.
Is there a cleaner way of performing the same action, I would like my code to be as readable as possible.
注意:x、y 和 z 只是任何长度的任何字符串的占位符.在 if 条件中,这里可能有 20 个可变长度的字符串术语,每个术语都被 OR'd 在一起
NOTE: x, y and z are just placeholders for any string of any length. There could be 20 string terms here of variable length in if condition each being OR'd together
推荐答案
Set<String> stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
if(stuff.contains(a)) {
//stuff
}
如果这是一个紧密循环,您可以使用静态 Set.
If this is a tight loop you can use a static Set.
static Set<String> stuff;
static {
stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
}
//Somewhere else in the cosmos
if(stuff.contains(a)) {
//stuff
}
如果您想在不看的时候更加确定没有任何修改.
And if you want to be extra sure nothing is getting modified while you're not looking.
Set<String> test = Collections.unmodifiableSet(new HashSet<String>() {
{
add("x");
add("y");
add("z");
}
});
如果您只想为一些硬编码条件获得一些逻辑,那么 switch 或 if 语句之一与换行符解决方案可能会更好.但是,如果您有很多条件,那么最好将您的配置与逻辑分开.
If you just want to get some logic in there for a handful of hard coded conditions then one of the switch or if statement with newlines solutions might be better. But if you have a lot of conditions then it might be good to separate your configuration from logic.
这篇关于具有多重比较的更清洁的 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!