17

Is there anyway to get indexOf like you would get in a string.

output.add("1 2 3 4 5 6 7 8 9 10);  
String bigger[] = output.get(i).split(" ");
int biggerWher = bigger.indexOf("10");

I wrote this code but its returning an error and not compiling! Any advice ?

chuck finley
  • 459
  • 3
  • 8
  • 16

6 Answers6

62

Use this ...

output.add("1 2 3 4 5 6 7 8 9 10");  
String bigger[] = output.get(i).split(" ");
int biggerWher = Arrays.asList(bigger).indexOf("3");
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
  • What are the collateral effects by using asList? Is made a copy of original array on memory? – richardaum Jun 13 '14 at 17:27
  • @Richard: It will create a new ArrayList object and converts from the String array, I'd guess 3-5 times the amount of memory than before. public static List asList(T... array) { return new ArrayList(array); } – John Dec 18 '14 at 03:38
13

When the array is an array of objects, then:

Object[] array = ..
Arrays.asList(array).indexOf(someObj);

Another alternative is org.apache.commons.lang.ArrayUtils.indexOf(...) which also has overloads for arrays of primitive types, as well as a 3 argument version that takes a starting offset. (The Apache version should be more efficient because they don't entail creating a temporary List instance.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
4

Arrays do not have an indexOf() method; however, java.util.List does. So you can wrap your array in a list and use the List methods (except for add() and the like):

output.add("1 2 3 4 5 6 7 8 9 10");  
String bigger[] = output.get(i).split(" ");
int biggerWhere = Arrays.asList(bigger).indexOf("10");
Be Kind To New Users
  • 9,672
  • 13
  • 78
  • 125
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
3

You can use java.util.Arrays.binarySearch(array, item); That will give you an index of the item, if any...

Please note, however, that the array needs to be sorted before searching.

Regards

Andrew
  • 2,663
  • 6
  • 28
  • 50
2

There is no direct indexOf method in Java arrays.

abhishek58g
  • 145
  • 4
0
output.add("1 2 3 4 5 6 7 8 9 10");

you miss a " after 10.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
ChandlerSong
  • 387
  • 1
  • 14