How can I find an index of a certain value in a Java array of type int?
I tried using Arrays.binarySearch on my unsorted array, it only som
The easiest way is to iterate. For example we want to find the minimum value of array and it's index:
public static Pair getMinimumAndIndex(int[] array) {
int min = array[0];
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
index = i;
}
return new Pair;
This way you test all array values and if some of them is minimum you also know minimums index. It can work the same with searching some value:
public static int indexOfNumber(int[] array) {
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 77) { // here you pass some value for example 77
index = i;
}
}
return index;
}