Search code examples
javaclonedeep-copy

Copying An Object With Sharing References To Member Data


I have an Java webapp, that pulls up an employee's record and stores it in a home made data holder object, called, oddly enough "EmployeeRecordDataHolder".

I want to make a copy of EmployeeRecordDataHolder at the beginning of an update process, so that I can do a comparison to report on how the data changed.

I ran into some problems with the original and copy sharing references to member data, with the result being that the original data didn't stay un-updated.

I originally get the data back from the database via a HashMap. If I populated both objects, the original and copy, from the HashMap get(), would the two objects still share the same references to the data, resulting in the situation that changing the data in one object will also change it in the copy?

What if I used the HashMap to populate the original object and then made a copy by calling all of the getters on the orignal in all of the setters on the copy? Example:

copyDataHolderObj.setSomePieceOfData(  originalDataHolderObj.getSomePieceOfData() );

Would this method result in two objects that could be changed independent of each other?

Thanks much in advance

Steve


Solution

  • Answer to your first question:

    Yes, both will share references to the same object. HashMap stores the references, hence any update done is done on the original object. This page clearly explains that the changes are reflected.

    Answer to your second question:

    You can do it that way. Creating a copy of all objects.