平常,作為靜态類Arrays中的靜态方法sort()經常被我們使用。但是你知道怎麼控制它排序按照正序還是逆序呢?
其實,可以通過使用Comparable接口//Comparator接口,實作compareTo() / /compare()方法來調整正序還是逆序。
代碼如下:
首先建立一個StudentCoparable類使用Comparable接口,并實作方法compareTo();
public class StudentComparable implements Comparable<StudentComparable>{
private String number;
private String name;
private int age;
public int compareTo(StudentComparable student) {
return Integer.parseInt(this.number)-Integer.parseInt(student.number);
}
<span style="white-space:pre"> </span>……
}
然後我們開始測試資料,
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
StudentComparable sc = new StudentComparable("10000", "lz", 18);
StudentComparable sc1 = new StudentComparable("10001", "wx", 18);
StudentComparable sc2 = new StudentComparable("10003", "zh", 18);
StudentComparable sc3 = new StudentComparable("10002", "gd", 18);
StudentComparable scs[] = new StudentComparable[]{sc,sc1,sc2,sc3};
Arrays.sort(scs);//正序排序
for (int i = 0; i < scs.length; i++) {
System.out.println(scs[i].getNumber()+","+scs[i].getName()+","+scs[i].getAge());
}
}
}
此時,測試結果為:
可見是正序排序。
那如果想要逆序排序呢?其實很簡單,隻需要把compareTo中的
return Integer.parseInt(this.number)-Integer.parseInt(student.number);
//換個位置
<pre name="code" class="java">return Integer.parseInt(<span style="font-family: Arial, Helvetica, sans-serif;">student.number</span><span style="font-family: Arial, Helvetica, sans-serif;">)-Integer.parseInt(this.number);</span>
即可變為逆序排序。
其中,Comparator接口也是相同,隻需修改compare中的傳回值,就可以調整正逆序輸出了!!
結論:Arrays中的sort()方法,是跟Comparable接口,Comparator接口有密切相關,如果将來想使用這兩個接口和Arrays.sort()方法,值得注意一下。