indexOf in a string array
Asked Answered
T

6

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 ?

Thermo answered 6/6, 2011 at 8:44 Comment(3)
Hope you have specific programming language?Gnotobiotics
Looks like Java to me...Gerrit
possible duplicate of Where is Java's Array indexOf?Toinette
S
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");
Selvage answered 6/6, 2011 at 9:28 Comment(2)
What are the collateral effects by using asList? Is made a copy of original array on memory?Submission
@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); }Guildroy
T
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.)

Toinette answered 6/6, 2011 at 9:18 Comment(3)
Why do I keep forgetting that most collection-methods apply to arrays too by using asList.... +1Gerrit
What are the collateral effects by using asList? Is made a copy of original array on memory?Submission
@Richard - No copy is made. The 'asList' List is a wrapper for the original array. Read the javadocs!!Toinette
N
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");
Nonintervention answered 6/6, 2011 at 9:18 Comment(0)
B
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

Blackcap answered 6/6, 2011 at 9:36 Comment(0)
B
2

There is no direct indexOf method in Java arrays.

Bolen answered 19/10, 2016 at 5:51 Comment(0)
A
0
output.add("1 2 3 4 5 6 7 8 9 10");

you miss a " after 10.

Aphaeresis answered 6/6, 2011 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.