简体   繁体   English

参数类型中的名称是否确定该类是否是通用的?

[英]Does the name in a parameter type determine if the class is generic?

I just started reading about generic classes. 我刚开始阅读有关泛型类的内容。 I'm wondering if the name of the parameter type affects what gets passed in. So does code 1 and 2 work exactly the same way? 我想知道参数类型的名称是否会影响传入的内容。代码1和代码2的工作方式是否完全相同? Are they both generic classes? 它们都是通用类吗? Thanks! 谢谢!

// Code 1
public class Bar<AnyType> {
    private AnyType a;
}

// Code 2
public class Bar<Lalaland> {
    private Lalaland a;  
}

It works the exact same way, just as choosing a different variable name works the same way. 它的工作方式完全相同,就像选择不同的变量名称一样。

int anyInt = 5;

vs.

int lalaland = 5;

But always be careful that you choose a generic type parameter name different than an existing class name. 但是请务必小心选择与现有类名不同的泛型类型参数名称。 While it's legal, it leads to plenty of confusion when the type parameter is mistaken for the class name. 虽然它是合法的,但当类型参数被误认为类名时,会导致很多混淆。

// Don't do this.
public class Bar<Integer>  // confusing!

According to the Java tutorial on the subject , 根据关于这个主题的Java教程

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) E - Element(Java Collections Framework广泛使用)
  • K - Key K - 钥匙
  • N - Number N - 数字
  • T - Type T型
  • V - Value V - 价值
  • S,U,V etc. - 2nd, 3rd, 4th types S,U,V等 - 第2,第3,第4类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM