這期內容當中小編將會給大家帶來有關java判斷數組是否包含指定元素的方法,以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
檢查數組是否包含某個值的方法
1、使用Set
public static boolean useSet(String[] arr, String targetValue) { Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue); }
2、使用List
public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); }
3、使用循環判斷
public static boolean useLoop(String[] arr, String targetValue) { for(String s: arr){ if(s.equals(targetValue)) return true; } return false; }
4、使用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; }
5、使用Apache Commons類庫中的ArrayUtils
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0) {
return true;
}else {
return false;
}
}
上述就是小編為大家分享的java判斷數組是否包含指定元素的方法了,如果您也有類似的疑惑,不妨參照上述方法進行嘗試。如果想了解更多相關內容,請關注億速云行業資訊。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。