0

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()); } 

1 Answer 1

1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.