[英]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 我正在使用用户定义的arrayList并从
settergetter
类向其添加元素,并且有2种情况
nam[] and em[] are arrays which are already declared and have values in them nam []和em []是已经声明并在其中具有值的数组
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 在这种情况下,当我迭代时,我会得到我想要的正确答案..即第一个元素,然后第二个,依此类推
in this case i create 2 objects of settergetter class and add it to the arraylist 在这种情况下,我创建了2个settergetter类的对象并将其添加到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 在这种情况下,我得到的ans仅是最后添加的对象,即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());
}
If you closely look, you are still setting to sg
, actually you named your second instance as sg1
. 如果仔细观察,您仍将设置为
sg
,实际上您将第二个实例命名为sg1
。 Set to sg1
instance and it works. 设置为
sg1
实例即可。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.