【问题标题】:understand Hash map keys- java了解哈希映射键 - java
【发布时间】:2014-09-16 12:11:25
【问题描述】:

我知道 HashMap 不允许重复键(它确实允许重复值)。 但是在这个完美运行的示例中,所有值都具有相同的键(这意味着键不是唯一的)也许我误解了代码。有人可以帮助我正确理解它。

这是代码

public class PlayListManager {
//**********************************hashmap keys************************
public static final String ALL_VIDEOS = "AllVideos";
public static final String ALL_Songs = "AllSongs";
//***************************************************************************
 ..
 ...
 ....
       while (cursor.moveToNext()) {
        Songs song = new Songs();
        song.songId = cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
        song.artist = cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
        song.title = cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
        song.songName = cursor
                .getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
        song.duration = Integer.parseInt(cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)));
        song.albumId = Integer.parseInt(cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)));
        song.songData = cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));


        //*******here it uses the same ky for all the videos?!!*************
        HashMap<String, Object> songMap = new HashMap<String, Object>();
        songMap.put(ALL_Songs, song);
        songsList.add(songMap);

    }

}

【问题讨论】:

标签: java hash map


【解决方案1】:

while 循环的每次迭代中,代码都会创建一个 HashMap 实例,并仅用一个将String 键("AllSongs")映射到Song 对象。

然后此地图(仅包含一个条目)将添加到列表songsList

while 循环完成后,您将拥有一个 HashMaps 列表,其中每个映射基本上将硬编码的关键字映射到一首歌曲。

歌曲列表:

, , , ...

在这种情况下,使用HashMap 似乎是多余的。您可以只用 Song 实例填充列表,而无需将每个实例都保存在地图中。

这里的关键概念是有很多HashMap(每次迭代都会创建一个),而不是有一个“全局”HashMap。如果它是全局的,每首歌曲都会覆盖另一首歌曲,因为它们总是使用相同的硬编码键映射。

【讨论】:

  • 我现在明白了。但是为什么不使用 hashmap 对象添加到列表 Songlist 中呢?为什么不使用对象 Song 来添加到列表 Songlist 中呢?---我在说这个具体的例子
  • 你说得对:在这种情况下,使用 HashMap 似乎是多余的。您可以只用 Song 实例填充列表,而无需将每个实例保存在地图中。但我不知道是谁编写了这段代码以及他或她为什么决定采用这种方法。
猜你喜欢
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
相关资源
最近更新 更多