Question

I am trying to add my user defined objects to a linked list however every time I add, the information just gets duplicated.

public class Videostore(){
    public LinkedList<Video> videoList = new LinkedList<>();
    public Videostore(){
        addVideo("a");
        addVideo("b");
        addVideo("c");
    }
    private void addVideo(String o){  
        Video vid = new Video(o);
        videoList.add(vid);     
    }
}

public class Video {

    public static Object title;
    public static boolean isRent;

    public Video(String t){
        title = t;
        isRent = false;
    }

    public static void setisRent(boolean bool){
        isRent = bool;
    }

    public String toString(){
        return title.toString();
    }
}

When Video Store is initialized the videoList has only "c"'s inside.I need it to have a b and c.

Était-ce utile?

La solution

The problem is that your Video class variables are static, meaning only one copy of each for the whole class. They get overwritten with each new instance.

Video ---> "c"
         ^ ^
Video --/ /
         /
Video --/

Remove static to make them instance variables, meaning one each per instance of the class. Then the values won't overwrite each other.

Video ---> "a"

Video ---> "b"

Video ---> "c"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top