Amol
Amol

Reputation: 303

What is the difference between the two?

i am using an user-defined arrayList and adding elements to it from settergetter class and there are 2 scenarios

using for loop

nam[] and em[] are arrays which are already declared and have values in them

for(int i=0;i<2;i++)
  {
    settergetter sg = new settergetter();
    sg.setName(nam[i]);
    sg.setEmail(em[i]);
    a1.add(sg);
  } 

in this case when i iterate i get correct ans as i want .. ie 1st element and then 2nd and so on

normal case

in this case i create 2 objects of settergetter class and add it to the arraylist

  settergetter sg = new settergetter();
  sg.setName("amol");
  sg.setEmail("amol@9372");
  a1.add(sg);
  settergetter sg1 = new settergetter();
  sg.setName("robin");
  sg.setEmail("robin@9372");
  a1.add(sg1);

in this case the ans i get is only of the last object added ie robin

in both the cases i am creating different instances of the class

i am using iterator as :

  Iterator itr=a1.iterator();
  while(itr.hasNext())
  {
     settergetter element = (settergetter) itr.next();
     System.out.println(element.getName());
     System.out.println(element.getEmail());
  }

Upvotes: 0

Views: 37

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 121998

If you closely look, you are still setting to sg, actually you named your second instance as sg1. Set to sg1 instance and it works.

 settergetter sg1 = new settergetter();
  sg.setName("robin");
  sg.setEmail("robin@9372");
  a1.add(sg1);

That should be

settergetter sg1 = new settergetter();
  sg1.setName("robin");  // here 
  sg1.setEmail("robin@9372"); // here 
  a1.add(sg1);

Upvotes: 1

Related Questions