Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array index printing wrong value

Tags:

java

I've the below Java code.

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

In the above code I'm trying to retrieve the maximum value in the array and also its index, but here the output that I'm getting is

-1 and 5

The max value is returned fine, but not sure of what's wrong with the index. This should actually print 2, but it is printing -1, please let me know where am i going wrong and how can I fix this.

Thankd

like image 545
user3872094 Avatar asked Dec 08 '15 10:12

user3872094


2 Answers

You should update the max index in the loop :

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

The reason Arrays.asList(num).indexOf(maxValue); returns -1 is that an array of primitives is converted by Arrays.asList to a List of a single element (the array itself), and that List doesn't contain maxValue (it only contains the original array).

like image 163
Eran Avatar answered Sep 30 '22 18:09

Eran


Need to update index while iterating, 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);
    }

output

2 and 5

Below is something @Eran is referring to.

It is converted to List of size 1, containing a single element (the array itself).

As per Javadoc,indexOf

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

So it searches for maxValue inside List and not inside array stored in 0th index of List.

enter image description here

like image 33
Ankur Singhal Avatar answered Sep 30 '22 17:09

Ankur Singhal