user3392377
user3392377

Reputation: 33

understand Hash map keys- java

I know that HashMap doesn’t allow duplicate keys (It does allow duplicate values). However in this example that works perfectly,all the values have the same key(that means the key is not unique)Maybe I misunderstood the code.Could someone help me understand it right.

this is the code

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);

    }

}

Upvotes: 1

Views: 197

Answers (1)

M A
M A

Reputation: 72844

In each iteration of the while loop, the code is creating a new HashMap instance and filling it with only one entry that maps a String key ("AllSongs") to the Song object.

This map (which contains only one entry) will then be added to the list songsList.

After the while loop is finished, you would have a list of HashMaps where each map basically maps a hardcoded keyword to one song.

songsList:

<"AllSongs", song1>, <"AllSongs", song2>, <"AllSongs", song3>, ...

In this case, using a HashMap seems redundant. You could just fill the list with the Song instances without saving each one in a map.

The key concept here is that there are many HashMap (each iteration creates one), as opposed to having a "global" HashMap. If it were global, each song would overwrite the other since they are always mapped using the same hardcoded key.

Upvotes: 3

Related Questions