为什么在测试类排序会报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | public class Student { //成员变量 private int id; private int age; private String name; //构造方法 public Student(){} public Student( int id, int age,String name){ this .setId(id); this .setAge(age); this .setName(name); } //getter和setter方法 public void setId( int id){ this .id=id; } public int getId(){ return this .id; } public void setAge( int age){ this .age=age; } public int getAge(){ return this .age; } public void setName(String name){ this .name=name; } public String getName(){ return this .name; } //toString()方法 public String toString(){ return "[学号:" + this .getId()+ "年龄:" + this .getAge()+ "姓名:" + this .getName()+ "]" ; } } public class StudentTest implements Comparator<Student>{ //实现接口中的方法 public int compare(Student o1, Student o2) { String s1=o1.getName(); String s2=o2.getName(); int n=s1.compareTo(s2); return n; } public static void main(String[] args){ //定义Student类的对象 Student stu1= new Student( 12 , 23 , "peter" ); Student stu2= new Student( 16 , 18 , "angel" ); Student stu3= new Student( 61 , 20 , "tom" ); //将对象添加到List中 List<Student> list= new ArrayList<Student>(); list.add(stu1); list.add(stu2); list.add(stu3); System.out.println( "排序前:" ); //输出排序前的数据 for (Student stu:list){ System.out.println(stu); } //输出排序后的数据 Collections.sort(list, new StudentTest()); System.out.println( "排序后:" ); for (Student stu:list){ System.out.println(stu); } } } |
37
收起
正在回答 回答被采纳积分+1
3回答
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧