开发者

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开发者_如何学运维


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');


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.


Something along the lines may do the trick:

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

Trying to avoid a manual loop :p


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜