-1

I need to assess the last int in an array where a certain conditional is met. My program can work out what that int is, but it needs to also know where it's position was in the array. I searched on stack-exchange and someone posted this:

Arrays.asList(array).indexOf(indexPos);

As a possible solution, but I am not sure if I am doing it right, because I get the error cannot find symbol. I also allowed:

int test = Arrays.asList(array).indexOf(indexPos);

And then tried to print test, but I could not even get to that point. Thanks.

entropy
  • 169
  • 3
  • 13

3 Answers3

1

You may need to import java.util.Arrays to get the symbol.

There is no guaranteed way of finding the position of an element in an array except for looping over the array - that is basically what your asList snippets are doing.

This will work as long as your arrays don't have duplicate values. If you need to handle duplicate values, you may need to rethink you data structs.

John3136
  • 28,809
  • 4
  • 51
  • 69
0

Someone posted a similar question that someone else asked. It seems that this has worked for me.

The Code is:

java.util.Arrays.asList(seq).indexOf(indexPos);

and the Question:Where is Java's Array indexOf?

Community
  • 1
  • 1
entropy
  • 169
  • 3
  • 13
0

Yes you have the method defined in List interface. So you need to use asList() function followed by indexOf() function.

If the array is not sorted you can use java.util.Arrays.asList(theArray).indexOf(o) If the array is sorted, you can make use of a binary search function(improves performance) java.util.Arrays.binarySearch(theArray, o)

As for the error make sure you have imported java.util.Arrays. Also that you have defined Array seq and int indexPos which makes your code int test = Arrays.asList(seq).indexOf(indexPos);.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289