Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling an array with objects

Tags:

java

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!

like image 723
DaniFC Avatar asked Jul 31 '13 22:07

DaniFC


People also ask

How do you fill an array with values?

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.

Can you put objects in arrays?

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.

How do you fill an array with 0's?

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.


1 Answers

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
    }
}
like image 75
cdMinix Avatar answered Sep 23 '22 01:09

cdMinix