具有通用返回类的 Java 方法签名

发布于 2024-10-05 12:46:03 字数 166 浏览 7 评论 0原文

以下2个方法签名有什么区别:

public <T extends MyClass> Set<T> getMyList() {...}

public Set<? extends MyClass> getMyList() {...}

What is the difference between the following 2 method signature:

public <T extends MyClass> Set<T> getMyList() {...}

public Set<? extends MyClass> getMyList() {...}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

请帮我爱他 2024-10-12 12:46:03

在第一个方法中,T 可以在方法体中访问,而在第二个方法中则不能。这是否有用取决于该方法的工作。

In the first one, T is accessible in method body, while in the second one it is not. Whether that's useful depends on the method's job.

§普罗旺斯的薰衣草 2024-10-12 12:46:03

对于第一个,您可以将其用作:

Set<MyClass> set = thing.getMyList();
Set<MyDerivedClass> set = thing.getMyList();
Set<?> set = thing.getMyList();
Set<? extends MyClass> set = thing.getMyList();
Set<? extends MyDerivedClass> set = thing.getMyList();

对于第二个,您受到更多限制:

Set<?> set = thing.getMyList();
Set<? extends MyClass> set = thing.getMyList();

您希望如何实现第一个?第二个不好,因为它强制客户端代码使用通配符。

For first one you can use it as:

Set<MyClass> set = thing.getMyList();
Set<MyDerivedClass> set = thing.getMyList();
Set<?> set = thing.getMyList();
Set<? extends MyClass> set = thing.getMyList();
Set<? extends MyDerivedClass> set = thing.getMyList();

For the second, you are more limited:

Set<?> set = thing.getMyList();
Set<? extends MyClass> set = thing.getMyList();

How would you expect to implement the first? The second is bad because it forces client code to use wildcards.

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