老师帮忙看看错在哪?谢谢!
测试类:
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 | //实现Comparator接口 public class StudentTest implements Comparator{ //实现接口中的方法 @Override public int compare(Student o1, Student o2) { String name1=o1.getName(); String name2=o2.getName(); int n=name1.compareTo(name2); return n; } public static void main(String[] args){ //定义Student类的对象 Student stu1= new Student( 40 , 20 , "perter" ); Student stu2= new Student( 28 , 5 , "angle" ); Student stu3= new Student( 35 , 18 , "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); } } |
学生类:
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 | public class Student { //成员变量 private int number; private int age; private String name; //构造方法 public Student(){ } public Student( int number, int age,String name){ this .number=number; this .age=age; this .name=name; } //getter和setter方法 public int getNumber(){ return number; } public void setNumber(){ this .number=number; } public int getAge(){ return age; } public void setAge(){ this .age=age; } public String getName(){ return name; } public void setName(){ this .name=name; } //toString()方法 public String toString(){ return "[学号:" +number+ ", 年龄:" +age+ ", 姓名:" +name+ "]" ; } } |
1
收起
正在回答
4回答
同学很棒哦,自己解决了问题~也是编程工作中很重要的能力呢~
继续加油吧~祝:学习愉快~
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧