数组索引打印错误值

时间:2015-12-08 10:15:32

标签: 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);
    }   
}

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

-1 and 5

最大值返回正常,但不确定索引有什么问题。这实际上应该打印2,但它正在打印-1,请告诉我哪里出错了,我该如何解决这个问题。

Thankd

4 个答案:

答案 0 :(得分: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;
        }
    }

Arrays.asList(num).indexOf(maxValue);返回-1的原因是一个基元数组被Arrays.asList转换为单个元素的List(数组本身),而{ {1}}不包含List(它只包含原始数组)。

答案 1 :(得分: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);
    }

<强>输出

2 and 5

以下是@Eran所指的内容。

它被转换为List size 1,包含一个元素(数组本身)。

根据Javadoc, indexOf

  

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

因此,它会搜索maxValue inside Listnot inside array stored in 0th index of List

enter image description here

答案 2 :(得分:4)

每个人都给出了很好的提示,但没有人详细解释为什么它不起作用。

Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH); if (month == 0) { do something } else if (month == 1) { do something } 使用签名Arrays.asList()定义,该签名包含可变数量的对象或仅包含对象数组。

但是,public static <T> List<T> asList(T... a)是基本类型而不是对象类型。所以int不被解释为“取这个数组”,而是“把这个对象当作一个对象”。结果是Arrays.asList(num),其中找不到给定的数字(当然)。

因此,最好在搜索最大值时保留索引,正如其他答案已经建议的那样。

答案 3 :(得分:1)

以上答案是正确的,但您也可以

import java.util.Arrays;

public class Cook {

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

    public static void getMaxValue(Integer[] num) {
        int maxValue = Arrays.asList(num).get(0);
        int getMaxIndex = 0;
        for (int i = 1; i < num.length; i++) {
            if (Arrays.asList(num).get(i) > maxValue) {
                maxValue = Arrays.asList(num).get(i);
            }
        }
        getMaxIndex = Arrays.asList(num).indexOf(maxValue);
        System.out.println(getMaxIndex + " and " +maxValue);
    }
}
相关问题