why does
public interface ArrayOfONEITEMInterface <T extends ONEITEMInterface>{
public List<T> getONEITEM();
}
compile, but not
public interface ArrayOfONEITEMInterface <? extends ONEITEMInterface>{
public List<?> getONEITEM();
}
what is the difference between ? and T in class and method signatures?
In the first case, T is defined at class level, so your method is part of a generic class and you will have to specialize the class when you declare/instantiate. T will be the same for all methods and attributes in the class. In the second, T is defined at method level, so it's a generic method.
Generics appear in TypeScript code inside angle brackets, in the format < T > , where T represents a passed-in type. <T> can be read as a generic of type T .
The method signature in java is defined as the structure of the method that is designed by the programmer. The method signature is the combination of the method name and the parameter list. The method signature depicts the behavior of the method i.e types of values of the method, return type of the method, etc.
Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ). The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?>
?
is a wildcard and means any subclass of ONEITEMInterface
including itself.
T
is a specific implementation of ONEITEMInterface
in this case.
Since ?
is a wildcard, there is no relation between your ?
in the class declaration and the ?
in your method declaration hence it won't compile. Just List<?> getONEITEM();
will compile though.
The first scenario means the entire class can handle exactly one type of Bar
per instance.
interface Foo<T extends Bar> {
List<T> get();
}
The second scenario allows each instance to operate on any subtype of Bar
interface Foo {
List<? extends Bar> get()
}
T is a placeholder for a type that will be provided by an implementing or instantiating class.
? is a placeholder saying "I don't know or care what the generic type is" generally used when the work you'll do on the container object doesn't need to know the type.
The reason you can't use '?' in the class/interface definition is because there's the value is saying defining the name of the placeholder (and the type will be provided elsewhere). Putting a '?' doesn't make sense.
Furthermore, the placeholder doesn't need to be T, it can any standard Java variable. By convention, it is one capital character, but need not be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With