-1

I need to copy all content of class object to new class object. I don't need to copy references to data, because in that case if I change fields in object a2 those data will be changed in object a2.

public class Msg {
    String info="";
    HashMap fld = new HashMap();

    public void assign(Msg value) {
        info = value.infol;
        fld = value.fld;
    }

}

// Do stuff with class
a1 = new Msg();
a1.info="111";
a1.fld.put("1","111");

a2 = new Msg();
a2.assign(a1);

How to realise function assign?

neizan
  • 2,291
  • 2
  • 37
  • 52
vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

0

You need to make a copy of your HashMap as well or you will have 2 objects pointing to the same HashMap.

public void Assign(Msg value)
{
    Info = value.Infol;
    fld = new HashMap(value.fld);
}
Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
0
org.apache.commons.beanutils.PropertyUtils.copyProperties( dest, source );
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64