Java object comparer and cloning

Source: Internet
Author: User
Tags comparable

I. Comparator comparable and comparator

The previous blog introduced the Tool class arrays tool class. We can call the Arrays.sort () function on an array of basic types to sort the array. Sorting operations are often used in daily development. Then can the string class and custom classes be sorted using Arrays.sort (). Let's try it as follows:

Java code

publicclassmystring {

Publicstaticvoidmain (string[] args) {

String []a={"Morning", "noon", "Afternoon", "evening", "Evening"};

Person[] b={Newperson ("Small white", ","), Newperson ("Little Black", 19),

Newperson ("Little Red", Newperson), ("Little Violet", 20)};

Arrays.sort (a);

for (inti=0;i<a.length;i++)

System.out.print (A[i]);

System.out.print ("\ r \ n");

Arrays.sort (b);

for (inti=0;i<b.length;i++)

System.out.println (B[i]);

}

}

Custom Classes

Classperson {

Publicstring name;

Publicintage;

Publicperson (String name,intage) {

This.name=name;

This.age=age;

}

}

Program Run Result:

We find that string can call the Arrays.sort () function, and we customize the person class to make an error, looking at the wrong keyword comparable

Open String Source

By introducing the comparator comparable, we use the comparable interface below to implement the person using Arrays.sort () to sort the ascending order by age.

The comparable interface is able to sort the objects that implement its classes, using the CompareTo function primarily for sorting. The CompareTo function returns the int type, which returns -1,0,1, which corresponds to less than, equal to, greater than.

Change the code to:

Java code

publicclassmystring {

Publicstaticvoidmain (string[] args) {

String []a={"Morning", "noon", "Afternoon", "evening", "Evening"};

Person[] b={Newperson ("Small white", ","), Newperson ("Little Black", 19),

Newperson ("Little Red", Newperson), ("Little Violet", 20)};

Arrays.sort (a);

for (inti=0;i<a.length;i++)

System.out.print (A[i]);

System.out.print ("\ r \ n");

Arrays.sort (b);

for (inti=0;i<b.length;i++)

System.out.println (B[i]);

}

}

Custom Classes

Classperson implementscomparable<person>{

Publicstring name;

Publicintage;

Publicperson (String name,intage) {

This.name=name;

This.age=age;

}

Comparator comparison function

/**

* Returns 1 if the current object is less than the comparison object

* Returns 0 if the current object equals the comparison object

* Returns 1 if the current object is greater than the comparison object

*/

@Override

Publicintcompareto (person O) {

Object is empty, throws a null pointer exception

if (o==null)

Thrownewnullpointerexception ();

if (this.age<o.age)

return-1;

if (this.age>o.age)

RETURN1;

Return0;

}

Overriding the ToString Method

@Override

Publicstring toString () {

return "person [name=" + name + ", age=" + Age + "]";

}

}

Operation Result:

To implement the comparer comparable interface for the custom person, you can call Arrays.sort () to sort.

There is another way to implement the comparator interface.

Java code

publicclassmystring {

Publicstaticvoidmain (string[] args) {

String []a={"Morning", "noon", "Afternoon", "evening", "Evening"};

Person[] b={Newperson ("Small white", ","), Newperson ("Little Black", 19),

Newperson ("Little Red", Newperson), ("Little Violet", 20)};

Arrays.sort (a);

for (inti=0;i<a.length;i++)

System.out.print (A[i]);

System.out.print ("\ r \ n");

Arrays.sort (B,newpersoncomparator ());

for (inti=0;i<b.length;i++)

System.out.println (B[i]);

}

}

Custom Classes

Classperson {

Publicstring name;

Publicintage;

Publicperson (String name,intage) {

This.name=name;

This.age=age;

}

@Override

Publicstring toString () {

return "person [name=" + name + ", age=" + Age + "]";

}

}

Classpersoncomparator implementscomparator<person>{

Comparator comparison function

/**

* Returns 1 if the current object is less than the comparison object

* Returns 0 if the current object equals the comparison object

* Returns 1 if the current object is greater than the comparison object

*/

@Override

Publicintcompare (person O1, person O2) {

Object is empty, throws a null pointer exception

if (o1==null| | O2==null)

Thrownewnullpointerexception ();

if (o1.age<o2.age)

return-1;

if (o1.age>o2.age)

RETURN1;

Return0;

}

}

Two. Cloning clone of an object

Copies a copy of an object, called the object's cloning technique. Cloning an object is a two-step move.

1. Implement cloneable Tag interface

Cloneable is a markup interface that does not have any methods defined by this interface. Just as a token to the virtual machine.

2. Overriding the Clone method of object

Java code

Custom class person implementation cloneable interface

Classperson implementscloneable {

Publicstring name;

Publicintage;

Publicperson (String name,intage) {

This.name=name;

This.age=age;

}

Overriding the Clone method of object

@Override

Protectedobject Clone () throwsclonenotsupportedexception

{

Returnsuper.clone ();

}

}

Cloned calls:

Java code

Publicstaticvoidmain (string[] args) {

Person Temp=newperson ("Wang Nima", 18);

try{

Person ok= (person) temp.clone ();//Convert the object class to person,

System.out.println (ok.name);//Output Wang Nima

} catch (Clonenotsupportedexception e) {

E.printstacktrace ();

}

}

This can be done to clone an object, when we want to create a series of similar objects, you can consider the use of cloning technology can get better performance, than you create better.

Technology sharing: Edith Academy

Java object comparer and cloning

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.