The difference between CompareTo and compare in Java

Source: Internet
Author: User
Tags comparable

Compare

As can be seen from here, compare is a class in the comparator interface, and then look at the explanation in the source code

Compares its-arguments for order. Returns a negative integer,
Zero, or a positive integer as the first argument is less than, equal
To, or greater than the second

If the first argument is less than the second parameter, a negative number is returned, or 0 if it is equal, and a positive number is returned if it is greater.

Look at the CompareTo method again

First, he is a method in the comparable interface,

The string class then inherits the comparable interface and implements the Comparteto method

To see the implementation of the specific method:

 Public intcompareTo (String anotherstring) {intLen1 =value.length; intLen2 =anotherString.value.length; intLim =math.min (Len1, len2); CharV1[] =value; CharV2[] =Anotherstring.value; intK = 0;  while(K <Lim) {CharC1 =V1[k]; CharC2 =V2[k]; if(C1! =C2) {                returnC1-C2; } k++; }        returnLEN1-Len2; }

So, compare is a comparator method, and CompareTo is the concrete way to implement this interface.

The difference between CompareTo and compare in Java

Related Article

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.