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
I don't seem to quite understand what exactly does every letter correspond to. I understand that each letter represents just a convention but what does 2nd, 3rd and 4th type mean exactly? When should I use what? On their official tutorials website it doesn't give further information.
A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
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.
Some examples:
Map<K, V>
: A map usually assigns V
alues to K
eys. These are special kinds of types, so they are used here.List<E>
: A list contains E
lements. It's a convention that they are called elements. On the other hand, T
would also be acceptable here.Formatter<T>
: A formatter can format any T
ype. It's not really an element, nor a key, nor a value, so T
is the correct letter here.Triplet<T, U, V>
: A triplet for arbitrary types. Since the type definition does not know anything about the types that will be filled in later, it uses just the T
for the first type, followed by the next letters in alphabetical order.As you know, the letters don't mean anything in themselves and are just conventions to make reading the code a bit easier. The "2nd, 3rd and 4th types" bit just means when you have a parameterised type with multiple arguments you should call those arguments S, T, U, V etc. For example
class MyClass<S, T, U> { }
is a class with three type parameters.
Obviously you don't have to use S, T and U. If a more meaningful convention can be used then you should do so, for example
class Car<W, E, P> { }
could be a Car class parameterised on wheel, engine and paint type.
EDIT: As the other answer pointed out, even better would be:
class Car<WheelType, EngineType, PaintType> { }
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