0

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]

0

1 Answer 1

2

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 the contains method.
Sign up to request clarification or add additional context in comments.

7 Comments

Surely binarySearch would fail on two separate Integer instances for the same underlying value?
@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.
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. :-)
Which method is smoother ? using for loop or using Arrays.binarySearch(array, number)
@SabareeshAP Define "smoother" !
|