Comparable接口的使用
本文最后更新于:2021年9月2日 晚上
Comparable接口的使用:(知识回顾)
1、定义一个学生类,具有年龄age和姓名username两个属性,并通过Comparable接口提供比较规则。
package demo02.sort;
public class Student implements Comparable<Student>{
private String username;
private int age;
public String getUsername() {
return username;
}
public int getAge() {
return age;
}
public void setUsername(String username) {
this.username = username;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
return this.getAge()-o.getAge();
}
}
2、定义测试类TestComparable,在测试类Test中定义测试方法Comparable getMax(comparable c1,comparable c2)完成测试
package demo02.test;
import demo02.sort.Student;
public class TestComparable {
public static void main(String[] args) {
Student s1 = new Student();
s1.setUsername("张三");
s1.setAge(18);
Student s2 = new Student();
s2.setUsername("李四");
s2.setAge(20);
Comparable max = getMax(s1, s2);
System.out.println(max);
}
public static Comparable getMax(Comparable c1, Comparable c2) {
int result = c1.compareTo(c2);
//如果result>0,则c1比c2大,如果result<0,则c2比c1大如果result=0,则c1==c2大
if (result >= 0) {
return c1;
} else {
return c2;
}
}
}
运行结果:
本文作者: CodeAnime
本文链接: https://codeanime.cc/Comparable%E6%8E%A5%E5%8F%A3%E7%9A%84%E4%BD%BF%E7%94%A8.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!