11

我需要一些关于我正在处理的家庭作业问题的帮助。我需要创建一个包含 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 Song getSong(int idx) 谢谢你期待你的回答!

4

4 回答 4

4

如果您确实必须使用数组(而不是 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
    }
}
于 2013-07-31T22:47:28.723 回答
2

有多种方法可以做到这一点。

您使用的逻辑或多或少都可以。

但是你在这里做什么:

public void addSong(Song s){
    for(int i=0; i<10; i++)
        arr[i] = s;
}

用同一首歌曲填充所有 Songs 数组,也许这样会更好:

public void addSong(Song s, int index){
        arr[index] = s;
}

当然,如果你传递一个负数索引,或者一个大于 9 的索引,你就会遇到麻烦。

于 2013-07-31T22:42:11.073 回答
1

使用ArrayList而不是数组。这样,您可以使用该ArrayList.add()函数附加到数组的末尾,并使用该ArrayList.get(int index)函数在 index 处获取数组条目index

public class Library{

    ArrayList<Song> arr = new ArrayList<Song>();

    public void addSong(Song s){
        arr.add(s);
    }

    public Song getSong(int index){
        return arr.get(index);
    }
}
于 2013-07-31T22:41:57.827 回答
0

要扩展 Vacation9s 的答案:

ArrayList<Song> songArray = new ArrayList<Song>();

public void addSong(Song s){
    songArray.add(s);
}
于 2013-07-31T22:44:07.527 回答