Sub topic 3
Naming Type Parameters: T, E, K, V
In the last chapter you wrote Box<T>. You may have wondered why the type parameter is called T and not Thing or Item. This chapter explains the naming habits Java programmers follow, why they follow them, and which mistakes a bad name can cause.
A type parameter is a placeholder name for a type. The caller fills it in later. In Box<T>, the T is the type parameter. In Box<String>, String is the type argument, meaning the real type that replaces T.
The Rule the Compiler Enforces
To the compiler, a type parameter name is just an identifier. An identifier is a name you make up, like a variable name. Any legal Java name works. These two classes behave exactly the same:
public class Crate<T> {
private T content;
public Crate(T content) { this.content = content; }
public T get() { return content; }
}public class Crate2<Content> {
private Content content;
public Crate2(Content content) { this.content = content; }
public Content get() { return content; }
}Both compile, and both work. The name only matters to people reading the code. That is why the community agreed on a short list of conventions.
The Standard Letters
A naming convention is a habit that most programmers follow so code looks familiar. For generics, the convention is a single uppercase letter. Each common letter hints at what the type is for.
| Letter | Stands for | Typical use | Example in the JDK |
|---|---|---|---|
| `T` | Type | Any general type | `Comparable<T>`, `Optional<T>` |
| `E` | Element | Items stored in a collection | `List<E>`, `Set<E>` |
| `K` | Key | Keys in a map | `Map<K, V>` |
| `V` | Value | Values in a map | `Map<K, V>` |
| `N` | Number | A numeric type | Often used with `N extends Number` |
| `R` | Result or Return | What a function returns | `Function<T, R>` |
| `S`, `U` | Second, third type | Extra types beside `T` | `BiFunction<T, U, R>` |
The JDK means the Java Development Kit, the standard library that ships with Java. When you open its source code, you see these letters everywhere. Once you know them, you can guess what a type is for from its signature alone. For example, Function<T, R> reads as "takes a T, returns an R."
A Worked Example with E
Here is a small stack. A stack is a collection where the last item you put in is the first item you take out. It holds elements, so the convention says to use E.
import java.util.ArrayList;
import java.util.List;
public class SimpleStack<E> {
private final List<E> items = new ArrayList<>();
public void push(E item) {
items.add(item);
}
public E pop() {
if (items.isEmpty()) {
throw new IllegalStateException("stack is empty");
}
return items.remove(items.size() - 1);
}
public boolean isEmpty() {
return items.isEmpty();
}
public static void main(String[] args) {
SimpleStack<String> stack = new SimpleStack<>();
stack.push("first");
stack.push("second");
System.out.println(stack.pop()); // second
System.out.println(stack.pop()); // first
}
}A reader sees SimpleStack<E> and knows at once that E is the kind of thing stored inside. It matches List<E> in the same file, so the code reads smoothly.
Why One Uppercase Letter?
Class names in Java are words like String, Customer, or ArrayList. If type parameters were also full words, you could not tell them apart at a glance. Look at this line:
// public Item find(Key key)Is Item a real class somewhere in the project, or a type parameter? You would have to scroll up to check. With public V find(K key), a single letter tells you right away that these are placeholders.
Gotcha 1: Naming a Parameter After a Real Class
Since any identifier is allowed, you can name a type parameter String. The code compiles, but now String inside the class means the placeholder, not java.lang.String. This is called shadowing: a new name hides an older name that is spelled the same way.
public class ShadowDemo<String> {
private String value; // this String is the type parameter
public ShadowDemo(String value) {
this.value = value;
}
public String get() {
return value;
}
// Inside this class, plain "String" means the type parameter.
// So main must spell out java.lang.String.
public static void main(java.lang.String[] args) {
ShadowDemo<Integer> demo = new ShadowDemo<>(42);
Integer x = demo.get(); // the "String" here was really Integer
System.out.println(x); // 42
}
}The program prints 42, which surprises most readers. Single letters avoid this trap, because no normal class is called T or E.
Gotcha 2: Reusing T in a Method
A method can declare its own type parameter. The chapter on generic methods covers this in full. For now, note one naming trap: if the class already has T and a method declares <T> again, the method's T hides the class's T. They are two separate types that happen to share a name.
public class Holder<T> {
private final T item;
public Holder(T item) {
this.item = item;
}
// Confusing: this <T> is a NEW type, unrelated to the class's T.
public <T> T echoConfusing(T input) {
return input;
}
// Clear: a different letter shows it is a different type.
public <U> U echoClear(U input) {
return input;
}
public T getItem() {
return item;
}
public static void main(String[] args) {
Holder<String> h = new Holder<>("box");
Integer a = h.echoConfusing(7); // works: method T is Integer
Integer b = h.echoClear(8);
System.out.println(h.getItem() + " " + a + " " + b); // box 7 8
}
}echoConfusing accepts an Integer even though the holder is a Holder<String>. A reader expecting T to mean String would be misled. Many IDEs, the code editors such as IntelliJ IDEA or Eclipse, warn about this hiding. Picking U makes the intent clear.
When a Longer Name Is Fine
The single-letter rule is a convention, so you can break it when doing so makes the code clearer. Some teams use names like TKey and TValue, or ID for an identifier type, when a class has many type parameters and single letters become hard to follow. If you choose longer names:
- Keep them visually different from class names, for example with a
Tprefix. - Use the same style throughout the project.
- Never reuse the name of an existing class.
For most code, and in every example in this tutorial, the standard letters are the best choice because every Java programmer already knows them.
Exercise
You are writing a generic class that stores a lookup table from product codes to prices, where the caller chooses both types. Which letters should you use for its two type parameters, and why?
Show answer
Use K for the product code and V for the price, as in ProductTable<K, V>. The class maps keys to values, and K and V are the standard letters for map keys and values, matching java.util.Map<K, V>.
Exercise
A teammate writes "public class Wrapper<Integer> { Integer data; }" and then creates "new Wrapper<String>()". What type does the field data really have for that object, and what would you change?
Show answer
The field has type String, because Integer here is a type parameter that shadows java.lang.Integer, and the caller supplied String. Rename the type parameter to a single letter such as T: "public class Wrapper<T> { T data; }".
Exercise
Inside class Cache<T>, a method is declared as "public <T> void store(T x)". Is the method's T the same as the class's T? How should you fix the declaration?
Show answer
No. The method declares a new type parameter that hides the class's T, so the two are unrelated. If the method should use the class's type, remove the <T> and write "public void store(T x)". If it really needs its own type, rename it, for example "public <U> void store(U x)".