-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,225
  • 2
  • 34
  • 49
vico
  • 15,367
  • 39
  • 141
  • 262

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,012
  • 19
  • 91
  • 135
0
org.apache.commons.beanutils.PropertyUtils.copyProperties( dest, source );
Rohit Jain
  • 203,151
  • 43
  • 392
  • 509
Prabhakaran Ramaswamy
  • 24,936
  • 10
  • 54
  • 63