Inf1 OP : Lab Sheet Week 7 Q2 - Arrays and Reference Types
Overview

Go back and have a look at Arrays and Reference Types warm up exercise from last week. You will be asked to re-implement it using an ArrayList rather than a standard array.

However, first we will revise how to organise your Java code files into Packages.

Packages

Packages in Java allow classes to be grouped together, and allow classes with the same names to be uniquely identified. For example, within Java there are two different classes with the name List

java.util.List
in the package java.util, is a class specifying the interface of data lists (as implemented by ArrayList).
java.awt.List
in the package java.awt, is a class for displaying lists of items in a user interface.

To use classes in packages you either name them fully, including the package name:

public class MyClass {

    java.util.List myList;
    
    ...

Alternatively, and more commonly, you can import classes at the top of your Java code file, and then just use the class name without package name within your code:

import java.util.List;

public class MyClass {

    List myList;
    
    ...

You have already been making use of classes in packages in earlier exercises. In the Voronoi Diagram exercise from week 5, you used the class Color, which lived in the package java.awt

import java.awt.Color;

public class Voronoi {

    ...

To make use of packages in your own code, you must do two things. First you need to create a package to store the Java files. In IntelliJ this is done by choosing 'File' / 'New' / 'Package' and filling in the package name. A package is just a folder on the filesystem, so you could just as easily have created a subdirectory of your current directory. Second, any Java files stored in a package need to be identified as belonging to that package. This is done by having a package statement at the top of the code file, before any other statements. For example, if the file MyClass was added to the package mypackage, the first line of MyClass.java would be

package mypackage;
Creating and using packages

Returning to the exercise, create a package music in your workspace.

Create or copy the Java files Favourites.java and MusicTrack.java into the music package. The new Java files should both have the first line

package music;

If you copy the classes using IntelliJ, it may add these lines for you automatically.

Re-implement this new copy of the class Favourites so that favourite tracks are stored in an ArrayList rather than a standard array. Verify that there is no upper limit on the number of tracks that can be added.

An automated test has been created for this exercise: music/FavouritesTest.java.

Note that this JUnit class must also be put in the package music.