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?
Asked
Active
Viewed 1.5k times
-1
-
Ohh! -1 on my question with no comment? Must be on StackOverflow.com – EGHDK Dec 06 '12 at 04:13
-
using for loop doesn't look such an overkill to me, you can also use collections like ArrayList for example and use `contains()` method but I think internally it has to apply a single loop (but it'll make your code simpler and compact) – vishal_aim Dec 06 '12 at 04:16
-
1Similar question here: http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value – tuga Dec 06 '12 at 04:22
-
1*Do you really think is there a way to identify whether a number exists in an array or not without traversing... All you can do is shorten the syntax but the work will always be the same!!!* – Bharat Sinha Dec 06 '12 at 05:56
-
Crazier things have happened. `Arrays.asList(...).contains(...)` works. And I never write the code for traversing through the array. It's just that it doesn't work for int's apparently. – EGHDK Dec 06 '12 at 18:41
4 Answers
4
You can use the Arrays utility class and its simple BinarySearch algorithm:
Arrays.sort(array); // must sort before next line
boolean found = Arrays.binarySearch(array, someValue) > -1;

Tasawar Hussain
- 650
- 7
- 21

Bohemian
- 412,405
- 93
- 575
- 722
2
If you still want to traverse the array without using Lists, you can use this basic structure of for loops:
boolean validInput = false;
for (int i = 0; i < account_numbers.length; i++) {
if (account_numbers[i] == userInput) {
validInput = true;
break;
}
}

Matthew Diana
- 1,106
- 7
- 14
1
The simplest way is to convert the array into a list and use contains
method as below:
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
}

Yogendra Singh
- 33,927
- 6
- 63
- 73
-
-
While that's certainly a very Java thing to do ... all it's going to do internally after wasting time copying the array and creating objects is a simple O(n) linear search which a simple `for` loop would solve. If you're set on using arrays, of course. – Brian Roach Dec 06 '12 at 05:41
0
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);

Abhijeet Warik
- 1
- 2