问题描述
我的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!