java-Object Ordering

Source: Internet
Author: User

In business logic, we often need to sort the list as follows:

Collections.sort (l);

If the elements in L are of type string, you will find that the sort method will be sorted alphabetically. If the elements in L are of type date, the sort method is sorted using the calendar order. This is because both string and date implement the comparable interface, which means that if you want to sort an object, it must implement the comparable interface. In the Java language, the classes that implement the interface are listed as follows:

Classes Implementing comparable
Class Natural Ordering
Byte Signed numerical
Character Unsigned Numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

If a class is written by someone else and it really does not implement the interface, is it powerless to sort the problem? No, sort has another form:

Collections.sort (list, comparator)
only these two methods. If you have not done both of these methods, then the sort method throws an exception. 
Comparable interface
The comparable interface form is as follows:
Public interface Comparable<t> {public    int compareTo (T o);}
Yes, it has only one way. You must define how the object is compared in this method. Here is a demo:
Sortdemo.java
 Packagecolloections;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List; Public classSortdemo { Public Static voidMain (string[] args) {//TODO auto-generated Method Stubnew Sortdemo (). sort ();    }   Private voidsort () {person P1=NewPerson ("Bob", 5); Person P2=NewPerson ("Albert", 8); Person P3=NewPerson ("Bob", 13); List<Person> list =NewArraylist<person>();        List.add (p1);        List.add (p2);        List.add (p3); System.out.printf ("Before sorting:%n");  for(person person:list) {System.out.printf (person.tostring ());        } collections.sort (list); System.out.printf ("After sorting:%n");  for(person person:list) {System.out.printf (person.tostring ()); }    }}classPersonImplementsComparable<person>{     PublicString name;  Public intAge ;  PublicPerson (String N,inta) {Name=N; Age=A; }         PublicString toString () {returnString.Format ("Name is%s, age is%d%n", name, age); } @Override Public intcompareTo (Person o) {//TODO auto-generated Method Stub//sort Priority is: name/Age        intNamecomp = This. Name.compareto (O.name); return(Namecomp! = 0? Namecomp: ( This. Age-o.age)); }}

The program output is as follows:

Before sorting:
Name is Bob, which is 5
Name is Albert, age is 8
Name is Bob, which is 13
After sorting:
Name is Albert, age is 8
Name is Bob, which is 5
Name is Bob, which is 13

Comparator
The comparator interface provides a separate sorting function, which has two uses: 1. You do not want to use a class with the CompareTo logic to sort; 2. A class does not inherit the comparable interface. Visible, the comparator interface makes sorting more flexible. Its form is as follows:
 Public Interface Comparator<t> {    int  compare (t O1, T O2);}

Yes, one way is enough. When O1 is less than O2, equal to, greater than, the Compare method returns a negative number, 0, or a positive number. Use the demo as follows:

Sortdemo.java

 Packagecolloections;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List; Public classSortdemo { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//new Sortdemo (). sort ();        NewSortdemo (). SORTBYCOMPARATPR (); }        Private voidSortbycomparatpr () {person P1=NewPerson ("Bob", 5); Person P2=NewPerson ("Albert", 8); Person P3=NewPerson ("Bob", 13); List<Person> list =NewArraylist<person>();        List.add (p1);        List.add (p2);        List.add (p3); System.out.printf ("Before sorting:%n");  for(person person:list) {System.out.printf (person.tostring ()); } Personcomparator Comparator=NewPersoncomparator ();        Collections.sort (list, comparator); System.out.printf ("After sorting:%n");  for(person person:list) {System.out.printf (person.tostring ()); }    }        Private voidsort () {person P1=NewPerson ("Bob", 5); Person P2=NewPerson ("Albert", 8); Person P3=NewPerson ("Bob", 13); List<Person> list =NewArraylist<person>();        List.add (p1);        List.add (p2);        List.add (p3); System.out.printf ("Before sorting:%n");  for(person person:list) {System.out.printf (person.tostring ());        } collections.sort (list); System.out.printf ("After sorting:%n");  for(person person:list) {System.out.printf (person.tostring ()); }    }}classPersonImplementsComparable<person>{     PublicString name;  Public intAge ;  PublicPerson (String N,inta) {Name=N; Age=A; }         PublicString toString () {returnString.Format ("Name is%s, age is%d%n", name, age); } @Override Public intcompareTo (Person o) {//TODO auto-generated Method Stub//sort Priority is: name/Age        intNamecomp = This. Name.compareto (O.name); return(Namecomp! = 0? Namecomp: ( This. Age-o.age)); }}classPersoncomparatorImplementsComparator<person>{@Override Public intCompare (person O1, person O2) {//TODO auto-generated Method Stub                returnO2.compareto (O1); }}

The program output is as follows:

Before sorting:
Name is Bob, which is 5
Name is Albert, age is 8
Name is Bob, which is 13
After sorting:
Name is Bob, which is 13
Name is Bob, which is 5
Name is Albert, age is 8

Note that the output here is in descending order, because the Compare method is used to compare O2 with O1. If you need to sort in ascending order, you can modify the following:

return O1.compareto (O2);

Note, do not modify this:

return -o2.compareto (O1);

This is because the negative value returned by CompareTo is indeterminate, and there is a special negative integer, and negative results remain negative:

-integer.min_value = = Integer.min_value

java-Object Ordering

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.