java对象的拷贝

本文通过实例详细解析了Java中int类型和String类的拷贝机制,对比了浅拷贝和深拷贝的区别,展示了如何使用clone()方法实现深拷贝。

int类型的拷贝:

public static void main(String[] args) {
    int[] str1 = {0,1};
    int[] str2 = str1;
    str2[1] = 2;
    int[] str3 = str1.clone();
    str3[1] = 3;
    System.out.println(Arrays.toString(str1));
    System.out.println(Arrays.toString(str2));
    System.out.println(Arrays.toString(str3));
}

[0, 2]
[0, 2]
[0, 3]

可以看到只有调用clone()方法,才能深拷贝一个基本对象。

String类的拷贝:

public static void main(String[] args) {
        String[] str1 = {"a0", "a1"};
        String[] str2 = str1;
//        str2[1] = "a2";
        String[] str3 = str1.clone();
//        str2[1] = "a3";
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }

[Ljava.lang.String;@4554617c
[Ljava.lang.String;@4554617c
[Ljava.lang.String;@74a14482

可以看到,String类的复制与包装类一样,是索引的复制,而其clone()方法可以实现值的复制。

### 浅拷贝的实现方式 浅拷贝可以通过以下几种方式实现: 1. **使用构造器实现浅拷贝**:可以通过类的构造器将对象的字段逐一赋值来实现浅拷贝。这种方式需要手动编写代码来复制字段值。 2. **重写 `Object.clone()` 方法**:Java 提供了 `clone()` 方法来实现浅拷贝。需要类实现 `Cloneable` 接口,并重写 `clone()` 方法。需要注意的是,`clone()` 方法默认是浅拷贝,即只复制基本数据类型的字段,而引用类型的字段只会复制引用,不会复制引用对象本身。 ### 深拷贝的实现方式 深拷贝可以通过以下几种方式实现: 1. **递归调用 `clone()` 方法**:可以通过递归调用 `clone()` 方法来实现深拷贝。需要在类中重写 `clone()` 方法,并对引用类型的字段进行递归调用 `clone()` 方法来复制引用对象[^4]。 2. **序列化实现深拷贝**:可以通过序列化和反序列化来实现深拷贝。需要类实现 `Serializable` 接口,并通过 `ObjectInputStream` 和 `ObjectOutputStream` 来进行序列化和反序列化操作。这种方式需要注意类及其引用的对象都必须实现 `Serializable` 接口[^3]。 ### 代码示例 #### 浅拷贝示例 ```java public class ShallowCopyExample implements Cloneable { private int value; private String reference; public ShallowCopyExample(int value, String reference) { this.value = value; this.reference = reference; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // Getters and setters } ``` #### 深拷贝示例(使用 `clone()` 方法) ```java public class DeepCopyExample implements Cloneable { private int value; private String reference; public DeepCopyExample(int value, String reference) { this.value = value; this.reference = reference; } @Override protected Object clone() throws CloneNotSupportedException { DeepCopyExample copy = (DeepCopyExample) super.clone(); copy.reference = new String(this.reference); // 复制引用对象 return copy; } // Getters and setters } ``` #### 深拷贝示例(使用序列化) ```java import java.io.*; public class DeepCopyWithSerialization implements Serializable { private int value; private String reference; public DeepCopyWithSerialization(int value, String reference) { this.value = value; this.reference = reference; } public DeepCopyWithSerialization deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); oos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (DeepCopyWithSerialization) ois.readObject(); } // Getters and setters } ``` ### 注意事项 - **性能优化**:深拷贝通常比浅拷贝消耗更多的资源,尤其是在对象结构复杂的情况下。因此,在选择拷贝方式时需要考虑性能因素。 - **安全性**:在使用序列化进行深拷贝时,需要注意类及其引用的对象都必须实现 `Serializable` 接口,否则会抛出异常。 - **常见错误**:在实现 `clone()` 方法时,需要注意正确处理引用类型的字段,否则可能导致浅拷贝而不是预期的深拷贝。 ### 选择深拷贝还是浅拷贝? 选择深拷贝还是浅拷贝取决于具体的应用场景。如果对象的引用类型字段不需要独立复制,浅拷贝就足够了。如果需要完全独立的对象副本,包括引用的对象,则需要使用深拷贝
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值