Complete the Specimen free response before reviewing the solution.

Review the Specimen solution with AP CS Tutor Brandon Horn.

handleNewSpecimen method

public static Specimen handleNewSpecimen(
        ArrayList<Specimen> specList, Specimen newSpec)
{
    for(int i = 0; i < specList.size(); i++)
    {
        Specimen curSpec = specList.get(i);
        
        if(newSpec.material().equals(curSpec.material()))
        {
            if(newSpec.quality() > curSpec.quality())
                return specList.set(i, newSpec);
            else
                return null;
        }
    }
    
    int i = 0;
    
    while(i < specList.size() &&
            newSpec.material().compareTo(specList.get(i).material()) > 0)
    {
        i++;
    }
    
    specList.add(i, newSpec);
    return null;
}

The first loop handles the case in which a specimen with the same material as newSpec is in specList. A regular for loop is appropriate because the index of the matching specimen is needed for the call to set.

The ArrayList method set returns the element formerly at the specified position. This is the same value that handleNewSpecimen returns. There is no need to call get prior to calling set.

The problem description states that no 2 elements in specList have the same material. If a specimen in specList with the same material as newSpec is found, the method returns regardless of whether newSpec is placed into specList. The method returns null if the quality of newSpec is less than or equal to the quality of the specimen in the list.

When a return statement executes, the entire method ends. If execution continues past the first loop, there is no element in specList with the same material as newSpec.

The code after the first loop is the standard algorithm for insertion into a sorted list.

Handling the case in which a specimen in specList has the same material as newSpec first enables the use of standard algorithms. The first for loop is a standard sequential search that is easy to write without error.

Handling both cases within the same loop is possible; however, the resulting code is more complex and error prone.

Comments

Comment on Specimen free response