在Java中,判断一个数是否在数组中,可以通过以下几种方法:
使用`Arrays.asList`方法
Integer[] arr = {1, 2, 3};
int a = 2;
System.out.println(Arrays.asList(arr).contains(a));
使用`List.contains`方法
String[] strArr = {"a1", "b1", "c1"};
String str = "c1";
List
list = Arrays.asList(strArr); boolean result = list.contains(str);
System.out.println(result);
使用`Stream.anyMatch`方法 (Java 8及以上版本):int[] arr = {5, 1, 1, 9, 7, 2, 6, 10};
int toCheckValue = 7;
boolean test = Arrays.stream(arr).anyMatch(element -> element == toCheckValue);
System.out.println("Is " + toCheckValue + " present in the array: " + test);
使用`for`循环进行线性搜索
int[] arr = {5, 1, 1, 9, 7, 2, 6, 10};
int toCheckValue = 7;
boolean test = Arrays.stream(arr).anyMatch(element -> element == toCheckValue);
System.out.println("Is " + toCheckValue + " present in the array: " + test);
```java
int[] arr = {5, 1, 1, 9, 7, 2, 6, 10};
int toCheckValue = 7;
boolean test = false;
for (int element : arr) {
if (element == toCheckValue) {
test = true;
break;
}
}
System.out.println("Is " + toCheckValue + " present in the array: " + test);
```
使用`Arrays.binarySearch`方法(数组需要是有序的):
int[] arr = {1, 2, 3, 4, 5};
int toCheckValue = 3;
int index = Arrays.binarySearch(arr, toCheckValue);
boolean test = index >= 0;
System.out.println("Is " + toCheckValue + " present in the array: " + test);
选择哪种方法取决于你的具体需求,例如是否需要修改数组、数组的类型以及是否关心性能。如果数组很大,使用`Stream.anyMatch`方法可能更加高效,因为它可以利用并行处理。如果数组是有序的,`Arrays.binarySearch`方法可以提供对数时间复杂度的搜索。如果需要频繁修改数组,使用`List`可能更加方便
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/113840.html