labs / tiddlers / content / labs / lab04 / _Labs_04_Duplicate Categories &

You might have noticed that you have a bug in your system that causes duplicate categories to appear in the comboboxes. To test this, add two products with the same category and then check what appears in the combobox.

The fix here is easy. Instead of using an ArrayList to hold the categories we should be using a HashSet. Sets are collections that will only allow unique objects. If you try to add another object with the same value (as determined by the equals method) the add method will not add the new object. This was discussed in lecture 5.

Change all of the collections (including the collection that stores the products) in your DAO class from ArrayList to HashSet. As a general rule, you should be using HashSet as your default collection class rather than ArrayList since there are also some performance advantages in addition to enforcing uniqueness (refer to lecture 5).

If you have been following the principle of 'programming to an interface' (see INFO202 lecture 1, slide 14; and INFO201 lecture 12, slides 14 to 17) this will be nice and easy. If not then you have made life harder for yourself since you will also need to change all of your declarations and your method return types. You should be using Collection in the declaration. For example:

Collection<Product> products = new HashSet<>();

The method return types should also use Collection. For example:

public Collection<Product> getProducts() {
   return products;