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;
        }
    }
}

运行结果

image-20210811161236197

Q.E.D.


樱花庄的一只二刺猿