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

Public class Mystring {

  1. Public Static voidMain (string[] args) {

  2. String []a={"Morning","Noon","Afternoon","Evening","Evening"};

  3. Person[] b={ newperson ("small white",newperson ("Black",19 ),

  4. New Person ("Little Red",+),newperson ("Little Purple")};

  5. Arrays.sort (a);

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

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

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

  9. Arrays.sort (b);

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

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

  12. }

  13. }

  14. Custom Classes

  15. class person {

  16. Public String name;

  17. Public intage;

  18. Public Person (String name,intage) {

  19. this. name=name;

  20. this. age=age;

  21. }

  22. }

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

  1. Public class Mystring {

  2. Public Static voidMain (string[] args) {

  3. String []a={"Morning","Noon","Afternoon","Evening","Evening"};

  4. Person[] b={ newperson ("small white",newperson ("Black",19 ),

  5. New Person ("Little Red",+),newperson ("Little Purple")};

  6. Arrays.sort (a);

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

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

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

  10. Arrays.sort (b);

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

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

  13. }

  14. }

  15. Custom Classes

  16. class Person implementscomparable<person>{

  17. Public String name;

  18. Public intage;

  19. Public Person (String name,intage) {

  20. this. name=name;

  21. this. age=age;

  22. }

  23. Comparator comparison function

  24. /**

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

  26. * Returns 0 if the current object equals the comparison object

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

  28. */

  29. @Override

  30. Public intcompareTo (person O) {

  31. Object is empty, throws a null pointer exception

  32. if (o==null)

  33. Throw New NullPointerException ();

  34. if (this. age<o.age)

  35. return-1;

  36. if (this. age>o.age)

  37. return 1;

  38. return 0;

  39. }

  40. Overriding the ToString Method

  41. @Override

  42. Public String toString () {

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

  44. }

  45. }

Operation Result:

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

there is another way to achieve Comparator interface.

Java code

  1. Public class Mystring {

  2. Public Static voidMain (string[] args) {

  3. String []a={"Morning","Noon","Afternoon","Evening","Evening"};

  4. Person[] b={ newperson ("small white","newPerson" ("small Black"),

  5. New Person ("Little Red",+),newperson ("Little Purple")};

  6. Arrays.sort (a);

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

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

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

  10. Arrays.sort (b,newpersoncomparator ());

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

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

  13. }

  14. }

  15. Custom Classes

  16. class person {

  17. Public String name;

  18. Public intage;

  19. Public Person (String name,intage) {

  20. this. name=name;

  21. this. age=age;

  22. }

  23. @Override

  24. Public String toString () {

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

  26. }

  27. }

  28. class Personcomparator implementscomparator<person>{

  29. Comparator comparison function

  30. /**

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

  32. * Returns 0 if the current object equals the comparison object

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

  34. */

  35. @Override

  36. Public intCompare (person O1, person O2) {

  37. Object is empty, throws a null pointer exception

  38. if (o1==null| | o2==null)

  39. Throw New NullPointerException ();

  40. if (O1.age<o2.age)

  41. return-1;

  42. if (O1.age>o2.age)

  43. return 1;

  44. return 0;

  45. }

  46. }

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

  1. Custom class person implementation cloneable interface

  2. class Person implementscloneable {

  3. Public String name;

  4. Public intage;

  5. Public Person (String name,intage) {

  6. this. name=name;

  7. this. age=age;

  8. }

  9. Overriding the Clone method of object

  10. @Override

  11. protected Object Clone () throwsClonenotsupportedexception

  12. {

  13. return Super. Clone ();

  14. }

  15. }

Cloned calls:

Java code

    1. Span>public static void main (string[] args) {

    2. person temp= new person ( "Wang Nima" , + );

    3. try {

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

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

    6. }  catch ( Clonenotsupportedexception e) {

    7. E.printstacktrace ();

    8. }

    9. }

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: www.kaige123.com

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.