Rewrite of the "Java" Clone Clone () method and the equal Equals () method

Source: Internet
Author: User
Tags shallow copy

1. Why rewrite the Clone () method?

The shallow copy in Java does not re-create a new reference space for the object that you want to copy, and we'll rewrite the Clone () method when we need a deep copy.

2. Example of the Equals () and Clone () method overloads

Hourse class:

Importjava.util.Date; Public classHouseImplementscloneable {Private intID; Private DoubleArea ; PrivateDate Whenbulit; House () {} house (intNewId,DoubleNewarea) {ID=newId; Area=Newarea; Whenbulit=NewDate (); }         Public intgetId () {returnID; }         Public voidSetId (intID) { This. ID =ID; }         Public voidSetarea (DoubleArea ) {             This. Area =Area ; }          Public voidSetwhenbulit (Longwhenbulit) {            This. Whenbulit.settime (Whenbulit); }             Public DoubleGetarea () {returnArea ; }         PublicDate Getwhenbulit () {returnWhenbulit; }         Public LongGetwhenbulittime () {returnWhenbulit.gettime (); }       //override the Equals method because we are comparing the time in the date class to the reference address of the object         Public Booleanequals (House obj) {//Obj.getarea () ==this.getarea ( )//Obj.getid () ==this.getid (); //obj.getwhenbuildtime==this.getwhenbuildtime ()            if(Obj.getarea () = = This. Getarea () &&obj.getid () = = This. GetId () &&obj.getwhenbulittime () = = This. Getwhenbulittime ())return true; Else            {                return false; }        }        //if the Equals method is overloaded, hashcode () should also be overloaded by specification, which simply associates hashcode with the passed-in ID.@Override Public inthashcode () {returngetId (); }         PublicObject Clone ()throwsclonenotsupportedexception{//constructs an object house, and uses the ID and areaHouse House =NewHouse ( This. GetId (), This. Getarea ()); //call the Setwhenbuild method in the object, and use GetTime () to get a number of milliseconds. House.setwhenbulit ( This. Getwhenbulit (). GetTime ()); returnHouse ; }    }

Testor class:

 public  class   Testor { static  void  main (string[] args) throws   clonenotsupportedexception{house h1  = new  House (1,200.0 = ==H2);                        System.out.println (H1.equals (H2));                        System.out.println (H1.getwhenbulit ()  == H2.getwhenbulit ());        System.out.println (H1.getwhenbulit (). Equals (H2.getwhenbulit ())); }}

3, the API in the Clone () method introduced the doubts

In the API1.6 saw such a sentence:

the case:     true, but this is not a requirement that must be met.

It is important to note that if we call the code test like this:

 Public classTestcloneImplementscloneable { Public Static voidMain (String []args)throwsclonenotsupportedexception{Testclone TC=NewTestclone (); Try{Object obj=Tc.clone (); System.out.println (obj==TC);//The result is falseSystem.out.println (Obj.equals (TC));//The result is false}Catch(Exception e) {System.out.println ("Exception:" +e.getmessage ()); }    }}

Then the result is false. Because the default condition for equals is the value of the reference address in the comparison variable, the API means that if we need to use the Clone () method, the Equals () method should be overridden in general when overloaded, without the need to compare the object's references, You only need to write the rewritten code as the value of the comparison object.

Rewrite of the "Java" Clone Clone () method and the equal Equals () method

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.