Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/** * Remove from the club\'s collection all members who * joined in the given m

ID: 3629877 • Letter: #

Question

/**
     * Remove from the club's collection all members who
     * joined in the given month and year, and return
     * them stored in a seperate collection object...
     * @param month is the month of the Membership..
     * @param year is the year of the Membership...
     * @retrun the members who joined in a given month and year...
     */
    public ArrayList<Membership> purge(int month, int year)
    {
        ArrayList<Membership> purged = new ArrayList<Membership>();
      
        if(month < 1 || month > 12)
        {
            System.out.println("Month " + month + " out of range. Must be in the range 1 ... 12");
        }
       
        for(Membership member : members) // THE ERROR HAPPENS HERE!!!
        {
            if((member.getMonth() == month) && (member.getYear() == year))
            {
                members.remove(member);
                purged.add(member);
            }
        }
        return purged;
    }

Explanation / Answer

You can't iterate through the list at the same time that you're removing elements from it. The iterator tries to iterate through elements that aren't there.

public ArrayList<Membership> purge(int month, int year)
{
ArrayList<Membership> purged = new ArrayList<Membership>();

if(month < 1 || month > 12)
{
System.out.println("Month " + month + " out of range. Must be in the range 1 ... 12");
return null;
}

int idx = 0;

while(idx < members.size())
{
if((member.getMonth() == month) && (member.getYear() == year))
{
members.remove(member);
purged.add(member);
// don't increment idx here, you're removing an element
}
else
{
// if no element is removed, you must increment idx to check next element
idx++;
}
}
return purged;
}