AVi
AVi

Reputation: 101

Element position in array

I have an array:

char[] modifiers = {'A', 'M', 'D'};

and a variable:

char a = 'D'

How to get position of variable value in array?

Thanks

Upvotes: 10

Views: 60860

Answers (6)

This is very simple and tested code for your reference

String[] arrayValue = {"test","test1","test2"};
int position = Arrays.asList(arrayValue).indexOf("test");

position: 0th Position

Upvotes: 2

st0le
st0le

Reputation: 33575

This is the shortest way I know. I had this as a comment but now writing it as an answer. Cheers!

Character[] array = {'A','B','D'};

Arrays.asList(array).indexOf('D');

Upvotes: 11

President James K. Polk
President James K. Polk

Reputation: 42018

You could do it yourself easily enough, you can use the sort() and binarySearch() methods of the java.util.Arrays class, or you can convert the char [] to a String and use the String.indexOf() method.

Upvotes: 2

user166390
user166390

Reputation:

Something along the lines may do the trick:

Collections.indexOfSubList(Arrays.asList(array), Arrays.asList('D'))

Trying to avoid a manual loop :p

Upvotes: 3

khachik
khachik

Reputation: 28703

Iterate through the array and compare its elements to the variable, return the index, if equals. Return -1 if not found. You might want to consider using any implementation of java.util.List.

Upvotes: 0

icyrock.com
icyrock.com

Reputation: 28628

Try:

int pos = -1;
for(int i = 0; i < modifiers.length; i++) {
  if(modifiers[i] == a) {
     pos = i;
     break;
  }
}

This will get the first occurrence of the value in variable pos, if there are multiple ones, or -1 if not found.

Upvotes: 3

Related Questions