public class Student implements Comparable{ private String useName; private int age; public String getUseName() { return useName; } public void setUseName(String useName) { this.useName = useName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "useName='" + useName + ''' + ", age=" + age + '}'; } @Override public int compareTo(Student o) { return this.getAge()-o.getAge(); } }
测试
public static void main(String[] args) {
//创建两个Student对象并调用getMax方法
Student s1 = new Student();
s1.setUseName("张三");
s1.setAge(18);
Student s2 = new Student();
s2.setUseName("李四");
s2.setAge(20);
Comparable max = getMax(s1, s2);
System.out.println(max);
}
getMax方法
public static Comparable getMax(Comparable c1, Comparable c2) {
int result = c1.compareTo(c2);
//如果result<0,则c10,则c1>c2
//如果result=0,则c1=c2
if (result >= 0) {
return c1;
} else {
return c2;
}
}



