Reputation: 55
Ive been trying to work this out for a few hours now, but am stuck, hence I am coming here for some help. N.B. I am using BlueJ, to construct these classes, as im still learning.
What I am trying to do is create a PlayList which has a two parameters: name and a ArrayList of tracks. It then creates a playlist and copies the tracks from the list (in order) onto the playlist; but I dont want any help with this part, as of yet.
My issue is I am unsure how to call the ArrayList when constructing the PlayList.. Because the specified type is of .
public class PlayList
{
private String myName;
private ArrayList<Track> myTracks;
private int myDuration;
public PlayList(String name, ArrayList<Track> tracks) {
name = myName;
myTracks = new ArrayList<Track>();
for (Track t : tracks) {
myTracks.add(t);
}
}
}
What happens, in BlueJ, is when I construct a new PlayList class, it provides an empty field box for String name, and for ArrayList tracks. String name is fine, as I can simply put "anything" but am stuck as to the ArrayList tracks?
I know this is probably isnt a very specific question, but I am still learning.
Upvotes: 2
Views: 6125
Reputation: 6897
sunadorer's response should answer your direct question. I have some general remarks about naming conventions for the fields in your class and the parameters of your constructor.
I would not prefix your fields with 'my'. It is a bit of a matter of style, but I would not have much against using the same names for the constructor parameters. You can distinguish between the parameter and the field by using this.name
when referring to the field.
Also, using ArrayList
here seems unnecessarily restrictive: you could use the more general List
interface (which ArrayList
is just one implementation of, so you don't have to touch PlayList
if you want another kind of List
later o):
public class PlayList {
private String name;
private List<Track> tracks;
private int duration;
public PlayList(String name, List<Track> tracks) {
this.name = name;
this.tracks = new ArrayList<Track>(tracks);
}
}
Upvotes: 2
Reputation: 3892
The constructor of your PlayList
wants an object of type ArrayList
filled with elements of type Track
. So to create a PlayList you must provide an already created one.
It depends on your surrounding of the call, maybe you already build a list there and can just put it into your PlayList constructor, but you need something like this anywhere:
// Create an empty list
ArrayList<Track> tracks = new ArrayList<Track>();
// Add a track. e.g. when receiving a gui event
tracks.add(track); // track was created with new Track()
Or maybe you don't need/want lists outside of PlayList
objects. You could use PlayList
objects to manage and encapsulate those, by changing the constructor to only create an empty list on its own and allow others to add tracks to it via an addTrack
method.
Upvotes: 1