"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:

  1. public class Mystring {


  2. public static void Main (string[] args) {


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


  4. Person[] b={New Person ("small white", new Person ("black", 19),

  5. New person ("Little Red", +), new person ("Little Violet", 20)};

  6. Arrays.sort (a);

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

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

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


  10. Arrays.sort (b);

  11. for (int i=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 int age;


  19. Public person (String Name,int age) {

  20. This.name=name;

  21. This.age=age;


  22. }


  23. }

Copy Code

program run Result:
650) this.width=650; "id=" aimg_275 "src=" http://techfoxbbs.com/data/attachment/forum/201505/21/ 105254iibwc84wnhsqbjss.png "class=" Zoom "width=" "alt=" 105254iibwc84wnhsqbjss.png "/> 

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

650) this.width=650; "id=" aimg_276 "src=" http://techfoxbbs.com/data/attachment/forum/201505/21/ 105311pdudux7895h5j5a1.png "class=" Zoom "width=" "alt=" 105311pdudux7895h5j5a1.png "/>"


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:

  1. public class Mystring {


  2. public static void Main (string[] args) {


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


  4. Person[] b={New Person ("small white", new Person ("black", 19),

  5. New person ("Little Red", +), new person ("Little Violet", 20)};

  6. Arrays.sort (a);

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

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

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


  10. Arrays.sort (b);

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

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

  13. }


  14. }

  15. Custom Classes

  16. Class Person implements comparable<person>{


  17. public String name;


  18. public int age;


  19. Public person (String Name,int age) {

  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 int compareTo (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. }

Copy Code



650) this.width=650; "id=" aimg_277 "src=" http://techfoxbbs.com/data/attachment/forum/201505/21/ 105342evxcx50oz0x0iaiz.png "class=" Zoom "width=" 391 "alt=" 105342evxcx50oz0x0iaiz.png "/> 

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.

  1. public class Mystring {


  2. public static void Main (string[] args) {


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


  4. Person[] b={New Person ("small white", new Person ("black", 19),

  5. New person ("Little Red", +), new person ("Little Violet", 20)};

  6. Arrays.sort (a);

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

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

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


  10. Arrays.sort (B,new personcomparator ());

  11. for (int i=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 int age;


  19. Public person (String Name,int age) {

  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 implements comparator<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 int Compare (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. }

Copy Code

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

  1. Custom class person implementation cloneable interface

  2. Class Person implements Cloneable {

  3. public String name;


  4. public int age;


  5. Public person (String Name,int age) {

  6. This.name=name;

  7. This.age=age;


  8. }

  9. Overriding the Clone method of object

  10. @Override

  11. Protected Object Clone () throws Clonenotsupportedexception

  12. {

  13. return Super.clone ();

  14. }


  15. }

Copy Code

Cloned calls:

  1. public static void Main (string[] args) {


  2. Person Temp=new person ("Wang Nima", 18);


  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. }

Copy Code

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 a better


"Java object comparer and cloning"

Related Article

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.