ACSA Exam Prep
← All free-response questions
Question 3 · Data Analysis with ArrayList · 5 points

Inventory Merge

A store's stock is kept in an ArrayList of Item objects. Because of a data-entry problem, the same product can appear more than once.

public class Item
{
    /** Returns the product name */
    public String getName()
    { /* implementation not shown */ }

    /** Returns the number in stock */
    public int getCount()
    { /* implementation not shown */ }

    /** Adds amount to the number in stock */
    public void addCount(int amount)
    { /* implementation not shown */ }

    // There may be instance variables, constructors,
    // and methods that are not shown.
}

public class Inventory
{
    /** The items in stock; never null */
    private ArrayList<Item> items;

    /** Combines items with the same name, as described below,
     *  and returns the number of items removed from the list.
     */
    public int mergeDuplicates()
    { /* to be implemented */ }

    // There may be instance variables, constructors,
    // and methods that are not shown.
}

Your class

5 points

Write mergeDuplicates. For each name, keep only the first Item with that name. Add the count of every later item with the same name to that first item, then remove the later item. Return how many items were removed.

If items is [(pen, 4), (ink, 2), (pen, 3), (cap, 1), (pen, 1), (ink, 5)], then mergeDuplicates() returns 3 and items becomes [(pen, 8), (ink, 7), (cap, 1)].

Tab inserts spaces. Drafts save as you type.
Self-score
0 / 5