Object sorting: Comparator & amp; Comparable

Source: Internet
Author: User

When all objects are stored in the collection, we need to sort them by Comparator or Comparable to simply sort objects or customize the sorting.
Example: an object class:
Java code
Public class UserPo {
// Name
Private String name;
// Age
Private int age;

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;
}

}
 
1: Use the Comparator interface for sorting: The compare method is implemented. The size is determined based on the negative integer, zero, or positive integer returned by the first parameter smaller than, equal to, or greater than the second parameter.
A comparison function that forcibly sorts the collection objects. Comparator can be passed to the sort method (such as Collections. sort or Arrays. sort) to allow precise control over the sorting order. You can also use Comparator to control the order of certain data structures (such as ordered set or ordered ing), or provide sorting for object collections without natural order.
Import java. util. Comparator;
Java code

Public class MyCompare implements Comparator <Object> {

Public int compare (Object o0, Object o1 ){
UserPo user0 = (UserPo) o0;
UserPo user1 = (UserPo) o1;
If (user0.getAge ()> user1.getAge ()){
Return 1; // The first is greater than the second
} Else if (user0.getAge () <user1.getAge ()){
Return-1; // The first is smaller than the second
} Else {
Return 0; // equal
}
}
}
 
Test code:
Java code
Import java. util. ArrayList;
Import java. util. Collections;

Public class Test {

Public static void main (String args []) {

String SQL = "select name, age from users ";
// Obtain data from the database and assemble the object set
ArrayList <UserPo> array = BaseDao. getyAll (SQL );
MyCompare comp = new MyCompare ();
// Execute the sorting method
Collections. sort (array, comp );
For (UserPo p: array ){
System. out. println (p. getName () + ":" + p. getAge ());
}

}
}
 
GetAll () method:
Public static ArrayList <UserPo> getyAll (String SQL ){
Java code
ArrayList <UserPo> list = new ArrayList <UserPo> ();
ResultSet rs = null;
PreparedStatement ps = null;
Try {
Connection con = JdbcUtils. getMsConnection ();
Ps = con. prepareStatement (SQL );
Rs = ps.exe cuteQuery ();
While (rs. next ()){
UserPo p = new UserPo ();
P. setName (rs. getString ("name "));
P. setAge (rs. getInt ("age "));
List. add (p );
}
} Catch (Exception e ){
E. printStackTrace ();
}
Return list;
 
2: Use the Comparable interface to complete sorting: the object list (and array) of this interface can be automatically sorted through Collections. sort (and Arrays. sort. The object implementing this interface can be used as a key or element in an ordered set in an ordered ing without specifying a comparator.
Modify the UserPo class
Java code
Import java. util. ArrayList;
Import java. util. Collections;
Public class UserPo implements Comparable {

Private String name;

Private int age;

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;
}
/**
* CompareTo
*/
Public int compareTo (Object o ){
Return this. age-(UserPo) o). getAge ();
}
// Test
Public static void main (String args []) {
String SQL = "select name, age from users ";
ArrayList <UserPo> array = BaseDao. getyAll (SQL );
// Execute the sorting method
Collections. sort (array );
For (UserPo p: array ){
System. out. println (p. getName () + ":" + p. getAge ());
}
}
}
 
Comparison of the two interfaces:
 
1: Comparable is the sorting of methods defined inside the set, and Comparator is the sorting implemented outside the set.
2: If a class implements the Camparable interface, it indicates that the objects of this class can be compared with each other. A set composed of these class objects can be directly sorted using the sort method. Generally, all the beans we write need to implement this interface, which is also the Standard javabean specification.
3: Comparator can be seen as an algorithm implementation that separates algorithms from data. Comparator can also be used in the following two environments:
1. Category designers do not consider comparison issues and do not implement Comparable. You can use Comparator to sort objects without changing the object itself.
2. Multiple sorting criteria can be used, such as ascending or descending.

Author's "Brave track"
 

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.