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

标签 java generics

在 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

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

关于java - 在java中使用单字符泛型类型名称的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908389/

相关文章:

java - 使用 Yahoo Finance API 检索股票行情

java - 赋值 - 创建一个通用类并实现 Comparable(Java)

c# - 具有泛型属性的 LINQ 表达式

delphi - TControlClass 作为通用 TControl 参数?

java - 从Pig脚本向UDF中的参数化构造函数传递值

java - AppEngine sun.misc.Unsafe 限制

嵌入式设备上的 JavaFX BufferOverflowException

java - Oracle 的 Collection<Object> 教程令人困惑

java - 无法编译 FutureTask 内部类创建

java - 如何在 Wiremock 中使用相同的 header 进行响应?