java对象的拷贝

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()方法可以实现值的复制。

Java中可以使用以下几种方式进行对象拷贝: 1. 浅拷贝(Shallow Copy):使用`clone()`方法实现浅拷贝。浅拷贝只是复制了对象的引用,而不是创建一个新的对象。修改原对象拷贝对象的属性会相互影响。 ```java class MyClass implements Cloneable { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } // 使用浅拷贝 MyClass obj1 = new MyClass(); obj1.setValue(10); MyClass obj2 = (MyClass) obj1.clone(); System.out.println(obj2.getValue()); // 输出 10 obj2.setValue(20); System.out.println(obj1.getValue()); // 输出 20,原对象也被修改了 ``` 2. 深拷贝(Deep Copy):通过序列化和反序列化实现深拷贝。深拷贝会创建一个新的对象,并复制对象的所有属性。修改原对象拷贝对象的属性不会相互影响。 ```java import java.io.*; class MyClass implements Serializable { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } public MyClass deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); MyClass copy = (MyClass) ois.readObject(); ois.close(); return copy; } } // 使用深拷贝 MyClass obj1 = new MyClass(); obj1.setValue(10); MyClass obj2 = obj1.deepCopy(); System.out.println(obj2.getValue()); // 输出 10 obj2.setValue(20); System.out.println(obj1.getValue()); // 输出 10,原对象不受影响 ``` 除了上述方法,还可以使用第三方库如Apache Commons的`SerializationUtils`类、Gson库等来实现对象的深拷贝
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值