未来星开发团队的官网

如何高效检查一个数组中是否包含某个值?


1. public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); }
2. public static boolean useSet(String[] arr, String targetValue) {
    Set<String> set = new HashSet<String>(Arrays.asList(arr));
    return set.contains(targetValue);
}
3. public static boolean useLoop(String[] arr, String targetValue) {
    for (String s : arr) {
        if (s.equals(targetValue)) {
            return true;
        }
    }
    return false;
}
4。下面的代码是错误。但是,为了这个回答的完整性,还是将其列在这里。binarySearch()方法仅能用于已排序的数组。不过,你将会被下面的结果所震惊。
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
    int a = Arrays.binarySearch(arr, targetValue);
    if (a > 0) {
        return true;
    } else {
        return false;
    }
}
10K的数据
useList:  1678
useSet:  25609
useLoop:  1802
useArrayBinary:  10
 
posted @ 2016-01-11 16:08  费元星的博客  阅读(1000)  评论(0编辑  收藏  举报
未来星开发团队的官网