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. 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.
精彩评论