为什么Java编译器不能解决这个问题呢?
发布时间:2020-12-15 05:15:11 所属栏目:Java 来源:网络整理
导读:为什么编译器无法在以下示例中从Collections.emptySet()推断出结果的正确类型? import java.util.*;import java.io.*;public class Test { public interface OptionA { public B B option(B b,FA,B f); } public interface FA,B { public B f(A a); } publi
为什么编译器无法在以下示例中从Collections.emptySet()推断出结果的正确类型?
import java.util.*; import java.io.*; public class Test { public interface Option<A> { public <B> B option(B b,F<A,B> f); } public interface F<A,B> { public B f(A a); } public Collection<String> getColl() { Option<Integer> iopt = null; return iopt.option(Collections.emptySet(),new F<Integer,Collection<String>>() { public Collection<String> f(Integer i) { return Collections.singleton(i.toString()); } }); } } 这是编译器错误消息: knuttycombe@knuttycombe-ubuntu:~/tmp/java$javac Test.java Test.java:16: <B>option(B,Test.F<java.lang.Integer,B>) in Test.Option<java.lang.Integer> cannot be applied to (java.util.Set<java.lang.Object>,<anonymous Test.F<java.lang.Integer,java.util.Collection<java.lang.String>>>) return iopt.option(Collections.emptySet(),Collection<String>>() { ^ 1 error 现在,getColl()的以下实现当然有效: public Collection<String> getColl() { Option<Integer> iopt = null; Collection<String> empty = Collections.emptySet(); return iopt.option(empty,Collection<String>>() { public Collection<String> f(Integer i) { return Collections.singleton(i.toString()); } }); } 并且关于集合的类型安全方法的整个意图是避免使用单例集合的这种问题(而不是使用静态变量.)因此,编译器是否无法跨多个泛型级别执行推理?这是怎么回事? 解决方法
Java需要通过推理进行大量的手工操作.类型系统可以在很多情况下更好地推断,但在您的情况下,以下将起作用:
print("Collections.<String>emptySet();"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |