I have an array with some integers in it. I want to check if a given integer is in it or not. Other than using a for loop to check one by one is there a way using indexOf method in java? [ -1 if not in it, else the index]
1 Answer
There is no indexOf method on arrays in Java. Your main options are:
- write the method (for example using a for loop)
- sort the array and use
Arrays.binarySearch(array, number) - use a collection, such as a
HashSet<Integer>and thecontainsmethod.
7 Comments
T.J. Crowder
Surely
binarySearch would fail on two separate Integer instances for the same underlying value?assylias
@T.J.Crowder If it's an
int[] (which is my understanding), then there's no problem. If it's an Integer[], the contract is "If the array contains multiple elements equal to the specified object, there is no guarantee which one will be found.", so it should still return a value that is >=0.T.J. Crowder
For some reason I read it as an array of
Integer. But it's an issue with the question, not your answer; you can read "I got a array with some integers in it." either way. :-)assylias
@SabareeshAP Define "smoother" !
|