在 Java 中,JDK 中的大多数(或全部?)泛型类都具有一位数的泛型类型名称。例如HashMap
的定义如下所示:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
为什么这是约定而不是更具描述性的类型名称,如 HashMap<KEY,VALUE>
?
最佳答案
我认为这里的重点是简单约定。如果您对泛型类型使用单字母名称,而对类名称使用多字母名称,那么您正在处理的内容就很明显了。此外,如果您在指向时使用 KEY 或 VALUE,这些名称将看起来像常量名称。公约说:
UPPERCASE_AND_UNDERSCORE -> CONSTANTS
UpperCamelCase -> ClassNames
lowerCamelCase -> attributes
T,S,V -> genericTypes
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.
关于java - 在java中使用单字符泛型类型名称的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908389/