Array.Sort()方法是根据元素的自然顺序对指定的对象数组按升序进行排序,但是如果如果数组中的对象不是能直接进行比较的话,那么会报错,例如学生的成绩进行排序,对象是学生,具有成绩,学号,姓名的属性。如果想对学生的成绩进行排序,有两种方法:
1.实现Comparable接口,并覆盖compareTo方法,按照你的意思进行排序
2.实现Comparator接口,并覆盖compare方法,按照你的意思进行排序
下面是我的两种实现方法,对于其中的更深的内容还没有了解,网大虾指教。
package com.practice.ch10;
import java.util.Arrays;
public class Result implements Comparable{
int point; //成绩
int no; //学号
String name; //姓名
public Result(int point,int no,String name)
{
this.point = point;
this.no = no;
this.name = name;
}
public int compareTo(Object o) {
int point_cp = ((Result)o).point;
int no_cp = ((Result)o).no;
//1.只按成绩排return (point < point_cp ? -1 : (point == point_cp ? 0 :1 ));
// //2.先按成绩排,再按姓名排
// String name_cp=((Result)o).name;
// if(point
// }else if (point>point_cp){
// return 1;
// }else{
// return name.compareTo(name_cp);
// }
//3.先按成绩排,再按学号排
if(point
}else if (point>point_cp){
return 1;
}else{
return no - no_cp;
}
}
public static void main(String[] args) {
Result[] ra = {new Result(90,2,"zhang"),new Result(83,1,"wang"),new Result(86,3,"lt"),new Result(86,5,"li"),new Result(86,4,"ls")};
System.out.println("原始数据");
for(int i=0;i
System.out.println(ra[i].no + "," + ra[i].name + "," +ra[i].point);
}
System.out.println("**************************************");
System.out.println("按成绩和学号排序后");
Arrays.sort(ra);
for(int i=0;i
System.out.println(ra[i].no + "," + ra[i].name + "," +ra[i].point);
}
System.out.println("**************************************");
System.out.println("按成绩和姓名排序后");
Arrays.sort(ra,new ComResultComparator());
for(int i=0;i
System.out.println(ra[i].no + "," + ra[i].name + "," +ra[i].point);
}
}
}
package com.practice.ch10;
import java.util.Arrays;
import java.util.Comparator;
class ComResultComparator implements Comparator {
public int compare(Object o1, Object o2) {
int point1 = ((Result) o1).point;
String name1 = ((Result) o1).name;
int point2 = ((Result) o2).point;
String name2 = ((Result) o2).name;
//return (no1 < no2 ? -1 : (no1 == no2 ? 0 : 1));
if(point1 < point2){
return -1;
}else if(point1 > point2){
return 1;
}else {
return name1.compareTo(name2);
}
}
}