Generics & Collections


Classwork/Homework


Part A

Create a class Song which has String variables for title, artist, album, and an int for track number.  Add a method play which just prints a message saying that the song that is playing.

In a separate class, in a main, create an ArrayList of songs and add at least 10 songs to the list. Make sure you have more than one artist, more than one album for at least one artist, more than one song for at least one album, and songs on different albums for at least one artist.

Print the list and make sure your toString for Song results in a nice readable list

Make Song Comparable so that Songs are sorted alphabetically by title  (hint: String is Comparable).

In your main, sort the songs and print the sorted list.


Turn in part A as Classwork, continue for Homework.


Part B

Create a Comparator class for Song that allows you to sort alphabetically by artist, then title (that is, sort by title if the artists are the same).  [hint: you've already got something that can handle the title part.]

Create another Comparator that lets you sort alphabetically by album, and if the albums are the same, then sort by track number.

In your main, sort the songs using each of the Comparators and print the results.


Part C

Create a class Album, which has an instance variable for a title, and an instance variable tracks, which is an ArrayList of Songs.  For this class, have toString only use the title.

Add a method addSong, which, given a Song, adds it to the end of the list.  Set the track number of the song based on its new position (except that tracks should start at 1...).

Add a method tracklist, which returns a String that lists the track number and each song in the list, one per line. 

Add a method play, which, using an iterator, calls play for each of the Songs in the album in order.

In your main, create an album with at least four songs, list the tracks, and play the album.


Part D

Make Album comparable, based on the title only.

Go back through the rest of the code and in all the places where you formerly had album as a String, use the Album class.  Overload setAlbum so that one takes an Album, and the other takes a String and creates and sets a new Album based on the String as its title.

In your main, create a second Album, and make sure comparison works.

 

EC+15: Add to Album a method addExistingSong which, given a Song, checks its track number and inserts it into the list at the appropriate position (tracks are numbered from 1...).  Then go through the list, using an iterator, and update the track numbers to reflect the Songs' new positions. (You don't have to worry about the case where two songs use this to try to get the same position)  So if myAlbum has  (1. song1, 2. song2, 3. song3) and songX which has track number 2, and then we do myAlbum.addExistingSong(songX), then myAlbum has (1. song1, 2. songX, 3. song2, 4. song3).  In your main, check that this works.