The sort method of Java

Source: Internet
Author: User

Java's sort method is generally two, divided Array.Sort () and Collection.sort ()

Arrays.sort (t[], Comparator < super T > C) method is used to sort the object array by user custom rule. Collections.sort (LIST&LT;T&GT;, Comparator <? super T > C) methods are used for object collections sorted by user-defined rules. Comparable is a generic interface that users can implement to accomplish their own specific comparisons. We use arrays to sort the arrays, using collections to sort the combined frame containers, such as arrayslist,linkedlist. Generally when the object itself implements the comparable interface, such as the string type and the integer type, orthe lists object string itself implements the comparable interface and contains the CompareTo method, so you can call the sort method directly, sort by natural order, ascending sort. However, when the object does not implement the interface, it is sorted by a custom method, such ascollections.sort (list, new Pricecomparator ()); This requires implementation of the interface, write CompareTo method://Custom Comparator: Sort by book price static class Pricecomparator implements Comparator { public int Compare (object Object1, Object object2) {//method implemented in interface

Book P1 = (book) Object1; //Forced conversion

Book P2 = (book) Object2;

Return new Double (P1.price). CompareTo (new Double (P2.price));

}

}

The sort method of Java

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.