在 if 语句中格式化多个“或"条件的最佳方法 [英] Best way to format multiple 'or' conditions in an if statement
问题描述
我有一个带有许多条件的 if 语句(必须检查 10 或 15 个常量以查看其中是否存在.)
I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)
而不是像这样写:
if (x == 12 || x == 16 || x == 19 || ...)
有什么方法可以格式化它
is there any way to format it like
if x is [12, 16, 19]?
只是想知道是否有更简单的方法来编码,任何帮助表示赞赏.
Just wondering if there is an easier way to code this, any help appreciated.
答案非常有帮助,但有些人要求我添加更多细节,所以我会这样做以满足他们的好奇心.我正在制作一个日期验证类,需要确保天数不 >在只有 30 天的月份中有 30 天(我认为有 4 天),我正在写一个 if 语句来检查这样的事情:
The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:
if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
我只是想知道是否有更快的方法来编写这样的代码 - 下面的许多答案都有帮助.
I was just wondering if there was a faster way to code things like that - many of the answers below have helped.
推荐答案
我经常使用这种模式.它非常紧凑:
I use this kind of pattern often. It's very compact:
// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));
// In your method:
if (values.contains(x)) {
...
}
此处使用 HashSet
以提供良好的查找性能 - 即使非常大的哈希集也能够非常快速地执行 contains()
.
A HashSet
is used here to give good look-up performance - even very large hash sets are able to execute contains()
extremely quickly.
如果性能不重要,你可以把它的要点写成一行:
If performance is not important, you can code the gist of it into one line:
if (Arrays.asList(12, 16, 19).contains(x))
但要知道它每次执行时都会创建一个新的ArrayList
.
but know that it will create a new ArrayList
every time it executes.
这篇关于在 if 语句中格式化多个“或"条件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!