欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java對(duì)象的淺拷貝和深拷貝區(qū)別

在Java中,對(duì)象的拷貝可以分為淺拷貝和深拷貝兩類。

淺拷貝

淺拷貝是指只復(fù)制對(duì)象自身,而不復(fù)制對(duì)象內(nèi)部包含的引用類型變量所引用的對(duì)象。即新的對(duì)象持有原對(duì)象中引用類型變量的引用,這兩個(gè)對(duì)象共用同一個(gè)引用類型對(duì)象。淺復(fù)制使用clone()方法實(shí)現(xiàn)。

public class ShallowCopy implements Cloneable {
private int[] arr;
ShallowCopy() {
arr = new int[10];
for (int i = 0; i< arr.length; i++) {
arr[i] = i;
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
ShallowCopy obj1 = new ShallowCopy();
ShallowCopy obj2 = (ShallowCopy) obj1.clone();
System.out.println(obj1.get(2)); // 2
System.out.println(obj2.get(2)); // 2
obj1.set(2, 100);
System.out.println(obj1.get(2)); // 100
System.out.println(obj2.get(2)); // 100
}
}

深拷貝

深拷貝是指不僅復(fù)制對(duì)象自身,還要復(fù)制對(duì)象內(nèi)部包含的引用類型變量所引用的對(duì)象。即新的對(duì)象和原對(duì)象所引用的引用類型對(duì)象完全獨(dú)立,互不影響。深復(fù)制可以通過(guò)實(shí)現(xiàn)Serializable(Java對(duì)象序列化接口)實(shí)現(xiàn)。

import java.io.*;
public class DeepCopy implements Serializable {
private int[] arr;
DeepCopy() {
arr = new int[10];
for (int i = 0; i< arr.length; i++) {
arr[i] = i;
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
public DeepCopy deepCopy() throws IOException, ClassNotFoundException, OptionalDataException {
// write the object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
// read the object from a byte array
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (DeepCopy) ois.readObject();
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IOException {
DeepCopy obj1 = new DeepCopy();
DeepCopy obj2 = obj1.deepCopy();
System.out.println(obj1.get(2)); // 2
System.out.println(obj2.get(2)); // 2
obj1.set(2, 100);
System.out.println(obj1.get(2)); // 100
System.out.println(obj2.get(2)); // 2
}
}
上一篇php crc
下一篇php craypt