In actual development, we often need to sort some data, which is often saved using arrays or collections. For sorting data in an array, the API provides an array of tool classes, java.util.Arrays, in which a large number of sort methods are overloaded to sort the array of various types. For example, you can sort an array of type object with the following methods:
public static void sort (object[] a)
Suppose there are class course, as follows:
Package com.csst.relation;
public class Course {
private String title;
private double price;
Public Course (String title, double price) {
super ();
this.title = title;
This.price = Price;
}
Public Course (String title) {
super ();
this.title = title;
}
Public Course () {
super ();
}
Public String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
}
Public double GetPrice () {return price
;
}
public void Setprice (double price) {
This.price = Price;
}
}
If you have an array of course types, you need to sort, according to the arrays class method, as long as you pass the array as an argument to the sort method. But as long as we think about it, we will find the problem. For course objects, the so-called order should have a sorting standard, for example, by Price row, or name row? The sorting criteria are determined to sort multiple course objects.
By carefully reading the detailed description of the Arrays.sort method, you will find that there is a requirement that objects sorted using this method must be of type comparable. Comparable is an interface that, as long as the course class implements this interface, overrides the method:
public int compareTo (Object o)
Assuming that we want the course array to be sorted by price, the course class implements the comparable interface, overwriting the CompareTo method:
public int CompareTo (Object arg0) {
//TODO auto-generated method stub
Course c= (Course) arg0;
if (this.price>c.price) {return
1;
} else if (this.price>c.price) {
return-1
} else{return
0;
}