Search code examples
javaforeachhashsettop-n

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


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

Solution

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