列表覆盖对象Java [英] List overriding objects java
问题描述
我的Java代码有问题...
Hi i'm with a problem in my java code...
这样的问题出现在我列表的add(e)中:
the problme is in the add(e) of my list like that:
List<Sms> listSms = new ArrayList<Sms>();
for(int i = 0; i < grupo.size(); i++){
Grupo group = new GrupoDao().carregaById(grupo.get(i),usuario.logado);
for(int j = 0; j < group.getContatos().size(); j++){
sms.setNumber(group.getContatos().get(j).getNumber());
listSms.add(sms);//Here he override all the list sms.number to last one added
}
}
有人可以帮助我吗?
推荐答案
添加到列表中的不是实例,而是对实例的引用.因此,最后,list
中的所有引用都引用同一实例.这意味着,您使用任何引用对实例所做的更改将反映在您之前添加到列表中的所有引用中.
What you add to the list is not an instance, rather a reference to an instance. So, at the end, all the references in the list
is referring to the same instance. That would mean that, the change you make to your instance using any reference, will be reflected for all the references you added earlier to the list.
解决方案是每次在列表中添加对它的引用时都创建一个新的Sms
实例.您必须在for
循环中执行此操作.
The solution would be to create a new Sms
instance each time you add a reference to it in the list. That you would have to do it in the for
loop.
for(int j = 0; j < group.getContatos().size(); j++){
Sms sms = new Sms();
sms.setNumber(group.getContatos().get(j).getNumber());
listSms.add(sms);//Here he override all the list sms.number to last one added
}
这篇关于列表覆盖对象Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!