How to Check if an ArrayList Contain 2 values?

前端 未结 6 1327
忘掉有多难
忘掉有多难 2021-01-19 09:34

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 loo

6条回答
  •  渐次进展
    2021-01-19 10:25

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

提交回复
热议问题