10

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

6 Answers 6

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Well this doesn't work. Try it with the OP's values. It returns -1.
Great catch. fixed. The initialization will need to be with Character.
3

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.

Comments

3

Something along the lines may do the trick:

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

Trying to avoid a manual loop :p

2 Comments

Why not just use Arrays.asList(array).indexOf('D');?
@st0le you should make that an answer. It's the best solution to the problem!
2

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.

1 Comment

+1. new String(modifiers).indexOf('D') is a pretty concise way to do this.
2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.