Implement the age of the person object, from small to large sort

Source: Internet
Author: User

1. Implementation sequencing

1PackageCom.app;23ImportJava.util.ArrayList;4ImportJava.util.Collections;5ImportJava.util.Comparator;6ImportJava.util.List;78PublicClass A1Extendsb{910PublicStaticvoidMain (string[] args) {List<person> List =GetData ();12//Sort13Collections.sort (list, comparator);1415For(Person Person:list) {System.out.println ("person" + person.getname () + "" +Person.getage ());17}1819}2021st/**22* Age is sorted by small to large23*/24static Comparator<person> Comparator =New comparator<person>() {25@Override26PublicIntCompare (person P1, person p2) {27if (P1.getage () >P2.getage ()) {28return 1;//Positive29}Elseif (P1.getage () <P2.getage ()) {30return-1;//Negative31}Else{32return 0;//Equal to 033}34}35};3637StaticPrivate list<person>GetData () {List<person> List =New arraylist<>() ;39P1 =NewPerson ();P1.setage (10);P1.setname ("P1");43P2 person =NewPerson ();P2.setage (30);P2.setname ("P2");47P3 =NewPerson ();P3.setage (20);P3.setname ("P3");51P4 person =new54 p4.setname ("P4"  56  List.add (p1);  List.add (p2);  List.add (p3);  List.add (p4); 61 return list; 62 }63}       

2. Create the Person class

PackageCom.app;PublicClassperson {PrivateIntAge;Private String name; public int Getage () { Span style= "color: #0000ff;" >returnpublic void setage (int  age) {this.age = Age;} public String GetName () { return name; public void SetName ( String name {this.name = name;}}     

3. Results of operation (to achieve the sorting of age)

Person P1, Person P4, p3 person p2


Get ""

Implement the age of the person object, from small to large sort

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.