[英]Java Method signature with generic return class
What is the difference between the following 2 method signature: 以下两个方法签名之间有什么区别:
public <T extends MyClass> Set<T> getMyList() {...}
public Set<? extends MyClass> getMyList() {...}
In the first one, T
is accessible in method body, while in the second one it is not. 在第一个中,方法主体中的
T
是可访问的,而在第二个中,方法主体中的T
是不可访问的。 Whether that's useful depends on the method's job. 是否有用取决于方法的工作。
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.
第二个不好,因为它强制客户端代码使用通配符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.