Java 返回副本以隐藏未来的更改
在 Java 中,假设您有一个包装 ArrayList(或任何集合)对象的类。
如何返回这些对象之一,以便调用者不会看到 ArrayList 中对该对象所做的任何未来更改?
即您想返回对象的深层副本,但您不知道它是否可克隆。
In Java, say you have a class that wraps an ArrayList
(or any collection) of objects.
How would you return one of those objects such that the caller will not see any future changes to the object made in the ArrayList?
i.e. you want to return a deep copy of the object, but you don't know if it is cloneable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这是一个显而易见的答案:
为存储在集合中的类提供可克隆的必要条件。 您可以在插入时或检索时检查这一点,无论什么更有意义,然后抛出异常。
或者,如果该项目不可克隆,则仅故障返回到按引用返回选项。
I suppose it is an ovbious answer:
Make a requisite for the classes stored in the collection to be cloneable. You could check that at insertion time or at retrieval time, whatever makes more sense, and throw an exception.
Or if the item is not cloneable, just fail back to the return by reference option.
将其转化为规范:
- 对象需要实现一个接口才能被允许进入集合
类似
ArrayList()
那么您可以放心,您始终会进行深层复制 - 接口应该有一个保证返回深层复制的方法。
我认为这是你能做的最好的事情。
Turn that into a spec:
-that objects need to implement an interface in order to be allowed into the collection
Something like
ArrayList<ICloneable>()
Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy.
I think that's the best you can do.
一种选择是使用序列化。 这是一篇解释它的博客文章:
http://weblogs.java .net/blog/emcmanus/archive/2007/04/cloning_java_ob.html
One option is to use serialization. Here's a blog post explaining it:
http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html