22.Collections sorting

Source: Internet
Author: User

 Packageentity; Public classStudentImplementscomparable{Private intnumber=0;//School Number    PrivateString name= "";//Student Name    PrivateString gender= "";//Sex     Public intGetNumber () {returnNumber ; }     Public voidSetnumber (intNumber ) {         This. number=Number ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. name=name; }     PublicString Getgender () {returngender; }     Public voidSetgender (String gender) { This. gender=gender; }     Public intcompareTo (Object obj) {Student Student=(Student) obj; if( This. number==Student.number) {              return0;//If the study number is the same, then the two are equal.}Else if( This.number>Student.getnumber ()) {             return1;//If the student's number is greater than the number of incoming students}Else{             return-1;//If the student's number is less than that of the incoming student ,        }    }}
 Packagetest;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Iterator;Importentity. Student; Public classCollectionsdemo { Public Static voidMain (string[] args) {Student student1=NewStudent (); Student1.setnumber (5); Student Student2=NewStudent (); Student2.setnumber (2); Student Student3=NewStudent (); Student3.setnumber (1); Student Student4=NewStudent (); Student4.setnumber (4); ArrayList<Student> list=NewArraylist<student>();        List.add (STUDENT1);        List.add (Student2);        List.add (STUDENT3);        List.add (STUDENT4); System.out.println ("--------------before sorting"); Iterator<Student> iterator=List.iterator ();  while(Iterator.hasnext ()) {Student Stu=Iterator.next ();        System.out.println (Stu.getnumber ()); }        //sort list by using the Sort method of collectionsSystem.out.println ("--------------after sorting");         Collections.sort (list); Iterator=List.iterator ();  while(Iterator.hasnext ()) {Student Stu=Iterator.next ();        System.out.println (Stu.getnumber ()); }     }}

22.Collections sorting

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.