Question

i've a problem by filling the Hashmap<Object, Collection<Object>>. every time i want to fill the value part of the HashMap(in this case the Collection) my object, which needs to be added to the Collection, only takes the last received value of the object. for example my code is like this(Using LastFM API):

Map<Object, Collection<Tag>> tracksTags = new HashMap<Track, Collection<Tag>>();
Collection<Track> trackSet = tracks.getPageResults();
Collection<Tag> tags  = new HashSet<Tag>();

String artist = "";
String trackTitle = "";

int counter = 0;

for (Track track : trackSet) {
    tags.clear();

    artist = track.getArtist();
    trackTitle = track.getName();

    Collection<Tag> tagList = Track.getTopTags(artist, trackTitle,
                apiKey);

    for (Tag tag : tagList) {
            if (counter <= 9) {

                counter++;

                System.out.println(trackTitle + " " + tag.getName() + " "
                        + tag.getCount());
                tags.add(tag);

            } else
                break;
    }
    counter = 0;

    tracksTags.put(track, tags);


}

My problem is that tags only takes the value of the last retrieval... still have no idea why. Even i dont know if it is a Hashmap-Filling problem.

Would appreciate any help.

Was it helpful?

Solution

All of your tracks share the same inner HashSet instance.
Therefore, tags.clear() at the top of the loop, and the inner loop to populate the set, affect all of the tracks.

You need to create a new HashSet<>() for each track inside the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top