我需要一些帮助来解决我正在做的家庭作业问题。 我需要创建一个包含 Song 对象数组的“库”类。(容量为 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;
}
}
我的问题是:是否有另一种方法来填充数组?我稍后需要根据索引值搜索歌曲。所以我将创建一个方法,如: 公共(public)歌曲 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;
}
}
如果您想在添加超过 10 首歌曲时避免运行时异常:
public void addSong(Song s){
if(songNumber<10)
{
arr[songNumber++] = s;
}else{
//what to do if more then 10 songs are added
}
}
关于java - 用对象填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17982199/