为什么在Java中的”for each”循环不访问最后一个元素?

huangapple go评论77阅读模式
英文:

Why does for each loop in java does not access the last element?

问题

我正在尝试迭代整数哈希集,以找到前两个最大的元素。我的第二个最大元素位于哈希集的末尾,我刚刚发现foreach循环跳过了最后一个元素。为什么会发生这种情况?

for (int n : set) {
    if (n > max1)
        max1 = n;
    else if (n == max1)
        max2 = n;
    else if (n > max2)
        max2 = n;
}
英文:

I am trying to iterate over an Integer hashset to find the first two greatest elements. My 2nd greatest element is at the end of the hashset and I just discovered that the foreach loop is skipping the last element. Why is this happening?

for(int n:set)
{
    if(n>max1)
        max1=n;
    else if(n==max1)
        max2=n;
    else if(n>max2)
        max2=n;
}

答案1

得分: 1

问题不在于循环,而在于您在每次迭代中没有正确更新 max1max2

for(int n : set) {
    if (n > max1) {
        max2 = max1;
        max1 = n;
    } else if (n > max2) {
        max2 = n;
    }
}

请注意,由于这是一个集合,且值是唯一的,所以不应出现 n 等于 max1max2 的情况。

英文:

The issue isn't the loop, but the fact you aren't properly updating both max1 and max2 in each iteration:

for(int n : set) {
    if (n > max1) {
        max2 = max1;
        max1 = n;
    } else if (n > max2) {
        max2 = n;
    }
}

Note that since it's a set, and the values are unique, there should be no case when n is equal to max1 or max2.

huangapple
  • 本文由 发表于 2020年9月5日 04:22:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63747613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定