gpt4 book ai didi

Java 泛型 : Error when using innerclass

转载 作者:行者123 更新时间:2023-11-29 04:23:26 25 4
gpt4 key购买 nike

基于答案:https://stackoverflow.com/a/47693998/8760211

当我尝试从类 Invoker 中对类型为 Student 的元素的列表进行排序时,发生以下编译错误。StudentUniversity 类的内部类:

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 类中,一切正常!!

任何帮助将不胜感激。提前致谢。

最佳答案

这是一个奇怪的错误,但原因只是 s.nameInvoker 中不可访问:它是私有(private)的。 s.id 也不是。所以你应该向 Student 添加 getter 方法,比如

public String getName() {
return name;
}

并改用它们。封闭类可以访问内部类的私有(private)成员,这就是为什么如果移动到 Invoker 就可以正常工作。

关于Java 泛型 : Error when using innerclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47719325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com