Find the index of an element in an int array
While trying to find the index of an element in an int array in an Android project today, weirdly, the index always returned -1.
import java.util.Arrays;
class Demo {
public static void main(String[] args) {
int[] array = {1};
int index = Arrays.asList(array).indexOf(1);
System.out.println(index);
}
}
I modified and tested the code for several times, but the problem is still there. Baffled, I extract the code into the above snippet to further investigate. Still -1, so not related to anything in the Android project. Maybe it's because the int
type? A quick Google search led me to this answer[1]:
Integer[] array = {1,2,3,4,5,6};
Arrays.asList(array).indexOf(4);
After changed int
to Integer
, bingo, that's the problem.