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 ?

3
  • 2
    Hope you have specific programming language? Commented Jun 6, 2011 at 8:45
  • Looks like Java to me... Commented Jun 6, 2011 at 8:46
  • possible duplicate of Where is Java's Array indexOf? Commented Jun 6, 2011 at 9:20

6 Answers 6

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");
Sign up to request clarification or add additional context in comments.

2 Comments

What are the collateral effects by using asList? Is made a copy of original array on memory?
@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 <T> List<T> asList(T... array) { return new ArrayList<T>(array); }
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.)

3 Comments

Why do I keep forgetting that most collection-methods apply to arrays too by using asList.... +1
What are the collateral effects by using asList? Is made a copy of original array on memory?
@Richard - No copy is made. The 'asList' List is a wrapper for the original array. Read the javadocs!!
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");

Comments

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

Comments

2

There is no direct indexOf method in Java arrays.

Comments

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

you miss a " after 10.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.