Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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? Are they both generic classes? Thanks!

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

// Code 2
public class Bar<Lalaland> {
    private Lalaland a;  
}
like image 393
user234159 Avatar asked Feb 14 '23 01:02

user234159


1 Answers

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,

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
like image 122
rgettman Avatar answered Apr 27 '23 17:04

rgettman