简体   繁体   English

Java中的协方差

[英]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: 除了上述正确答案外:

  1. use lower case method names in Java (split instead of Split) 在Java中使用小写的方法名称(拆分而不是拆分)
  2. why return such a heavy object as CopyOnWriteArrayList when your string is empty? 当您的字符串为空时,为什么返回诸如CopyOnWriteArrayList这样的重对象? That's the kind of situation where you want to return Collections.emptyList(), where no new object is created unnecessarily (assuming you are not going to add values to the list afterwards) 在这种情况下,您想返回Collections.emptyList(),在该情况下不需要创建新对象(假设您以后不会再向列表中添加值)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM