User Guide
250 Working with Arrays
As with all objects, declaring an Array instance is only half the job of creating an Array. Before
accessing an Array instance’s properties or methods, it must be instantiated, which is done in
the PlayList class’s constructor.
public function PlayList()
{
this._songs = new Array();
// Set the initial sorting.
this.sortList(SortProperty.TITLE);
}
The first line of the constructor instantiates the _songs variable, so that it is ready to be used.
In addition, the
sortList() method is called to set the initial sort-by property.
Adding a song to the list
When a user enters a new song into the application, the code in the data entry form calls the
PlayList class’s
addSong() method.
/**
* Adds a song to the playlist.
*/
public function addSong(song:Song):void
{
this._songs.push(song);
this._needToSort = true;
}
Inside addSong(), the _songs array’s push() method is called, adding the Song object that
was passed to
addSong() as a new element in that array. With the push() method, the new
element is added to the end of the array, regardless of any sorting that might have been
applied previously. This means that after the
push() method has been called, the list of songs
is likely to no longer be sorted correctly, so the
_needToSort variable is set to true. In theory,
the
sortList() method could be called immediately, removing the need to keep track of
whether the list is sorted or not at a given time. In practice, however, there is no need for the
list of songs to be sorted until immediately before it is retrieved. By deferring the sorting
operation, the application doesn’t perform sorting that is unnecessary if, for example, several
songs are added to the list before it is retrieved.