문제

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.

도움이 되었습니까?

해결책

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"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top