Why is it that a generic T cannot be used as a return type of class if T extends Class.
Example:
public class Foo<T extends Bar> {
Bar[] array = new Bar[200];
Optional<T> forIndex(int index) {
return Optional.ofNullable(array[index]);
}
}
T is required to extend Bar Which means that T should never have a casting problem, or am I mistaking this? Could somebody elaborate.
You got it the wrong way around. Each
Tis aBar, but not eachBaris aT.Tis more specialized thanBar(each dachshound is a dog, but not each dog is a dachshound). This means, thatreturn Optional.ofNullable(array[index]);tries to match aBaron aT, which is not possible.What you can do is making only the method generic:
You might want to look at Oracle's tutorial on Wildcards as well as the PECS (Producer
extends- Consumersuper) mnemonic