四种不同方式检查数组是否包含某个值:
1:普通单遍历
2:List
3:Set
public static boolean Loop_1(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
}
public static boolean useList_2(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
public static boolean useSet_3(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
定义一个1000长度的数组测试结果如下:
useLoop:88ns useList: 137ns useSet: 2177ns