如何检查 ArrayList 是否包含 2 个值? [英] How to Check if an ArrayList Contain 2 values?
本文介绍了如何检查 ArrayList 是否包含 2 个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以检查集合是否包含一个或多个值,其性能比使用 contains 循环两次更好吗?
is there any way to check if a collection contain a value or more with better performance than looping twice with contains?
换句话说就是看起来像这样的东西
in other meaning something that would look like this
person.contains("Joe" || "Jasha");
推荐答案
ArrayList.contains()
的实现循环遍历每个元素并进行 equals()
测试,所以调用 .contains()
两次效率低下.
The implementation of ArrayList.contains()
loops through every element and does an equals()
test, so calling .contains()
twice is inefficient.
您可以编写自己的循环,使用已编译的正则表达式同时检查两者 模式同时查找任一名称:
You could write your own loop that check both at once using a compiled regex Pattern that looks for either name at the same time:
Pattern p = Pattern.compile("Joe|Jasha");
boolean found = false;
for (String s : person) {
if (p.matcher(s).find()) {
found = true;
break;
}
}
这篇关于如何检查 ArrayList 是否包含 2 个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文