我正在努力解决我的家庭作业问题.我需要创建一个包含Song对象数组的"Library"类(容量为10).然后创建一个方法addSong.这是我到目前为止所拥有的:
public class Library{
Song[] arr = new Song[10];
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:还有另一种填充数组的方法吗?我稍后需要根据索引值搜索一首歌.所以我将创建一个方法,如:public Song getSong(int idx)感谢您的期待!
如果您确实必须使用数组(而不是 ArrayList 或 LinkedList),那么此解决方案可能适合您:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想在添加超过 10 首歌曲时避免运行时例外:
public void addSong(Song s){
if(songNumber<10)
{
arr[songNumber++] = s;
}else{
//what to do if more then 10 songs are added
}
}
Run Code Online (Sandbox Code Playgroud)