有 4 种方法
1. 使用 List
123 | public static boolean useList(String[] arr, String targetValue) {return Arrays.asList(arr).contains(targetValue);} |
---|
2. 使用 Set
1234 | public static boolean useSet(String[] arr, String targetValue) {Set<String> set = new HashSet<String>(Arrays.asList(arr));return set.contains(targetValue);} |
---|
3. 使用简单的循环
Java
public static boolean useLoop(String[] arr, String targetValue) { for(String s: arr){ if(s.equals(targetValue)) return true; } return false; }
1234567 | public static boolean useLoop(String[] arr, String targetValue) {for(String s: arr){if(s.equals(targetValue))return true;}return false;} |
---|
4. 使用 Arrays.binarySearch
binarySearch 使用的时候,必须确保数组是有序的。
1234567 | public static boolean useArraysBinarySearch(String[] arr, String targetValue) {int a = Arrays.binarySearch(arr, targetValue);if(a > 0)return true;elsereturn false;} |
---|
4 种方法,经过测试。(测试用例:略)
在数组无序的情况下,性能最佳的就是使用循环,比采用集合方式好,毕竟,采用集合的方式还得把数组放入集合。
如果数组是有序的,则使用 Arrays.binarySearch() 是最佳的方法。
参考资料:https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/