Guava Source Analysis--ordering

Source: Internet
Author: User

Needless to doubt, ordering definitely implements the Comparator<t> interface, which is used in comparison sorting in Java. Whereas the static method returns a type of ordering, the different ordering subclasses implement their own compare () method, as follows:

 Public Static extends Comparable> ordering<c> Natural () {  return (ordering<c>) naturalordering.instance;}

The implementation class has the following:

If the ordering subclass is constructed without arguments, it is only constructed as a singleton using the final static instance method, which is thread safe because there are no shared member variables.

Decoration mode in which the perfection is used. As an example, verify that:

list<integer> numbers = lists.newarraylist (null, 1, 3, 2, 5, 4, 6); List<Integer> sorted = ordering.natural (). Nullsfirst (). sortedcopy (numbers);  for (integer integer:sorted) {System.out.println (integer);}

Ordering.natural () returns the Naturalordering.instance object and then calls Nullfirst (), returning the new nullsfirstordering<s> (this); This is the Naturalordering.instance object at this point, and the Nullsfirstordering constructor method aggregates the ordering parent class, and when the Compare () method is overridden, the null sort logic is added after the decoration.

 @Override 
public int compare (@Nullable t left, @Nullable T-right) { if (left == right) { return 0; if (left = = null return Right_is_greater; if (right = = null return Left_is_greater; return Ordering.compare (left, right);}

Finally ordering the parent class encapsulated in the way Sortedcopy (), in the call Arrays.sort (array, this) method, to decorate the ordering as the comparator incoming sort () method, Thus the perfect realization of the chain form of writing and calling rules.

The implementation of other sorting methods is not explained. Ordering the main analysis is the use of adorners

Guava Source Analysis--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.