Objects are in ascending or descending order based on a certain attribute.

Source: Internet
Author: User

It only sorts by the id in the object. It can also be implemented if it is in ascending or descending order of other fields. [Java]/*** sort personal information ** @ author wWX154783 **/public class PersonSort {public static void main (String [] args) {List <Person> list = new ArrayList <Person> (); for (int I = 0; I <10; I ++) {Person person = new Person (); person. setId (new Random (). nextInt (50); list. add (person);} System. out. println ("Original: \ t" + list); Collections. sort (list, new PersonOrderByIdAsc (); System. out. println ("Ascending Order: \ t" + list); Collections. sort (list, new PersonOrderByIdDesc (); System. out. println ("descending order: \ t" + list); }}/ * Person */class Person implements Comparator <Person> {private int id; private int age; private String name; private String sex; private String address; public int compare (Person o1, Person o2) {return 0;} public int getId () {return id;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String getSex () {return sex;} public void setSex (String sex) {this. sex = sex;} public String getAddress () {return address;} public void setAddress (String address) {this. address = address ;}@ Override public String toString () {return "id =" + this. id ;}}/* sort by person id in ascending order */class PersonOrderByIdAsc extends Person {@ Override public int compare (Person o1, Person o2) {if (o1.getId ()> o2.getId () {return 1;} else if (o1.getId () <o2.getId () {return-1 ;}else {return 0 ;}}} /* sort by person id in descending order */class PersonOrderByIdDesc extends Person {@ Override public int compare (Person o1, Person o2) {if (o1.getId () <o2.getId ()) {return 1 ;}else if (o1.getId ()> o2.getId () {return-1 ;}else {return 0 ;}}}

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.