Cloneable interface and the Clone () method of Object

Source: Internet
Author: User

Http://www.cnblogs.com/xrq730/p/4858937.html

Why do you want to clone

Why use cloning, this actually reflects a very real problem, if we have an object:

PublicClass SimpleobjectImplementscloneable{Private String str; public Simpleobject () {System.out.println ("Enter Simpleobject.constructor () "); } public String Getstr () { return str;} public void Setstr ( String str) {this.str = str;} public Object Clone () throws clonenotsupportedexception {return super.clone (); }} 

Now I'm writing a program:

void Main (string[] args) {    new simpleobject (); So0.setstr ("111"); System.out.println ("So0.getstr ():" + so0.getstr ()); Simpleobject so1 = so0; so1.setstr ("222"); System.out.println ("So0.getstr ():" + so0.getstr ()); System.out.println ("So1.getstr ():" + so1.getstr ());        

The result of the operation is obvious:

SO0.GETSTR (): 111so0.getstr (): 222So1.getstr (): 222

Java bottom-up is implemented in C/s + +, the "=" operator, if both sides are object references, the reference to the right of the equal sign in Java is assigned to the reference to the left of the equal sign, and both points to the same piece of memory, so any reference to the memory operation is directly reflected on the other reference.

However, now I want to take this so0 data to do some operation, do not want to change the original so0 content, this time can use cloning, it allows to clone a block and the same object in the heap, and the address of this object is given a new reference , so, Obviously my action on the new reference does not affect the original object.

Of course, understanding clones is a good idea for Java memory areas.

Cloneable interface and the Clone () method of Object

There are many classes in Java that implement the Cloneable interface, such as the familiar ArrayList, Calendar, Date, HashMap, Hashtable, HashSet, LinkedList, and so on.

Or that sentence, for unfamiliar interfaces, methods, the first reaction must be to query the JDK API.

1. Cloneable interface

Summary of three sentences:

(1) This class implements the Cloneable interface to indicate that the clone () method of object can legitimately replicate the class instance by field

(2) If the Clone () method of object is called on an instance that does not implement the Cloneable interface, it causes the clonenotsupporteddexception to be thrown

(3) By convention, a class that implements this interface should use a public method to override the Clone () method of object , and the Clone () method of object is a protected method

2. The clone () method of Object

Creates and returns a copy of this object. For any object x, an expression:

(1)x.clone ()! = X is True

(2)X.clone (). GetClass () = = X.getclass () is true

(3) X.clone (). Equals (x) is generally true, but this is not a requirement that must be met

Clone instance

Modify the main function of the example above:

PublicStaticvoid main (string[] args) throws  exception{simpleobject so0 = new Simpleobject (); So0.setstr ("111" ); Simpleobject so1 = (Simpleobject) So0.clone (); System.out.println ("so0 = = so1?" + (so0 == SO1)); System.out.println ("so0.getclass () = = So1.getclass ()?" + (So0.getclass () ==); System.out.println ("So0.getstr ():" + So0.getstr ()); System.out.println ("So1.getstr ():" + So1.getstr ())}      

Look at the results of the operation:

Enter simpleobject.constructor () So0 = = So1? falseso0.getclass () = = So1.getclass ()?  Trueso0.equals (SO1)?  FalseSo0.getstr (): 111so1.getstr (): 222      

Get three conclusions:

1. Cloning an object does not call the object's construction method because the "Enter Simpleobject.constructor ()" Statement only appears once

2. Clone () method three rules conforming to JDK API

3. SO1 changes to the Simpleobject object str field will no longer affect so0.

Shallow clones and deep clones

Shallow clone (Shallow clone) and deep Clone (deeply clone) reflect that when there are objects in the object, then:

1, shallow cloning, that is, the very surface of the clone, if we want to clone the object, only the clone itself and all the objects it contains the reference address

2. Deep clone, clone all objects except its own object, including all object instances contained by itself

These two concepts should be well understood and do not write code. In other words, all the basic data types, whether shallow or deep, will be cloned in the original value, after all, they are not objects, not stored in the heap.

In fact, the Clone () method of object provides a mechanism for shallow cloning, and if you want to implement a deep clone of an object, there are two ways to do it without introducing a third-party jar package:

1, the object is serialized first, immediately after the deserialization of the

2. First call the Super.clone () method to clone a new object, and then manually assign the cloned non-basic data type (reference type) to the Clone () method of the subclass, such as the Clone () method of ArrayList:

Public Object Clone () {try {    super. Clone (); v.elementdata = arrays.copyof (elementdata, size); V.modcount = 0returncatch//new internalerror ();}}        

Cloneable interface and the Clone () method of Object

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.