Java 中的协方差

发布于 2024-09-06 00:05:27 字数 366 浏览 3 评论 0原文

为什么下面的代码在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨巷深深 2024-09-13 00:05:27

您似乎忘记了为 else 分支返回 List

It looks like you've forgotten to return a List<String> for the else branch.

俏︾媚 2024-09-13 00:05:27

您要么显式地有一个 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.

九歌凝 2024-09-13 00:05:27

除了上面的正确答案之外:

  1. 在Java中使用小写方法名称(split而不是Split)
  2. 为什么当字符串为空时返回像CopyOnWriteArrayList这样的重对象?这就是您想要返回 Collections.emptyList() 的情况,其中不会创建不必要的新对象(假设您之后不会向列表添加值)

实际上,我会使用 apache commons lang 并这样做this:

return Arrays.asList(
    StringUtils.stripToEmpty(myString) // converts null into ""
                                 // and strips extra whitespace
        .split(
             Pattern.quote(Character.toString(delimiter))
        )
)

否 if / else 需要。

Apart from the correct answers above:

  1. use lower case method names in Java (split instead of Split)
  2. why return such a heavy object as CopyOnWriteArrayList when your string is empty? 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)

Actually, I'd use apache commons lang and do it like this:

return Arrays.asList(
    StringUtils.stripToEmpty(myString) // converts null into ""
                                 // and strips extra whitespace
        .split(
             Pattern.quote(Character.toString(delimiter))
        )
)

No if / else needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文