数组索引打印错误值

use*_*094 5 java

我有以下Java代码.

import java.util.Arrays;

public class Cook {
    public static void main(String[] args) {
        int num[] = { 3, 1, 5, 2, 4 };
        getMaxValue(num);
    }

    public static void getMaxValue(int[] num) {
        int maxValue = num[0];
        int getMaxIndex = 0;
        for (int i = 1; i < num.length; i++) {
            if (num[i] > maxValue) {
                maxValue = num[i];
            }
        }
        getMaxIndex = Arrays.asList(num).indexOf(maxValue);
        System.out.println(getMaxIndex + " and " +maxValue);
    }   
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我试图检索数组中的最大值以及它的索引,但这里我得到的输出是

-1 and 5
Run Code Online (Sandbox Code Playgroud)

最大值返回正常,但不确定索引有什么问题.这应该打印2,但它是打印-1,请让我知道我哪里出错了,我该如何解决这个问题.

Thankd

Era*_*ran 21

您应该更新循环中的最大索引:

    int maxValue = num[0];
    int getMaxIndex = 0;
    for (int i = 1; i < num.length; i++) {
        if (num[i] > maxValue) {
            maxValue = num[i];
            getMaxIndex = i;
        }
    }
Run Code Online (Sandbox Code Playgroud)

其原因Arrays.asList(num).indexOf(maxValue);返回-1是,基元的阵列被转换Arrays.asListList一个单一元件(数组本身)的,并且List不包含maxValue(它仅包含原始数组).


Ank*_*hal 6

需要在迭代时更新索引, getMaxIndex = i;

public static void getMaxValue(int[] num) {
        int maxValue = num[0];
        int getMaxIndex = 0;
        for (int i = 1; i < num.length; i++) {
            if (num[i] > maxValue) {
                maxValue = num[i];
                getMaxIndex = i;
            }
        }
        System.out.println(getMaxIndex + " and " + maxValue);
    }
Run Code Online (Sandbox Code Playgroud)

产量

2 and 5
Run Code Online (Sandbox Code Playgroud)

以下是@Eran所指的内容.

它被转换到Listsize 1,包含单元素(数组本身).

按照Javadoc,indexOf

返回此列表中第一次出现的指定元素的索引,如果此列表不包含该元素,则返回-1.

所以它搜索maxValue inside Listnot inside array stored in 0th index of List.

在此输入图像描述