【发布时间】:2017-12-31 05:12:28
【问题描述】:
我正在尝试返回ArrayList<Integer> 的最大值的第一个索引。下面的代码找到第二个最大值而不是第一个最大值。如何返回循环遇到的第一个最大值?
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;
}
返回的是 'test. 3'。但它应该是字母“a”的第一个最大值,即 3。
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
【问题讨论】:
-
您将什么定义为循环中的第一个最大值?
-
您只需为此使用
HashMap,如here所示。
标签: java for-loop arraylist integer max