The MusicDownloads problem from the 2013 AP Computer Science Exam is typical of free response problems that test lists.

MusicDownloads is #1 from the from the 2013 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/digitalServices/pdf/ap/apcentral/ap13_frq_comp_sci.pdf

Part (a) getDownloadInfo method

public DownloadInfo getDownloadInfo(String title)
{
    for(DownloadInfo info : downloadList)
        if(title.equals(info.getTitle()))
            return info;

    return null;
}

Finding a matching element requires a simple traversal of downloadList. An enhanced for loop is appropriate since it is not necessary to access multiple elements, add elements, remove elements or determine the index of elements.

On the free response, when in doubt, use a regular loop (for or while). See Enhanced for loop exercises for information on when enhanced for loops are appropriate, and to practice with them.

Since the matching is to be done by title, the getTitle method of each DownloadInfo object must be run. String objects must be compared using the equals method. See Strings on the AP CS A Exam for an explanation of String methods used on the AP CS A Exam.

Returning immediately upon finding a matching element (as opposed to storing the element and returning later) reduces the chance of an error. The method returns null, at the end, if no matching element was found.

Part (b) updateDownloads method

public void updateDownloads(List<String> titles)
{
    for(String title : titles)
    {
        DownloadInfo info = getDownloadInfo(title);

        if(info != null)
            info.incrementTimesDownloaded();
        else
            downloadList.add(new DownloadInfo(title));
    }
}

The method from Part (a) can be used to find the DownloadInfo object that matches a given title. If the return value of getDownloadInfo is anything other than null, incrementTimesDownloaded must be run on the object. If the return value is null a new DownloadInfo object must be constructed and added to the downloadList.

An enhanced for loop makes it easy to perform the required operation for each String in titles.

Storing the value returned by getDownloadInfo eliminates the need to run the method multiple times.

2013 AP CS Exam Free Response Solutions

Additional resources for ArrayList objects

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on MusicDownloads