檢查數組是否包含某個值的方法
使用List
public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); }
使用Set
public static boolean useSet(String[] arr, String targetValue) { Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue); }
使用循環判斷
public static boolean useLoop(String[] arr, String targetValue) { for(String s: arr){ if(s.equals(targetValue)) return true; } return false; }
使用Arrays.binarySearch()
Arrays.binarySearch()方法只能用於有序數組!!!如果數組無序的話得到的結果就會很奇怪。
public static boolean useArraysBinarySearch(String[] arr, String targetValue) { int a = Arrays.binarySearch(arr, targetValue); if(a > 0) return true; else return false; }