Sub topic 2
Writing Your First Generic Class
In the last chapter you saw what goes wrong without generics. You can put anything into a raw List, so every read needs a cast, and a wrong element only fails when the program runs. This chapter fixes that problem. You will write a small class called Box that holds one value, and then make it generic so the compiler always knows what type is inside.
Key words for this chapter
These terms come up throughout the chapter. Each one is defined here first.
| Term | Meaning | Example |
|---|---|---|
| Generic class | A class that has one or more type parameters | `Box<T>` |
| Type parameter | A placeholder name for a type, written in angle brackets | the `T` in `Box<T>` |
| Type argument | The real type you put in place of the placeholder | the `String` in `Box<String>` |
| Parameterized type | A generic class with a type argument filled in | `Box<String>` |
A type parameter works like a method parameter. A method parameter stands in for a value. A type parameter stands in for a type. When you call a method, you pass a value. When you use a generic class, you pass a type.
Step 1: A box that holds only strings
Start with a plain class that is not generic. It holds one String.
public class StringBox {
private String value;
public StringBox(String value) {
this.value = value;
}
public String get() {
return value;
}
public void set(String value) {
this.value = value;
}
}This class is safe. The compiler only lets you store a String. But what if you also need a box for an Integer, or a box for a LocalDate? You would have to copy the class and change the type each time. That gives you IntegerBox, DateBox, and so on. They all have the same code, and the only thing that changes is one type name.
Step 2: A box that holds anything, unsafely
One way to avoid the copies is to use Object, because every class in Java extends Object.
public class ObjectBox {
private Object value;
public ObjectBox(Object value) {
this.value = value;
}
public Object get() {
return value;
}
public void set(Object value) {
this.value = value;
}
}Now one class works for every type. But you are back to the old problem. get() returns Object, so you must cast the result, and the compiler cannot catch a wrong cast:
public class ObjectBoxProblem {
public static void main(String[] args) {
ObjectBox box = new ObjectBox("hello");
box.set(42); // compiles: any Object is allowed
String s = (String) box.get(); // ClassCastException at runtime
System.out.println(s);
}
}(This file needs ObjectBox from above to compile.) We want one class that is reusable like ObjectBox and also safe like StringBox.
Step 3: Make the class generic
To make Box generic, add a type parameter after the class name, then use that name everywhere you used String before.
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
public void set(T value) {
this.value = value;
}
}Here is what changed:
class Box<T>declares a type parameter namedT. The angle brackets< >hold the type parameter list.- The field
private T value;means "a field whose type is whateverTturns out to be." - The constructor takes a
T,get()returns aT, andsettakes aT.
Inside the class, you can use T almost anywhere you would write a normal type name: as a field type, a parameter type, a return type, or a local variable type.
Step 4: Use the generic class
When you use Box, you supply a type argument. Java then treats T as that type for that object.
class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
public void set(T value) {
this.value = value;
}
}
public class BoxDemo {
public static void main(String[] args) {
Box<String> greeting = new Box<>("hi");
String s = greeting.get(); // no cast needed
System.out.println(s.toUpperCase()); // HI
Box<Integer> count = new Box<>(5);
count.set(count.get() + 1);
System.out.println(count.get()); // 6
// greeting.set(5); // compile error: int cannot be converted to String
}
}Save this as BoxDemo.java, then run javac BoxDemo.java and java BoxDemo. It prints HI and then 6.
Look at what you gain:
- No casts.
greeting.get()already returns aString. - Errors are found early. If you remove the
//beforegreeting.set(5);, the program does not compile. The mistake is caught before the program runs, not by a user. - One class serves many types.
Box<String>andBox<Integer>both come from the same source code.
The empty <> on the right side, as in new Box<>("hi"), is called the diamond. It tells the compiler to work out the type argument from the left side. A later chapter covers it in detail. For now, read new Box<>("hi") as short for new Box<String>("hi").
How one class becomes many types
You write Box<T> once. Each time you choose a type argument, the compiler checks your code as if T were that type.
Common beginner mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Writing `Box box = new Box("hi");` | You get a raw type. Casts come back and the compiler warns you | Write `Box<String> box = new Box<>("hi");` |
| Writing `Box<int>` | Compile error: primitives are not allowed | Use `Box<Integer>` |
| Repeating `<T>` on the constructor | Compile error or a confusing new type parameter | Declare `<T>` only after the class name |
| Expecting `T` to have methods like `length()` | Compile error: the compiler only knows `T` is some `Object` | Add a bound, covered in a later chapter |
The last row is important. Inside Box<T>, the compiler knows nothing about T except that it is an object. You can call value.toString() or value.equals(...), because every object has those. You cannot call value.length(), because not every type has it.
Exercises
Exercise
In the declaration public class Box<T> and the use Box<Double> price = new Box<>(9.99);, which part is the type parameter and which is the type argument?
Show answer
T is the type parameter, the placeholder declared on the class. Double is the type argument, the real type that replaces T for the price object.
Exercise
Given Box<String> name = new Box<>("Ada");, does the line name.set(36); compile? Explain why.
Show answer
No. For name, T is String, so set accepts only a String. Passing 36 (an int) is a compile error, so the mistake is caught before the program runs.
Exercise
Write a generic class Holder<T> with a private field item, a constructor that takes the item, and a method isEmpty() that returns true when item is null.
Show answer
class Holder<T> { private T item; public Holder(T item) { this.item = item; } public boolean isEmpty() { return item == null; } } Comparing with null works for any T because every type argument is a reference type.
Exercise
Inside Box<T>, a student adds the method public int size() { return value.length(); }. Why does this not compile?
Show answer
The compiler only knows that T is some kind of Object, and Object has no length() method. A Box<Integer> would have no such method either. Bounds, covered in a later chapter, let you promise more about T.