I need some help with a homework question I am working on. I need to create a "Library" class that contains an array of Song objects.(capacity of 10). Then make a method addSong. Here's what I have so far:
public class Library{
Song[] arr = new Song[10];
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
}
My question is: Is there another way to fill the array? i will later need to search for a song based on a index value. So i will create a method like: public Song getSong(int idx) Thank you in anticipation for your answers!
Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.
You can add objects of any data type to an array using the push() function. You can also add multiple values to an array by adding them in the push() function separated by a comma. To add the items or objects at the beginning of the array, we can use the unshift() function.
Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.
If you really have to use an array (and not an ArrayList or LinkedList), this solution may be the right for you:
public class Library{
private Song[] arr = new Song[10];
private int songNumber = 0; //the number of Songs already stored in your array
public void addSong(Song s){
arr[songNumber++] = s;
}
}
If you want to avoid a runtime-exeption if you add more then 10 songs:
public void addSong(Song s){
if(songNumber<10)
{
arr[songNumber++] = s;
}else{
//what to do if more then 10 songs are added
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With