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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将单个元素与集合或列表中的任何元素进行比较[重复]相关的知识,希望对你有一定的参考价值。

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?
}

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

答案

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

例如,使用Set

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

以上是关于如何将单个元素与集合或列表中的任何元素进行比较[重复]的主要内容,如果未能解决你的问题,请参考以下文章