java—如何将单个元素与集合或列表中的任何元素进行比较

mdfafbf1  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(468)

这个问题在这里已经有答案了

是否可以检查一个字符是否与一个可能性列表匹配(4个答案)
将一个字符与多个字符进行比较(6个答案)
有没有一种更简单的方法来检查if语句中的多个值和一个值(12个答案)
在if语句中格式化多个“or”条件的最佳方法(java)(7个答案)
一年前关门了。

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

String aWord = "any word";

if(aWord.charAt(0) == 'a' || aWord.charAt(0) == 'e' ) {
//As you can see, this will be very messy by the time I get round to the last vowel.
}

if(aWord.charAt(0) == vowels) {
//This is illegal, is there a way to accomplish what I'm trying to get at?
}

在上述代码中是不言自明的。感谢您的帮助,谢谢!

unftdfkk

unftdfkk1#

对于array no,没有直接的方法,但是 Collection.contains() 对。
例如 Set :

Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
//...
if(vowels.contains(aWord.charAt(0)) {
   // ...
}

相关问题