About the use of the comparable interface

Source: Internet
Author: User
Tags comparable

First, use the comparable interface for sorting: How to sort a data type or a custom class must be implemented comparable

Both the base data type and the string type of data defined by the JDK are implemented comparable. The following example shows the concrete implementation of comparable

1, the definition of comparable interface:

Public interface Comparable<t> {public       int compareTo (T o);}

The comparable interface defines only one method, CompareTo (T o), and returns data of type int.

The method returns 3 ranges of data:>0;=0;<0;

Here is an example

 Public classGradeImplementsComparable<grade> {     private int  grade;  PublicGrade (intgrade) {        Super();  This. grade =grade; }     Public intGetgrade () {returngrade; }     Public voidSetgrade (intgrade) {         This. grade =grade; } @Override Public   int  compareTo (Grade Grade) {  return this. Grade- Grade.getgrade (); } @Override PublicString toString () {return"Grade [grade=" + Grade + "]"; }}

Sort a string

public int CompareTo (String anotherstring) {        int len1 = value.length;        int len2 = anotherString.value.length;        int lim = Math.min (len1, len2);        Char v1[] = value;        Char v2[] = Anotherstring.value;        int k = 0;        while (K < Lim) {            char C1 = v1[k];            char C2 = v2[k];            if (c1! = C2) {                return c1-c2;            }            k++;        }        return len1-len2;    }

  

  

About the use of the comparable interface

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.