加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Comparator接口 2.14 KB
一键复制 编辑 原始数据 按行查看 历史
鸢也12123 提交于 2021-12-28 01:52 . add Comparator接口.
import javax.naming.Name;
import java.util.Arrays;
import java.util.Comparator;
class Student1 {
private String name;
private int age;
private double score;
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Student1(String name, int age, double score) {
this.name=name;
this.age=age;
this.score=score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
class AgeComparator implements Comparator<Student1> {
@Override
public int compare(Student1 o1, Student1 o2) {
return o1.getAge()-o2.getAge();
}
}
class NameComparator implements Comparator<Student1> {
@Override
public int compare(Student1 o1, Student1 o2) {
return o2.getName().compareTo(o1.getName());
}
}
class ScoreComparator implements Comparator<Student1> {
@Override
public int compare(Student1 o1, Student1 o2) {
return (int)( o1.getScore()-o2.getScore());
}
}
public class TestComparator {
public static void main(String[] args) {
Student1[] students=new Student1[3];
students[0]=new Student1("鸢也",20,99.9);
students[1]=new Student1("张三",18,89.8);
students[2]=new Student1("李四",25,78.8);
System.out.println("排序前:" + Arrays.toString(students));
AgeComparator ageComparator=new AgeComparator();
NameComparator nameComparator=new NameComparator();
ScoreComparator scoreComparator=new ScoreComparator();
Arrays.sort(students,scoreComparator);
System.out.println("排序后: " +Arrays.toString(students));
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化