java排序方法总结:
一、数字类型数组排序:
int[] nums={3,2,3,5,9,39,90,40};
Arrays.sort(nums); //数字型数组排序,直接用Arrays.sort()方法
for (int i : nums) {
System.out.print(i+",");
}
二、String类型数组排序:
String[] strs={"ab","bc","kn","cd","jk"};
Arrays.sort(strs); //字符串类型数组排序,也可以用Arrays.sort()方法
for (String string : strs) {
System.out.print(string+",");
}
三、对象数组排序:
方法一:实体对象类,必须实现Comparable接口并实现compareTo方法, 此接口在java.lang包下
public class SortArrays implements Comparable {
private int num;
private String str;
public SortArrays(int num,String str){
this.num=num;
this.str=str;
}
//必须实现compareTo方法
public int compareTo(SortArrays o) {
if(num//这里用什么排序就用什么比较
return 1;//返回正数就行
}else if(num>o.num){
return -1; //返回负数就行
}else{
return 0;//相等为0
}
}
省去set/get方法
}
//main方法主要代码:
SortArrays[] sorts=new SortArrays[5];
sorts[0]=new SortArrays(3,"ab");
sorts[1]=new SortArrays(50,"kn");
sorts[2]=new SortArrays(30,"cd");
sorts[3]=new SortArrays(40,"jk");
sorts[4]=new SortArrays(35,"kn");
Arrays.sort(sorts); //Object对象排序,必须实现Comparable接口,实现compareTo方法
for (SortArrays sortArrays : sorts) {
System.out.println(sortArrays.getNum()+"/"+sortArrays.getStr());
}
方法二:实体类不实现Comparable接口,单独写一排序类,实现Comparator接口,并实现compare方法,此接口在java.util包下。
public class TestSort1Comparator implements Comparator {
public int compare(SortArrays1 o1, SortArrays1 o2) {
if(o1.getNum()>o2.getNum()){
return -1;
}else if(o1.getNum()
return 1;
}else{
return 0;
}
}
}
//实体类
public class SortArrays1 {
private int num;
private String str;
public SortArrays1(int num,String str){
this.num=num;
this.str=str;
}
}
//测试类
public class TestSort1 {
public static void main(String[] args) {
TestSort1Comparator comparator=new TestSort1Comparator();
TreeSet set1=new TreeSet(comparator);
set1.add(new SortArrays1(3,"ab"));
set1.add(new SortArrays1(50,"kn"));
set1.add(new SortArrays1(30,"cd"));
set1.add(new SortArrays1(40,"jk"));
set1.add(new SortArrays1(35,"kn"));
for (SortArrays1 sortArrays1 : set1) {
System.out.println(sortArrays1.getNum()+"/"+sortArrays1.getStr());
}
}
}