MusicDownloads free response answer 2

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.

http://media.collegeboard.com/digitalServices/pdf/ap/apcentral/ap13_frq_comp_sci.pdf

MusicDownloads Part (a): getDownloadInfo

    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. A foreach loop is appropriate since it is not necessary to access multiple elements, add elements, remove elements or determine the index of an element.

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.

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

MusicDownloads Part (b): updateDownloads

    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.

A foreach 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.

Get AP CS Help

2013 AP CS Exam Free Response Solutions

Similar Past AP CS Exam Free Response Solutions

2 thoughts on “MusicDownloads free response answer

  1. Reply D. Murray Mar 4,2016 12:59 pm

    We are able to assume that an increment applied to the returned object “info” will be reflected in the actual downloadList? I am having trouble seeing that Part B does exactly what it is supposed to.
    Is it because the object’s void method “incrementTimesDownloaded” will cause the element in the ArrayList to update even though the copy of the object is now not associated with the List??

    • Reply Brandon Horn Mar 6,2016 9:02 am

      info isn’t an object, it’s a reference to an object. Both info and the list refer to the same DownloadInfo object. info.incrementTimesDownloaded() runs a method on the object to which info refers, not on info itself.

Leave a Reply