php小编西瓜带来的java问答专栏,本期探讨intellij java中映射流的通用类型推断。在开发过程中,合理利用通用类型推断能够提高代码编写效率,减少冗余代码。通过本文的讨论和示例,读者可以更好地理解和应用intellij java中的映射流,进一步提升编程技能。
问题内容
想象一下下面的类:
public class test {
private static list> getmodels() {
return list.of(10).stream()
.map(test::getmodel)
.tolist();
}
private static model> getmodel(int key) {
return new model<>(key);
}
public static void main(string... str) {
system.out.println("hello world!" + getmodels());
}
public static class model {
private t field;
model(t key) {
field = key;
}
public string tostring() {
return "model(" + field + ")";
}
}
}
我很好奇为什么 intellij 在映射阶段后无法推断流的类型,并显示错误?
当我如下所示在地图阶段显式添加类型时,它工作正常。
public class test {
private static list> getmodels() {
return list.of(10).stream()
.>map(test::getmodel)
.tolist();
}
private static model> getmodel(int key) {
return new model<>(key);
}
public static void main(string... str) {
system.out.println("hello world!" + getmodels());
}
public static class model {
private t field;
model(t key) {
field = key;
}
public string tostring() {
return "model(" + field + ")";
}
}
}
为什么intellij显示错误,但是编译却没有任何错误?当我将鼠标悬停在它上面时,会显示此错误:
立即学习“Java免费学习笔记(深入)”;
Required type: List> Provided: List extends Model>>
解决方法
intellij 编译器错误地推断了 map 方法的更通用的返回类型(stream extends model>>,而它应该是 stream)。 java 编译器仍然会接受代码,因为它是正确的,但如果 ide 警告很烦人,那么您可以通过简单地提供显式类型参数来抑制它:
return List.of(10).stream()
.>map(Test::getModel)
.toList();











