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]

Thom
  • 14,013
  • 25
  • 105
  • 185

1 Answers1

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.
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Surely `binarySearch` would fail on two separate `Integer` instances for the same underlying value? – T.J. Crowder Jul 24 '18 at 11:01
  • @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`. – assylias Jul 24 '18 at 11:03
  • 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. :-) – T.J. Crowder Jul 24 '18 at 11:05
  • Which method is smoother ? using `for` loop or using `Arrays.binarySearch(array, number)` –  Jul 24 '18 at 11:14
  • @SabareeshAP Define "smoother" ! – assylias Jul 24 '18 at 11:16
  • the one works faster when there is too many integers in an array to check. ¯\_(ツ)_/¯ –  Jul 24 '18 at 11:19
  • @SabareeshAP It depends how many numbers you have and how often you call the method. If you only need to check that one number is present, then use a for loop. If you need to check a few numbers, and the array is small (say < 1000 numbers), I'd probably use binary search. If the array is larger or you need to check the presence of many numbers, I'd use a Set. In the end, the best way to get your answer is to benchmark each option and check which is better for your specific use case. – assylias Jul 24 '18 at 11:22