检查数组中是否存在元素 [英] Checking whether an element exist in an array
问题描述
用于检查数组中是否存在元素的简单Java代码:
A simple Java code for checking whether an element exists in an array or not:
import java.util.Arrays;
public class Main {
static int[] numbers = {813, 907, 908, 909, 910};
public static void main(String[] args) {
int number = 907;
//Integer number = 907; // the same thing -- it's not found.
boolean b = Arrays.asList(numbers).contains(number);
System.out.println(b); // => false
}
}
1)为什么不找到907 in数组?
1) Why doesn't it find 907 in the array?
2)如果有更好的方法,请继续分享您的知识。
2) If there is a better way of doing it, go ahead and share your knowledge.
更新:
据说 asList
转换你的 int []
进入列表< int []>
,只有一个成员:原始列表。但是,我希望下面的代码能给我1,但它给了我5:
It was said that asList
converts your int[]
into a List<int[]>
with a single member: the original list. However, I expect the following code to give me 1, but it gives me 5:
System.out.println(Arrays.asList(numbers).size());
推荐答案
问题在于数组.asList(数字)
没有按照你的想法做。它将您的 int []
转换为列表< int []>
,其中包含一个成员:原始列表。
The problem is that Arrays.asList(numbers)
isn't doing what you think. It is converting your int[]
into a List<int[]>
with a single member: the original list.
您可以进行简单的线性搜索,或者如果您的数字
数组始终排序,请使用 Arrays.binarySearch(numbers,907);
并测试结果是否为负(意味着未找到)。
You can do a simple linear search or, if your numbers
array is always sorted, use Arrays.binarySearch(numbers, 907);
and test whether the result is negative (meaning not found).
这篇关于检查数组中是否存在元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!