[英]Covariance in Java
Why does the following not work in Java? 为什么以下内容在Java中不起作用? It would work in C#:
它将在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. 我收到一条错误消息,指出此方法必须返回List。 CopyOnWriteArrayList implements the List interface.
CopyOnWriteArrayList实现List接口。 Why does covariance not apply on return values in Java?
为什么协方差不适用于Java中的返回值?
看来您已经忘记为else
分支返回List<String>
了。
You either have a else branch explicitly and return whatever you want to return (null maybe ?). 您要么明确拥有一个else分支,然后返回您想要返回的任何内容(也许为null?)。 Or have a return statement at the end of the method.
或者在方法末尾有一个return语句。 You program will not compile if you do not have either.
如果没有,则程序将不会编译。
Apart from the correct answers above: 除了上述正确答案外:
Actually, I'd use apache commons lang and do it like this: 实际上,我会使用apache commons lang并按以下方式进行操作:
return Arrays.asList(
StringUtils.stripToEmpty(myString) // converts null into ""
// and strips extra whitespace
.split(
Pattern.quote(Character.toString(delimiter))
)
)
No if / else needed. 否(如果需要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.