1、使用List:
1 2 3 |
public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); } |
2、使用Set:
1 2 3 4 |
public static boolean useSet(String[] arr, String targetValue) { Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue); } |
3、使用一个简单循环:
1 2 3 4 5 6 7 |
public static boolean useLoop(String[] arr, String targetValue) { for(String s: arr){ if(s.equals(targetValue)) return true; } return false; } |
4、使用Arrays.binarySearch():
注:下面的代码是错误的,这样写出来仅仅为了理解方便。binarySearch()只能用于已排好序的数组中。所以,你会发现下面结果很奇怪。
1 2 3 4 5 6 7 8 |
public static boolean useArraysBinarySearch(String[] arr, String targetValue) { // Arrays.sort(arr); // 首先对数组排序 int a = Arrays.binarySearch(arr, targetValue); if(a > 0) return true; else return false; } |
暂无评论