Java shallow clone and deep clone

Source: Internet
Author: User
Tags shallow copy

Concept: The slang is to copy a copy

General implementation:

Implementing the Cloneable Interface Override Clone () method

Part of the Code


Public Object Clone () {
Object o = null;
try {
o = (Student) super.clone ();//Clone () in object identifies which one you want to copy
An object.
} catch (Clonenotsupportedexception e) {
System.out.println (E.tostring ());
}
return o;
}

Note: Shallow copy cannot copy references at the same time

If you need to copy a reference, the object you want to reference is also cloned to do a deep copy

A better approach is to use serialization (often-called serialization) for deep replication (no need to implement cloneable interface, need to implement Serializable interface)

See part of the code

Public Object Deepclone () throws IOException, Optionaldataexception,
classnotfoundexception {
Write an object into the stream
Bytearrayoutputstream bo = new Bytearrayoutputstream ();
ObjectOutputStream oo = new ObjectOutputStream (bo);
Oo.writeobject (this);
Read it from the stream.
Bytearrayinputstream bi = new Bytearrayinputstream (Bo.tobytearray ());
ObjectInputStream oi = new ObjectInputStream (BI);
Return (Oi.readobject ());
}


For more information, please follow the public number: it haha (it_haha)


650) this.width=650; "style=" Width:auto;height:auto; "alt=" 640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1 "src=" http:/ /mmbiz.qpic.cn/mmbiz_jpg/ Xruic8oiyw5upuvcv1cifldft9jiazjawtzuqviaytibsdh5le8ricktou2mn0iblkxzw5kgo4ntibmclfng97qyqsntq/640?wx_fmt=jpeg &wxfrom=5&wx_lazy=1 "/>


This article is from the "doujh" blog, make sure to keep this source http://doujh.blog.51cto.com/10177066/1932919

Java shallow clone and deep clone

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.