Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for using single-character generic type names in java?

Tags:

java

generics

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> ?

like image 985
Adam Arold Avatar asked Dec 01 '16 10:12

Adam Arold


People also ask

What is the purpose of generic types in Java?

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.

Which character is used for generic type?

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.

What are the benefits of using generic types?

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.

What is the purpose of bounded type in generic programming?

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.


1 Answers

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.

like image 182
Rubasace Avatar answered Sep 27 '22 21:09

Rubasace