Student实体类代码如下所示: package com.test.Test08; public class Student implements Comparable<Student>{ private int age; private double height; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student(int age, double height, String name) { this.age = age; this.height = height; this.name = name; } @Override public String toString() { return "Student{" + "age=" + age + ", height=" + height + ", name='" + name + '\'' + '}'; } @Override public int compareTo(Student o) { // return 0; //按照年龄进行比较 //return this.getAge()-o.getAge(); //按照身高进行比较 /*return ((Double)(this.getHeight())).compareTo((Double)(o.getHeight()));*/ //按照名字比较 return this.getName().compareTo(o.getName()); } }
测试类如下所示:
package com.test.Test08; public class Test02 { public static void main(String[] args) { //比较两个学生 Student s1 = new Student(14, 160.2, "lili2"); Student s2 = new Student(14, 170.5, "lili"); //System.out.println(s1.compareTo(s2)); //0 -4 年龄进行比较 //System.out.println(s1.compareTo(s2)); //-1 身高进行比较 System.out.println(s1.compareTo(s2)); //0 1 名字进行比较 } }