Java set sorting

Source: Internet
Author: User

Using the collections. sort method to complete a small sorting function, you also have a simple understanding of the collections. sort method.

The sorting of Java Collection classes mainly uses the collections. sort method. Collections and collection are different. The former is a class, and the latter is an interface. Tip: when implementing the interface method, you only need to compare two numbers. If the value is large, 1 is returned. If the value is equal, 0 is returned, and less than-1 is returned. Simply put, write "Num> S. Num?" In the method? 1 :( num = S. Num? 0:-1); num indicates the number to be compared, and S. Num indicates the number to be compared,

1. collection. Sort (list arg0 );
This is the simplest sorting method. You only need to implement its comparable interface and the Public int compareto (Object arg0) method.

If you want to sort people in the list array, you only need to collect. Sort (people.
2. collection. srot (list arg0, comparator arg1 );
The comparator is added to facilitate management with greater flexibility. The comparator can be used as an internal static class for ease of management. The comparator must implement the comparator interface.

If you want to sort objects by a certain attribute in the list, you need to add a comparator. For example, if people is a people object set and the people object has the age attribute, you need to sort all people objects by age. The Code is as follows:

 

Add the internal static class peoplecomparator to the people class:

// Ignore the null age attribute

Public static class peoplecomparator implements comparator <people> {

Public int compare (People O1, people O2 ){

Return o1.getage (). compareto (o2.getage ());

}

}

The program has list <people> people. To sort the people set, add

Collections. Sort (people, new people. peoplecomparator.

 

 

 

I am comparing dishes. If there is any mistake, I hope the viewer will correct me. Thank you !!!! Haha ^_^

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.