我如何在java中创建对象的副本,而不是指针 [英] how do i create a copy of an object in java, instead of a pointer

查看:122
本文介绍了我如何在java中创建对象的副本,而不是指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我有一个我创造的对象。我在其中编辑了一些值,因此它与我引用的新对象()不同。让我们调用该对象f1。现在我想要另一个名为f2的对象是f1的副本而不是指针,所以当我改变f2中的值时,它也不会改变f1。我将如何在java中执行此操作?

Lets say i have an object that i created. I edited some values in it so it is different than the new object() that i referenced. Lets call that object f1. Now i want another object called f2 to be a copy of f1 but not a pointer, so that when i change a value in f2, it does not also change f1. How would i go about doing this in java?

推荐答案

首先,让您的类实现 Cloneable 界面。如果没有这个,在对象上调用 clone()将抛出异常。

First, have your class implement the Cloneable interface. Without this, calling clone() on your object will throw an exception.

接下来,覆盖 Object.clone()因此它返回您特定类型的对象。实现可以简单地是:

Next, override Object.clone() so it returns your specific type of object. The implementation can simply be:

@Override
public MyObject clone() {
    return (MyObject)super.clone();
}

除非你需要更复杂的东西。但是,请确保调用 super.clone()

unless you need something more intricate done. Make sure you call super.clone(), though.

这将在层次结构中一直调用 Object.clone(),它复制每一段数据在你的对象中构造它的新对象。引用是复制的,而不是克隆的,所以如果你想要一个深层拷贝(你的对象引用的对象的克隆),你需要在被覆盖的 clone()功能。

This will call all the way up the hierarchy to Object.clone(), which copies each piece of data in your object to the new one that it constructs. References are copied, not cloned, so if you want a deep copy (clones of objects referenced by your object), you'll need to do some extra work in your overridden clone() function.

这篇关于我如何在java中创建对象的副本,而不是指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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