在if语句中格式化多个'或'条件的最佳方法(Java) [英] Best way to format multiple 'or' conditions in an if statement (Java)
问题描述
一个简单的问题,但谷歌没有多少帮助。
A simple question but Google hasn't been helping much.
我有一个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.)
而不是写下这样的东西:
Instead of writing something like:
if (x == 12 || x == 16 || x == 19 || ...)
有没有办法格式化它像
if x is [12, 16, 19]?
只是想知道是否有更简单的方法对此进行编码,任何帮助都会受到赞赏。
Just wondering if there is an easier way to code this, any help appreciated.
编辑:答案非常有用,但有人要求我添加更多细节,以便满足他们的好奇心。我正在制作一个日期验证课程,需要确保在仅有30天的时间里天数不超过30天(其中有4天,我认为)并且我正在写一个if语句来检查这样的事情:
Edit: 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语句中格式化多个'或'条件的最佳方法(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!