In java most (or all?) generic classes in the JDK have single-digit generic type names. For example HashMap
's definition looks like this:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
Why is this the convention instead of more descriptive type names like HashMap<KEY,VALUE>
?
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
In the case of countTypes , simply a <T> indicates a generic type. As mentioned previously, bounded types can be used to restrict the type that can be specified for a generic type.
Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
I think the main point here is simple convention. If you use single-letter for generic types and multiple-letter names for class names it comes obvious what you are dealing with. Also, if you used KEY or VALUE as you point, these names would look as constant names. Convention says:
UPPERCASE_AND_UNDERSCORE -> CONSTANTS
UpperCamelCase -> ClassNames
lowerCamelCase -> attributes
T,S,V -> genericTypes
Check out the official documentation
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this lesson.
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