How to find the index of an element in an int array?

前端 未结 19 1403
南方客
南方客 2020-11-27 02:56

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

19条回答
  •  甜味超标
    2020-11-27 03:11

    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;
        }
    

提交回复
热议问题