We use wildcard in the method args when we want to pass list containing objects of child class. But as shown below we can achieve the same functionality using Type parameter. So why we need wildcards ?
Scenario
Lets say we have base-class named Department and its sub-classes named Development & Sales.
Development & Sales are subtypes of Department but List & List are not subtypes of List.
So when we want to pass list of Development or Sales object as method arg which is accepting list of any type of Department we use wildcard. But inside the code we can see we can achieve the same without using wildcard.
As per Effective Java using wildcard in return type is really a bad choice. What are the other usecases where wildcard is really helpful?
class MyGenericsClass<T extends SuperClass> {
//These 2 methods works the same
<H> void unboundedMethod1(AnotherGenericClass<H> arg) {
}
void unboundedMethod2(AnotherGenericClass<?> arg) {
}
//These two methods works the same
<H extends SuperClass> void boundedMethod1(AnotherGenericClass<H> arg) {
}
void boundedMethod2(AnotherGenericClass<? extends SuperClass> arg) {
}
//These two methods works the same
<U extends Building> void boundedListMethod1(List<U> list){
}
void boundedListMethod2(List<? extends Building> list) {
}
//Why can't we write like this? Giving Compile time error
//<U> void notWorkingMethod1(List<U extends SuperClass> list){ //Statements }
//<T> void notWorkingMethod2(List<U extends SuperClass> list){ //Statements }
}
Inside the notWorkingMethods1 and notWorkingMethods2 why can't we pass Bounded Type parameter directly but we can do so by first declaring it before return type ?