List overriding objects java [closed]

2019-09-09 14:16发布

问题:

Hi i'm with a problem in my java code...

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
        }
    }

can anybody help me ?

回答1:

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.

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
}


回答2:

You are adding the same object/instance again and again. You need to add a new instance to the list like this:

Sms x=new Sms();
x.setNumber......
listSms.add(x);