1

Say I have Employee class and within that I have a member like List of Address. One way is to create like list = Collections.unmodifiableList(list) and another way is doing defensive copying or deep cloning. But first approach is just wrapper around the mutable instance, the Address object will still be mutable. And we can not touch address class as it is third party class. And if we are doing deep cloning, say if list contains millions of entries, then while cloning there will be performance penalty. Is there any other approach for this?

implosivesilence
  • 536
  • 10
  • 24
  • 1
    You could create your own immutable wrapper class around `Address`. – vlumi Feb 26 '20 at 05:49
  • This might help - https://stackoverflow.com/a/3162682/6249539 – voucher_wolves Feb 26 '20 at 06:03
  • @kenobiwan It is quite similar to doing deep cloning in the constructor. Cloning comes with the performance cost, I was looking for other workaround. – implosivesilence Feb 26 '20 at 06:18
  • @vlumi Thanks. Do you have any code snippet for the same? – implosivesilence Feb 26 '20 at 06:19
  • The immutable wrapper would just be a class that would only have getters for the fields of `Address` -- and create a similar immutable wrapper for any other mutable classes in your hierarchy. This approach won't work if you need the to pass the original, mutable type object somewhere -- maybe the wrapper could have a method to get a deep clone of the original type, too. – vlumi Feb 26 '20 at 07:28

0 Answers0