Search code examples
javaarraylistparametersconstructorbluej

Why use an ArrayList as a constructor parameter in Java (BlueJ)?


I'm trying to complete an assignment in BlueJ for uni and I've hit a snag at the first hurdle.

In the assignment, we are given a class, as well as the names of the constructor, methods, and parameters of that class. We're not allowed to change these because the assignments are partially marked by a test unit (or something to that effect).

One of the constructors for this class is given as

 public class PlayList
 {
    public PlayList(String name, ArrayList<Track> tracks) {
    }

And I have (partially) completed it as

public class PlayList
{
   private String listName;
   private ArrayList<Track> listTracks = new ArrayList<Track>();

   /**
    * Constructs a playlist with a title and an ArrayList of tracks
    * 
    * @param name The name of the playlist
    * @param tracks An ArrayList of tracks in the playlist
    */
   public PlayList(String name, ArrayList<Track> tracks) {
       listName = name;
       //I really don't know what to do with the tracks parameter yet
   }

Okay, so, I know from this question (How do I enter parameters for an ArrayList in BlueJ?) that I have to create an instance of an ArrayList in order to pass it as a parameter in BlueJ.

What I don't understand is why - why have they used ArrayList<Track> as a parameter for the constructor? What is the benefit of doing this?

(I figure there must be a benefit to doing it like this (if there wasn't the functionality wouldn't exist in the first place), but I don't understand what it is, and if someone could explain it to me, I'd be greatly appreciative.)


Solution

  • why have they used ArrayList<Track> as a parameter for the constructor?

    They did it to allow callers to pass an arbitrary number of Tracks in a single parameter.

    Java offers several options to do this: you could pass a collection, an array, or even an iterator. If I were designing a signature for the constructor, I would strongly prefer Collection<Track> or at least a List<Track> to ArrayList<Track>, in order to give callers more options as far as what collection they could pass to my constructor.

    Going back to what to do with the array list, you should make a defensive copy of it. One way would be using Collections.copy, like this:

    Collections.copy(this.tracks, tracks);
    

    Once the copy is complete, you should walk through elements of this.track, and ensure that they are not null.