1

My sample code -

private final DataObj dataObj = getDataObjs();

private final DataObj dataObj1 = new DataObjImpl();
dataObj1 = dataObj; //I need the value of dataObj1 to be the same even if the value of dataObj is modified anywhere further down in a class.

My problem is that if the value of the Object dataObj is being modified then the value of the second Object dataObj1 is also modified but I need the second Object dataObj1 to be immutable (Value should persist), is there a way to do this?

M A
  • 71,713
  • 13
  • 134
  • 174
Sangli
  • 373
  • 4
  • 20
  • http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone() (or) http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying-an-instance – kosa Jun 22 '15 at 19:17
  • You ought to be implementing your own constructor that properly copies a `DataObj`. – Louis Wasserman Jun 22 '15 at 19:27

2 Answers2

3

By using the assignment statement, dataObj1 = dataObj;, dataObj1 refers to the exact same object as dataObj. The solution is to assign a copy of the object referenced by dataObj. One way to do this is via a copy constructor, something like:

dataObj1 = new DataObjImpl(dataObj);

Below is an example:

class DataObjImpl {

   private Object data;

   public Object getData() {
      return data;
   }

   public void setData(Object data) {
      this.data = data;
   }

   // copy constructor
   public DataObjImpl(DataObjImpl obj) {
      this.data = obj.data;
   }        
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • Could you please give me an example in the form of a code snippet with respect to my sample code? so should I substitute this line instead of direct assignment "dataObj1 = dataObj.clone();"? – Sangli Jun 22 '15 at 19:23
  • 1
    @user3652212 I edited my answer. A copy constructor is preferrable to a `clone()`. See http://www.javapractices.com/topic/TopicAction.do?Id=12.' – M A Jun 22 '15 at 19:25
  • Thanks, helped a lot! – Sangli Jun 22 '15 at 19:36
1

You need to deep copy the object. Or at least use the clone method to copy it over.

Adam
  • 2,422
  • 18
  • 29
  • See http://stackoverflow.com/questions/2427883/clone-vs-copy-constructor-which-is-recommended-in-java. – M A Jun 22 '15 at 19:38