java clone 中的浅复制和深复制 (三)

2014-11-24 11:10:40 · 作者: · 浏览: 2
nal serializable object
ColoredCircle c1 = new ColoredCircle(100, 100);
// print it
System.out.println("Original = " + c1);

ColoredCircle c2 = null;

// deep copy
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
// serialize and pass the object
oos.writeObject(c1);
oos.flush();
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bin);
// return the new object
c2 = (ColoredCircle) ois.readObject();

// verify it is the same
System.out.println("Copied = " + c2);
// change the original object's contents
c1.setX(200);
c1.setY(200);
// see what is in each one now
System.out.println("Original = " + c1);
System.out.println("Copied = " + c2);
} catch (Exception e) {
System.out.println("Exception in main = " + e);
} finally {
try {
oos.close();
ois.close();
} catch (IOException e) {
System.out.println(e);
}

}
}
}

public class DeepCopy {

static public void main(String[] args) {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;

try {
// create original serializable object
ColoredCircle c1 = new ColoredCircle(100, 100);
// print it
System.out.println("Original = " + c1);

ColoredCircle c2 = null;

// deep copy
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
// serialize and pass the object
oos.writeObject(c1);
oos.flush();
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bin);
// return the new object
c2 = (ColoredCircle) ois.readObject();

// verify it is the same
System.out.println("Copied = " + c2);
// change the original object's contents
c1.setX(200);
c1.setY(200);
// see what is in each one now
System.out.println("Original = " + c1);
System.out.println("Copied = " + c2);
} catch (Exception e) {
System.out.println("Exception in main = " + e);
} finally {
try {
oos.close();
ois.close();
} catch (IOException e) {
System.out.println(e);
}

}
}
}

程序输出结果:


[java]
Original = x=100,y=100
Copied = x=100,y=100
Original = x=200,y=200
Copied = x=100,y=100

Original = x=100,y=100
Copied = x=100,y=100
Original = x=200,y=200
Copied = x=100,y=100