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