如何检查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屋!
查看全文