I am having trouble interpreting/understanding the generic type of a Java List:
List<? extends Command> myVar = client.performAction(actionParams);
How is the generic type ? extends Command
called, like is there a name for it? What exactly is this type? Is it a Command
object? Or does this mean that it only accepts classes extending Command
? What is my advantage using this sort of construct? In what Java version was this type of construct integrated?
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).
The question mark ( ? ) wildcard character can be used to represent an unknown type using generic code. Wildcards can be used with parameters, fields, local variables, and return types.
In c#, List is a generic type of collection, so it will allow storing only strongly typed objects, i.e., elements of the same data type.
Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use. Rather than specifying obj to be of an int type, or a String type, or any other type, you define the Box class to accept a type parameter < ;T>.
Upper-bounded wildcards are used to relax the type-restriction of objects you can use. In this case you accept everything that extends/implements the Command
type.
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