Java object sorting

Source: Internet
Author: User
1. Implement the comparable interface of the class to be compared

 
Public class menupage implements comparable <menupage> {private string text; private string seq; // The Order of menus on the page is 0, 1, 2 .... @ Overridepublic int compareto (menupage O) {// return integer. valueof (this. attribute1)-integer. valueof (O. attribute1); int result = integer. valueof (this. SEQ ). compareto (integer. valueof (O. SEQ); If (result = 0) return 1; elsereturn result ;}

Use treeset (the compareable interface class will be automatically called) for comparison during addition.

 
Set <menupage> List = new treeset <menupage> (); list. add (page1); list. add (page2); list. add (page3); list. add (page4 );
2. Use manual sorting (compareable is not required when defining classes)

List <menupage> List = new arraylist <menupage> (); list. add (page1); list. add (page2); list. add (page3); list. add (page4); collections. sort (list, new comparator <menupage> () {@ overridepublic int compare (menupage O1, menupage O2) {return integer. valueof (o1.getseq ()). compareto (integer. valueof (o2.getseq ()));}});

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.