【发布时间】:2016-01-25 20:30:39
【问题描述】:
假设我有一个名为 Song 的类,其中包含很多信息,例如
- 歌曲名称
- 歌曲艺术家
- 歌曲文件扩展名
- 其他歌曲信息...
此类中的 setter 设置歌曲标题。
public class Song {
private String title;
private String artist;
...
public Song(String songTitle, String songArtist, ...) {
this.title=songTitle;
this.artist=songArtist;
...
}
public void setTitle(String Songname){
this.title = Songname;
}
public String getTitle(){return title;}
public String getArtist(){return artist;}
...
}
我有一个 字符串 列表,其中包含不同的歌曲标题,但没有关于歌曲的其他信息。现在我想填充一个 Songs 列表,并在 setter 的帮助下将这些 Songs 类的标题设置为列表 Strings 中的标题。我在 for 语句中执行此操作,但如果我检查列表条目,我只会得到最后添加的歌曲的标题。
int index = 0;
Song songClass = new LocalSong(null, null, ...);
for (final String song : Songs) {
try {
songClass.setTitle(song);
//Set Titles for Local Song Objects
AnotherList.add(index, null);
AnotherList.set(index, songClass);
System.out.println("Title of Song number " + index + " is " + AnotherList.get(index).getTitle());
index++;
} catch (Exception e) {e.printStackTrace();}
}
我发现,当我不使用 Song 类中的 setter 并在 for 语句中为每个 List of Strings 条目创建一个新的 Song 对象时,它可以工作。像这样:
int index = 0;
for (final String songname : Songs) {
try {
Song songClass = new LocalSong(songname, null, ...);
//Set Titles for Local Song Objects
AnotherList.add(index, null);
AnotherList.set(index, songClass);
System.out.println("Title of Song number " + index + " is " + AnotherList.get(index).getTitle());
index++;
} catch (Exception e) {e.printStackTrace();}
}
但该解决方案不是性能要求高吗?例如,如果我在 Strings 列表中有数百个条目,我会创建数百个我不使用的歌曲类,或者垃圾收集器是否处理得很好?
另外,有没有更好的方法来创建带有我从 Strings 列表中获得的标题的歌曲类。
【问题讨论】:
-
如果您只需要标题,为什么还要
Song实例? -
是的,您正在创建所有这些歌曲对象。但是物品很便宜。但是,您在什么意义上不使用这些歌曲对象?您将它们全部放入列表中是有原因的。无论如何,这不是性能好坏的问题,而是工作与否的问题。
-
Songs是一个字段/变量/参数,应该以小写开头,如songs。 --- 为什么打电话给add(index, null); set(index, songClass);而不仅仅是add(songClass)? ---songClass应该只是song。 -
@DaveNewton 我在可扩展的列表视图中使用这些歌曲对象,我有一些包含更多信息的歌曲和一些只有标题的歌曲。我根据其在 exp 中的分组位置对对象进行不同的处理。列表视图。
-
另外,请不要永远捕获这样的异常并继续处理,就好像没有出现任何问题一样。
标签: java android performance for-loop garbage-collection