一定要StudentTest引用Comparator接口吗?
来源:3-5 编程练习
福生玄黄天尊
2020-12-02 15:05:43
# 具体遇到的问题
如下,我在StudentTest下建立一个NameComparator类引用Comparator接口,为什么就不行呢?
# 报错信息的截图
StudentTest.java:32: error: cannot find symbol
Collections.sort(stuList, new NameComparator());
^
symbol: class NameComparator
location: class StudentTest
1 error
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
//实现Comparator接口
public class StudentTest{
//实现接口中的方法
public class NameComparaor implements Comparator<Student> {
@Override
public int compare(Student stu1, Student stu2){
String name1 = stu1.getName();
String name2 = stu2.getName();
return name1.compareTo(name2);
}
}
public static void main(String[] args){
//定义Student类的对象
Student peter = new Student(40,20,"peter");
Student angel = new Student(28,5,"angel");
Student tom = new Student(35,18,"tom");
//将对象添加到List中
List<Student> stuList = new ArrayList<Student>();
stuList.add(peter);
stuList.add(angel);
stuList.add(tom);
//输出排序前的数据
System.out.println("按名字排序前:");
for(Student stu:stuList){
System.out.println(stu.toString());
}
//排序
Collections.sort(stuList, new NameComparator());
//输出排序后的数据
System.out.println("按名字排序后:");
for(Student stu:stuList){
System.out.println(stu.toString());
}
}
}
1回答
同学你好,同学的写法也实现了Comparator接口,并重写了compare()方法,只不过同学的写法是在Student类中重新定义了一个类,属于内部类;在sort()方法中传入的是内部类,访问内部类应该通过访问外部类再访问内部类
如下
Collections.sort(stuList, new StudentTest().new NameComparaor());
祝学习愉快
相似问题