Hubert
Hubert

Reputation: 1

Array inside a Java Class?

public class Playlist 
{
    String title;
    String genre;
    Boolean privatePlaylist = true;
    Song[] listOfSongs;

    public Playlist(String tl, String gn, Boolean priv)
    {
        tl = title;
        gn = genre;
        priv = privatePlaylist;
    }

    Song[] mostPlayedSongs()
   {
       return listOfSongs;
   }

}

Above is my code. I am trying to create a java class that returns a playlist. I want it to return a title, genre, whether the playlist is private or public. All three of these things are already constructed above. However, to that list, as a fourth property I would like to add an array that lists all the song in the playlist. The array is already a property I created above(Song[]listOfSongs). However, I do not know how to join this array to the other three properties and how to put the songs in this array. Any suggestions?

Upvotes: 0

Views: 965

Answers (2)

Nand
Nand

Reputation: 600

import java.util.ArrayList;

public class Playlist {
    public final String title;
    public final String genre;
    public final Boolean privatePlaylist;
    public final ArrayList<Song> listOfSongs;

    public Playlist(String tl, String gn, Boolean priv) {
        title = tl;
        genre = gn;
        privatePlaylist = priv;
        listOfSongs = new ArrayList<>();
    }
}

Example usage:

public class Main {
    public static void main(String[] args) {
        Playlist pl = new Playlist("title", "genre", false);
        pl.listOfSongs.add(...);
        System.out.println(pl.title);
    }
}

Upvotes: 0

TK46
TK46

Reputation: 101

if you don't want to change the songs, you could just place it in the constructor:

public PlayList(String title, String genre, Boolean privatePlaylist, Song[] songs) {
    this.title = title;
    this.genre = genre;
    this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
    this.listOfSongs = listOfSongs;
  }

if the list of songs shouldn't be added in the constructor (i.e, it needs to be updated) I would use an ArrayList so you can change the size:

    // Field:
private ArrayList<Song> listOfSongs;

// Constructor
public PlayList(String title, String genre, Boolean privatePlaylist) {
        this.title = title;
        this.genre = genre;
        this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
        this.listOfSongs = new ArrayList<>();
}

// To edit the songs:
public void setListOfSongs (ArrayList<Song> listOfSongs) {
     this.listOfSongs = listOfSongs;
}

Upvotes: 1

Related Questions