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
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).
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.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With