Java Generics — Write Type-Safe Classes and Methods
Learning Objectives
- Write classes and methods with type parameters
- Apply bounded type parameters with the extends keyword
- Understand wildcards in method parameters
- Explain why generics improve safety despite type erasure
Overview
Before generics, collections stored every element as a raw object. You cast each item when reading it, and a wrong cast crashed the program at runtime with ClassCastException. Generics let you describe the element type once, and the compiler enforces that description everywhere.
The syntax uses angle brackets around a type name, written inside fenced code blocks when you declare the type. Inside the brackets you choose a placeholder such as T, E, K, or V by convention: T for type, E for element, K and V for map keys and values.
Generic Classes
A generic class declares one or more type parameters on the class line. Methods and fields may then refer to those parameters as real types.
class PairKv<K, V> {
private K key;
private V value;
PairKv(K key, V value) {
this.key = key;
this.value = value;
}
K getKey() {
return key;
}
V getValue() {
return value;
}
}
public class PairDemo {
public static void main(String[] args) {
PairKv<String, Integer> ages = new PairKv<>("Ann", 30);
System.out.println(ages.getKey());
System.out.println(ages.getValue());
}
}
When you construct Pair of String and Integer, the compiler remembers that combination. Trying to store an integer in the key slot produces a compile error instead of a late crash.
Generic Methods
Methods may declare their own type parameters, independent of the class. Place the type list before the return type.
class ArrayTools {
static <T> T firstOf(T[] items) {
if (items.length == 0) {
return null;
}
return items[0];
}
}
public class GenericMethodDemo {
public static void main(String[] args) {
String[] names = {"Ann", "Bo"};
Integer[] nums = {1, 2, 3};
System.out.println(ArrayTools.firstOf(names));
System.out.println(ArrayTools.firstOf(nums));
}
}
One implementation works for any array type, and the compiler still knows the precise return type at each call site, so no casting is required.
Bounded Type Parameters
Sometimes a type parameter must support certain behavior, such as calling compareTo for sorting. A bound written with the extends keyword in the declaration states that the type must be a given class or subclass, or implement a given interface.
class Stats<T extends Number> {
double sum;
void add(T number) {
sum += number.doubleValue();
}
double total() {
return sum;
}
}
public class BoundDemo {
public static void main(String[] args) {
Stats<Integer> intStats = new Stats<>();
intStats.add(5);
intStats.add(10);
System.out.println(intStats.total());
}
}
The bound guarantees doubleValue exists, while still allowing Integer, Double, and other numeric wrappers.
Wildcards
Wildcards express flexibility about the type argument. An unbounded wildcard means any type. A lower bound means any supertype of a given type. An upper bound means the given type or its subclasses. Upper bounds are the most common in method parameters when you only need to read elements.
import java.util.List;
class Logger {
static void printAll(List<?> items) {
for (Object item : items) {
System.out.println(item);
}
}
}
Prefer wildcards over raw types. Raw types disable checking and reintroduce the very errors generics were added to prevent.
Type Erasure
Generics are primarily a compile time feature. The compiler checks your type arguments, then removes most type parameter information in the translated bytecode. This process, called type erasure, preserves compatibility with older non-generic code.
The practical consequences are that you cannot create a new array of a generic type directly, you cannot use a type parameter with the instanceof operator in its bare form, and generic types are not distinct at runtime the way classes are. The compiler still protects normal usage, which covers the vast majority of application code.
Key Takeaways
💡
- Generics move type checks from runtime casts to compile time errors
- Generic classes declare type parameters once and reuse them everywhere
- Generic methods declare their own type list before the return type
- Bounds restrict type parameters when specific methods are required
- Type erasure explains a few advanced restrictions without negating safety
Practice Questions
- Build a generic Box class that stores one value and demonstrate it with two different types.
- Write a generic method that returns the larger of two comparable values.
- Why are raw types discouraged compared with wildcard parameters?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions