The Clone method of Java

Source: Internet
Author: User

Recently I encountered a bit of a problem writing the squared method in the Hugenumber class. The problem was found to be not cloned on the object.

The following is a summary of the several points on cloning;

----------------------------------------Split Line--------------------------------

One of the advantages of the Java language is that it cancels the concept of pointers, but it also causes many programmers to ignore objects and references in programming often.

The difference, especially the first C, C + + after the Java programmer. And because Java cannot solve object duplication by simply assigning a value

, the Clone () method is often used to replicate objects during the development process. For example, a function parameter type is a custom class

, this is a reference pass instead of a value pass . Here is a small example:

 Public classTestclone { Public voidChangea (A a) {A.name= "B"; }     Public voidChangint (inti) {i=i*2+100; }        /**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method StubTestclone test=NewTestclone (); A A=NewA (); A.name= "a"; System.out.println ("Before Change:a.name=" +a.name);        Test.changea (a); System.out.println ("After Change:a.name=" +a.name); intI=1; System.out.println ("Before change:i=" +i);        Test.changint (i); System.out.println ("After change:i=" +i); }}

When the Class A member variable type is the basic type of Java (plus string type), it is possible to implement the simple clone (called Shadow clone) as above.

However, if a class A member variable is an array or complex type, deep clone must be implemented.

 Public Object Clone () {        null;         Try {            super. Clone ();            O.name= (string[]) name.clone (); // It 's very simple, actually. ^_^        Catch (clonenotsupportedexception e) {            e.printstacktrace ();        }         return o;    }

Otherwise the clone is actually the address of the original object.

The Clone method of Java

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.