展开全部
用来实现Comaprable接口,比如现在有个学生类,想通过其中score字段来让两个学生类的实例实现排序 ,可以这62616964757a686964616fe4b893e5b19e31333335343435么写import java.util.Arrays;
public class Zhidao{
public static void main(String[] args) {
Student[] stu = {new Student("Tom", 90), new Student("Jerry", 95), new Student("Kate", 70), new Student("Jack", 98)};
System.out.println("Before:");
for(Student s : stu) {
System.out.println(s.getName() + " : " + s.getScore());
}
Arrays.sort(stu);
System.out.println("After:");
for(Student s : stu) {
System.out.println(s.getName() + " : " + s.getScore());
}
}
}
class Student implements Comparable {
private String name;
private int score;
public Student(String name, int score) {
this.setName(name);
this.setScore(score);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student stu) {
return score - stu.getScore();
}
}