如何将单个元素与集合或列表中的任何元素进行比较[重复]

问题描述 投票:0回答:1
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?
}

在上面的代码中不言自明。任何帮助表示赞赏,谢谢!

java compare condition
1个回答
0
投票

对于阵列没有你没有直接的方法,但与Collection.contains()是。

例如,使用Set

Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
//...
if(vowels.contains(aWord.charAt(0)) {
   // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.