用Java克隆对象有什么需要 [英] what is the need of cloning a object in Java

查看:76
本文介绍了用Java克隆对象有什么需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关Java中的克隆,如何制作对象的浅/深副本等的信息。

I was reading about the cloning in Java, how to make shallow/deep copies of object etc.

我想知道为什么需要在其中创建对象克隆Java的?任何实时示例都有助于理解。

I was wondering why do I need to create object clones in Java? Any real time examples could be helpful in understanding.

推荐答案

通常,您想使用不可变对象,在这种情况下,克隆是一种您的代码的必要部分。例如,如果您有一个具有列表或数组类型字段的不可变对象,则您的吸气剂应始终返回列表或数组的副本以保留不可变性。

Quite often you want to use immutable objects, in which case cloning is an essential part of your code. If for example you have an immutable object that has a list or array type field, your getter should always return a clone of the list or array to preserve immutability.

典型的用例是,当您需要事务性修改时,当您调用几种状态更改方法,但仅希望结果全部成功时,结果才可见。

The other typical use case is when you want "transactional" modifications, when you call several state changing methods but only want the result to be visible if all of them are successful.

这篇关于用Java克隆对象有什么需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆