java 在Java中查找数组中是否存在数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13736814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find if a number exists inside of an array in Java
提问by EGHDK
I have an array of account_numbers. I am taking the input from the user and trying to see if the input exists in the array. I've been trying an if statement with a for loop in the parameters, but I feel like that's overkill. Am I missing something?
我有一组 account_numbers。我正在接受用户的输入并尝试查看输入是否存在于数组中。我一直在尝试在参数中使用 for 循环的 if 语句,但我觉得这太过分了。我错过了什么吗?
回答by Bohemian
You can use the Arrays utility class and its simple BinarySearch algorithm:
您可以使用 Arrays 实用程序类及其简单的 BinarySearch 算法:
Arrays.sort(array); // must sort before next line
boolean found = Arrays.binarySearch(array, someValue) > -1;
回答by Matthew Diana
If you still want to traverse the array without using Lists, you can use this basic structure of for loops:
如果你仍然想在不使用 Lists 的情况下遍历数组,你可以使用 for 循环的这个基本结构:
boolean validInput = false;
for (int i = 0; i < account_numbers.length; i++) {
if (account_numbers[i] == userInput) {
validInput = true;
break;
}
}
回答by Yogendra Singh
The simplest way is to convert the array into a list and use contains
method as below:
最简单的方法是将数组转换为列表并使用contains
如下方法:
Long[] account_numbers = new Long[SIZE];//Your existing array
//get the list from array
List<Long> accountNumbers = Arrays.asList(account_numbers);
//check the desired account exist or not
Long accountToSearch= new Long("12345");
if(accountNumbers.contains(accountToSearch)){
//account exist
}
回答by Abhijeet Warik
Integer arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int a = 7;
boolean isThere = false;
List<E> list = new ArrayList<>();
list.addAll((Collection<? extends E>) Arrays.asList(arr));
// enter array into the list
if (list.contains(a)) {
isThere = true;
}
System.out.println(isThere);