Why do two objects share the same LinkedList when the objects are declared separately?

Viewed 43

I have a hash map that is supposed to display artists and their songs. I have two Artists objects declared as max and brian. When I execute the code, the list of songs is shared between the two Artists. How do I separate the songs added so each artist has their own list?

My current output is:
Brian : , Hello, World, World, World
Max : , Hello, World, World, World, World

When I want it to be:
Brian : , World, World
Max : , Hello, World, World

This class creates the map and adds the artists/songs.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class music {

    public static void run() {
        Artists max = new Artists("Max");
        Artists brian = new Artists("Brian");

        Map<String, String> musicLibrary = new HashMap<>();
        musicLibrary.put(max.getArtist(), max.addSong("Hello"));
        musicLibrary.put(max.getArtist(), max.addSong("World"));
        musicLibrary.put(brian.getArtist(), brian.addSong("World"));
        musicLibrary.put(brian.getArtist(), brian.addSong("World"));
        musicLibrary.put(max.getArtist(), max.addSong("World"));

        Set<String> keySet = musicLibrary.keySet();
        for (String key : keySet) {
            String value = musicLibrary.get(key);
            System.out.println(key + " : " + value);
        }
    }
}

This class is the Artists object.

import java.util.LinkedList;
import java.util.ListIterator;

public class Artists {

    String songName;
    String artist;
    static LinkedList<String> artistSongs = new LinkedList<String>();
    static ListIterator<String> songsIt = artistSongs.listIterator();

    public Artists(String artist){
        this.artist = artist;
    }

    public static String addSong(String songName){
        //this.artist = artist;
        artistSongs.add(songName);
        return output();
    }

    public static String output(){
        String allSongs = "";

        for(String song: artistSongs) {
            allSongs = allSongs + ", " + artistSongs.get(artistSongs.indexOf(song));
        }

        return allSongs;
    }

    public String getArtist(){
        return artist;
    }
}

My current output is:
Brian : , Hello, World, World, World
Max : , Hello, World, World, World, World

When I want it to be:
Brian : , World, World
Max : , Hello, World, World

1 Answers

You've declared artistSongs as static. This means it doesn't belong to a specific instance, but to the class, and is shared between all instances. Define it as an instance variable, and you should be good to go:

List<String> artistSongs = new LinkedList<>();
Related