我是使用Java集合框架的新手。我有以下代码:
private Map<String, List<Song>> byArtist() {
Map<String, List<Song>> byArtist = new HashMap<>();
for (Song song : mSongs) {
List<Song> artistSongs = byArtist.get(song.getArtist());
if (artistSongs == null) {
artistSongs = new ArrayList<>();
byArtist.put(song.getArtist(), artistSongs);
}
artistSongs.add(song);
}
return byArtist;
}
代码工作正常但是,我不明白的部分是如果我们只使用{{1}中的put方法添加艺术家和歌曲,地图byArtist
是如何更新的} condition,如果我们正在创建if
变量的新实例。其他实例的存储方式和位置在哪里?
答案 0 :(得分:1)
每首歌都有一位艺术家,你正在迭代歌曲并为艺术家的名字添加歌曲,因此你不仅可以找到给定歌曲的艺术家,还可以找到给定艺术家的歌曲。更重要的是你的
Map<String, List<Song>> byArtist = new HashMap<>();
应改为
Map<String, List<Song>> byArtist = new HashMap<String, List<Song>>();