前言
很多Java算法中都需要用到排序秒梅,但是往往在項目開發(fā)中并不需要自己實現(xiàn)排序功能怕敬,所以必須要熟練使用排序的庫函數(shù)才能快速的開發(fā)出高質(zhì)量的代碼置森。這篇博客就記錄以下常用的數(shù)組排序以及List排序,還有用處非常大的自定義對象數(shù)組排序
常見數(shù)據(jù)類型數(shù)組排序(正向)
Arrays.sort()
int []x = {3,8,3,2,4,1,4,1,2,2,6,5,5,3,5,1,0,2,4,2,0,4,8,4,2,1,9,4,3,9,6};
Arrays.sort(x);
for(int i =0;i<x.length;i++){
System.out.print(x[i]);
}
##輸出結(jié)果
0011112222223333444444555668899
一般對象數(shù)組(String槽卫、Integer拿诸、Character)正向與逆向排序
Arrays.sort(Object[] obj)
升序
Arrays.sort(Object[] obj , Comparator.reverseOrder())
降序
Java里面并沒有給int等自定義數(shù)據(jù)類型進行降序排列的函數(shù)
String []strings = {"1","x","3","g","5","6","7"};
Arrays.sort(strings,Comparator.reverseOrder());
for(int i = 0;i<strings.length;i++){
System.out.print(strings[i]);
}
###輸出
xg76531
自定義對象數(shù)組排序
方法一:實現(xiàn)Comparable接口的compareTo(Object o)
扒袖,然后調(diào)用函數(shù)自動按照規(guī)則排序。
class Name implements Comparable<Name>{
public String firstName;
public String lastName;
public Name(String first,String last){
this.firstName = first;
this.lastName = last;
}
@Override
public int compareTo(Name o) {
int lastCmp = firstName.compareTo(o.firstName);
return(!(lastCmp==0)?lastCmp:lastName.compareTo(o.lastName));
}
public String toString(){
return firstName + " " + lastName;
}
}
############## 測試
Name names[] ={new Name("John","Muhaha"),new Name("Gao","Dev"),new Name("Susan","JInjiao")};
Arrays.sort(names);
for(int i = 0 ;i<names.length;i++){
System.out.println(names[i].toString());
}
################ 輸出
Gao Dev
John Muhaha
Susan JInjiao
方法二:自定義比較參數(shù)亩码,在排序時傳入新創(chuàng)建的比較參數(shù)實現(xiàn)比較效果(實現(xiàn)compare(Object o1,Object o2))
)
******自定義類********
class Name2{
public String firstName;
public String lastName;
public Name2(String first,String last){
this.firstName = first;
this.lastName = last;
}
public String toString(){
return firstName + " " + lastName;
}
}
*******創(chuàng)建排序參數(shù)********
Comparator<Name2> comparator = new Comparator<Name2>() {
@Override
public int compare(Name2 o1, Name2 o2) {
int bigger = o1.firstName.compareTo(o2.firstName);
return (!(bigger==0)?bigger:o1.lastName.compareTo(o2.lastName));
}
};
******測試************
Arrays.sort(names2,comparator);
for(int i = 0 ;i<names2.length;i++){
System.out.println(names2[i].toString());
}
******輸出************
Wang Dev
Xing JInjiao
Yao Muhaha