list of list in instance of object (java) -


i have defined class 'student'. each instance of class has name , n*m preferences (which string).

public class student {     string firstname;     list<list<string>> choice = new arraylist<list<string>>();      public student(string name1, list<list<string>> preference){         this.firstname = name1;         this.choice.addall(preference);      } } 

next, have list in each student object saved.

list<student> students = new arraylist<student>(); 

now problem is, when save 1 student in list working fine. however, when add second student list preferences of first students overwritten. add , read data follow,

list<list<string>> preferences = new arraylist<list<string>>(); list<string> preferences1 = new arraylist<string>(); list<string> preferences2 = new arraylist<string>();   // add first student preferences.clear(); preferences1.clear(); preferences2.clear(); preferences1.add("company1"); preferences1.add("company3"); preferences2.add("company2"); preferences2.add("company4"); preferences.add(preferences1); preferences.add(preferences2); students.add(new student("michiel", preferences));  // add second student preferences.clear(); preferences1.clear(); preferences2.clear(); preferences1.add("company5"); preferences1.add("company7"); preferences2.add("company6"); preferences2.add("company8"); preferences.add(preferences1); preferences.add(preferences2); students.add(new student("william", preferences));  system.out.println(students.get(0).choice); system.out.println(students.get(1).choice); 

what going wrong? have tried 'final' in class.

ps. small subquestion, suggest using arraylist or list?

you can't reuse same list when add next student. save reference, clearing later clear saved preferences. create new lists of preferences each student, , fine:

...  preferences = new arraylist<list<string>>(); preferences1 = new arraylist<string>(); preferences2 = new arraylist<string>();  // add second student preferences1.add("company5"); preferences1.add("company7"); preferences2.add("company6"); preferences2.add("company8"); preferences.add(preferences1); preferences.add(preferences2); students.add(new student("william", preferences)); 

ps. small subquestion, suggest using arraylist or list?

what doing looks fine. need pick concrete implementation of list interface, , have chosen arraylist reasonable.
also, declaring variables of interface type list, preferred way it.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -