有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中使用单字符泛型类型名的原因是什么?

在java中大多数(或全部?)JDK中的泛型类具有一位数的泛型类型名。例如HashMap的定义如下:

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {

为什么这是惯例,而不是像HashMap<KEY,VALUE>这样更具描述性的类型名


共 (1) 个答案

  1. # 1 楼答案

    我认为这里的要点是简单的惯例。如果泛型类型使用一个字母,类名使用多个字母,那么很明显你要处理的是什么。此外,如果在指向时使用KEY或VALUE,这些名称将看起来像常量名称。公约规定:

    UPPERCASE_AND_UNDERSCORE -> CONSTANTS
    
    UpperCamelCase -> ClassNames
    
    lowerCamelCase -> attributes
    
    T,S,V -> genericTypes
    

    看看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.