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