根据答案:https://stackoverflow.com/a/47693998/8760211
发生编译错误后,当我尝试从类Student
中对包含Invoker
类型元素的列表进行排序时。
Student
是类University
的内部类:
Type mismatch: cannot convert from ToIntFunction<University.Student> to ToIntFunction<? super T>
代码:
public class University implements Serializable {
private List<Student> values = new ArrayList<Student>();
public static final class Student implements Serializable {
private int id;
private String name;
private String location;
private Date date;
Student(int id, String name, String location, Date date) {
this.id = id;
this.name = name;
this.location = location;
this.date = date;
}
// Problem occurs even with getters!!
}
public class Invoker implements Serializable {
public static void main(String[] args) {
List<University.Student> students = new ArrayList<>();
Map<String, Integer> locationOrder = students.stream().collect(HashMap::new,
(m, s) -> m.putIfAbsent(s.getName(), m.size()),
(m1, m2) -> m2.keySet().forEach(l -> m1.putIfAbsent(l, m1.size())));
students.sort(Comparator.comparingInt((University.Student s) -> locationOrder.get(s.name)).thenComparing(s -> s.id));
}
}
以下代码段在IDE中标记为编译器错误的原因:
comparingInt((University.Student s) -> locationOrder.get(s.name)
如果我将内部类移动到类Invoker
中,一切正常!!
非常感谢任何帮助。 提前谢谢。
答案 0 :(得分:2)
这是一个奇怪的错误,但原因只是s.name
无法访问Invoker
:它是私有的。 s.id
也不是。Student
。因此,您应该将getter方法添加到public String getName() {
return name;
}
,如
Invoker
并改为使用它们。封闭类可以访问内部类的私有成员,这就是为什么它移动到self.navigationItem.searchController.delegate = self;
...
- (void)willPresentSearchController:(UISearchController *)searchController {
self.navigationController.navigationBar.prefersLargeTitles = NO;
}
- (void)willDismissSearchController:(UISearchController *)searchController {
self.navigationController.navigationBar.prefersLargeTitles = YES;
}
时可以工作。
答案 1 :(得分:1)
尝试将其更改为此
students.sort(Comparator.<University.Student>comparingInt(s -> locationOrder.get(s.name)).thenComparing(s -> s.id));