Java comparable and cloneable interfaces

Source: Internet
Author: User
Tags comparable shallow copy

The comparable interface defines the CompareTo method, which is used to compare objects.

For example, in Javaapi, the Integer, BigInteger, String, and date classes are defined as follows

Cloneable interface

The Cloneable interface gives an object that can be cloned.

To appear when you need to create a copy of the object. For this purpose, you need to use the Clone method

Cloneable is defined as follows:

Call Clone () directly, the basic type data inside the object is copied directly, but the reference type data, is to copy his reference, this is called shallow copy, not deep copy

Package Test;import Java.util.date;public class House implements cloneable,comparable{private int Id;private double area ;p rivate Date whenbuilt;public House (Int. id,double area) {//TODO auto-generated constructor stubthis.id = Id;this.area = Area;whenbuilt = new Date ();} public int getId () {return ID;} Public double Getarea () {return area;} Public Date getwhenbuilt () {return whenbuilt;} Public Object Clone () throws Clonenotsupportedexception{return Super.clone ();} @Overridepublic int compareTo (Object o) {//TODO auto-generated Method stubif (Area > (house) O). Area) {return 1;} else if (area < (house) O). Area) {return-1;} else {return 0;}} public static void Main (String [] args) throws Clonenotsupportedexception {House house1 = new House (1, 1750.50); House House2 = (house) House1.clone ();}}

  

The example is to call clone directly () so the whenbuilt address is the same and the content is the same

If you change Clone () to this

Whenbuilt address is different, the content is the same

Java comparable and cloneable interfaces

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.