arrays - java objects changing without setting them -


this question has answer here:

i trying understand how below code working:

public class sample {      public static void main(string[] args) {         name defaultname = new name();         defaultname.setfirstname("defaultfirst");         defaultname.setlastname("defaultlast");          name name1 = new name();         name1.setfirstname("name1first");         name1.setlastname("name1last");          name name2 = new name();         name2.setfirstname("name2first");         name2.setlastname("name2last");          list<name> namesnew = new arraylist<name>();         namesnew.add(name1);         namesnew.add(name2);          list<name> names = new arraylist<name>();         for(int i=0;i<2;i++){             name name = defaultname;             name.setfirstname(namesnew.get(i).getfirstname());             name.setlastname(namesnew.get(i).getlastname());             system.out.println(i+ " name " +name);             names.add(name);             system.out.println(i +" " +names);         }          system.out.println(names);      }  } 

when first loop executed value of names[0] being set name1 after send loop getting executed names[1] , name[0] changing name2 though not setting names[0] anywhere in code.

can tell me how behaving , should names[0] not change.

don't do:

name name = defaultname; 

with you're continually changing state of single object within loop, , not want. instead create new name object within loop:

name name = new name(); 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -