正在回答
4回答
3-5的意思是说,在你的主方法StudentTest.java中implements Comparator,然后实现compare()方法。这个Comparator是系统的不是自己定义的。祝:学习愉快
慕虎8754231
2018-03-19 17:33:18
//实现Comparator接口 public class StudentTest{ //实现接口中的方法 public class NameComparator implements Comparator<Student> public int compare(Student o1,Student o2) { // 按名字进行升序排列 String name1=o1.getStudentNam(); String name2=o2.getStudentNam(); int n=name1.compareTo(name2); return n; } } public static void main(String[] args){ //定义Student类的对象 Student peter = new Student(40,20,"peter"); Student angle = new Student(28,5,"angle"); Student tom = new Student(35,18,"tom"); //将对象添加到List中 List<Student> studentList = new ArrayList<Student>(); studentList.add(peter); studentList.add(angle); studentList.add(tom); //输出排序前的数据 System.out.println("按名字排序前:"); for (Student student: studentList) { System.out.println(student + " "); } //排序 Collections.sort(studentList, new StudentComparator()); //输出排序后的数据 System.out.println("按名字排序后:"); for (Student student: studentList) { System.out.println(student + " "); } } }
我开始这样写的,还是通不过,老师看怎样处理呢?0.0
好帮手慕雪
2018-03-19 17:31:46
public class StudentTest implements Comparator<Student>{ public static void main(String[] args){ ....... } @Override public int compare(Student o1,Student o2) { // 按名字进行升序排列 String name1=o1.getStudentNam(); String name2=o2.getStudentNam(); return name1.compareTo(name2); } }
类似于这样的格式。
慕虎8754231
2018-03-19 16:54:13
//实现Comparator接口 public class StudentTest{ //实现接口中的方法 public class StudentComparator implements Comparator<Student> { public static void main(String[] args){ //定义Student类的对象 Student peter = new Student(40,20,"peter"); Student angle = new Student(28,5,"angle"); Student tom = new Student(35,18,"tom"); //将对象添加到List中 List<Student> studentList = new ArrayList<Student>(); studentList.add(peter); studentList.add(anglr); studentList.add(tom); //输出排序前的数据 System.out.println("按名字排序前:"); for (Student student: studentList) { System.out.println(student + " "); } //排序 Collections.sort(studentList, new StudentComparator()); //输出排序后的数据 System.out.println("按名字排序后:"); for (Student student: studentList) { System.out.println(student + " "); } @Override public int compare(Student o1,Student o2) { // 按名字进行升序排列 String name1=o1.getStudentNam(); String name2=o2.getStudentNam(); int n=name1.compareTo(name2); return n; } } } }
麻烦看看呢?
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星