Q:

How to return first max value in a Java ArrayList

I'm trying to return the first index of the max value of an ArrayList<Integer>. The code below finds the second maximum instead of the first. How do I return the first max value encountered by the loop?
public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 0; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > maxIndex) {
            maxIndex = myFreqs.get(k);
        }
    }
    return maxIndex;
}

What gets returned is 'test. 3'. But it should be the first max which is 3 for the letter 'a'.
Number of unique words: 7
1   this
1   is
3   a
3   test.
1   yes
1   test
1   of
The word that occurs most often and its count are: test. 3

A:

You seem to have forgotten to access the element at the maxIndex in your comparison. And you set the index to the value of the element in your if (instead of the index). I think you wanted,
public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 1; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > myFreqs.get(maxIndex)) {
            maxIndex = k;
        }
    }
    return maxIndex;
}

