Java 中的协方差
为什么下面的代码在 Java 中不起作用?它可以在 C# 中工作:
public static final List<String> Split(String str, char delimiter)
{
if ((str == null) || "".equals(str))
{
return new CopyOnWriteArrayList<String>();
}
}
我收到一条错误消息,指出此方法必须返回 List。 CopyOnWriteArrayList 实现 List 接口。为什么协方差不适用于 Java 中的返回值?
Why does the following not work in Java? It would work in C#:
public static final List<String> Split(String str, char delimiter)
{
if ((str == null) || "".equals(str))
{
return new CopyOnWriteArrayList<String>();
}
}
I get an error saying this method has to return List. CopyOnWriteArrayList implements the List interface. Why does covariance not apply on return values in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您似乎忘记了为
else
分支返回List
。It looks like you've forgotten to return a
List<String>
for theelse
branch.您要么显式地有一个 else 分支并返回您想要返回的任何内容(也许为 null ?)。或者在方法的末尾有一个 return 语句。如果两者都没有,您的程序将无法编译。
You either have a else branch explicitly and return whatever you want to return (null maybe ?). Or have a return statement at the end of the method. You program will not compile if you do not have either.
除了上面的正确答案之外:
实际上,我会使用 apache commons lang 并这样做this:
否 if / else 需要。
Apart from the correct answers above:
Actually, I'd use apache commons lang and do it like this:
No if / else needed.