01 / 21
<T> Java

Using Generic Types
in Java

Master type-safe collections and parameterized types: List<String>, Map<K,V>, and beyond.

Java

What Are Generics?

Generics let you write classes, interfaces, and methods that work with any type while still catching type errors at compile time rather than at runtime. Instead of storing everything as Object and casting, you declare a type parameter like <T>.

// Without generics: dangerous casts List items = new ArrayList(); items.add("hello"); String s = (String) items.get(0); // cast required // With generics: compile-time safety List<String> items = new ArrayList<>(); items.add("hello"); String s = items.get(0); // no cast needed

Why Generics Matter

✓ Type Safety
The compiler catches mismatched types before your code ever runs. No more ClassCastException at runtime.
✓ No Casting
Elements come back as their declared type. You never need to write (String) casts on collection access.
✓ Reusable Code
Write one algorithm that works for any type: Integer, String, your custom class, anything.

The Type Parameter <T>

Box<T> T item; void set(T item) T get() Generic Definition T = String Box<String> String item; void set(String item) String get() Concrete Usage

When you declare Box<T>, the T is a type parameter. When you instantiate Box<String>, the compiler replaces every T with String.

Core Syntax Rules

1
Declare the type parameter in angle brackets after the class or interface name: class MyList<E>.
2
Use the parameter as a type inside the class body: fields, method parameters, and return types.
3
Specify the concrete type when instantiating: new MyList<String>(). Use the diamond operator <> on the right side.
4
Only reference types are allowed: <Integer> not <int>. Primitives must use their wrapper classes.

Common Generic Collections

List<E> Ordered Indexed access Duplicates OK ArrayList, LinkedList Set<E> Unordered No duplicates Fast lookup HashSet, TreeSet Map<K,V> Key-value pairs Unique keys Two type params HashMap, TreeMap All from java.util.* package Queue<E> / Deque<E>

The Java Collections Framework is fully generic. Each interface accepts type parameters for the elements (or key-value pairs) it stores.

Raw Types vs Generic Types

Raw Type Generic Type
Declaration List items List<String> items
Type checking Runtime only Compile time
Casting needed Yes, always No
Can mix types Yes (dangerous) No (safe)
Compiler warnings "unchecked" warnings Clean compile

Step-by-Step: Using Generics

1
Identify the element type you need. Will your collection hold Strings? Integers? A custom Student class?
2
Choose the collection interface: List for ordered sequences, Set for unique elements, Map for key-value lookups.
3
Declare with angle brackets: List<String> names. For maps: Map<String, Integer> scores.
4
Instantiate with the diamond: new ArrayList<>(). The compiler infers the type from the left side.
5
Use directly: call add(), get(), put(), containsKey(), etc. No casts needed.

Example 1: List<String>

// Declare a list that only holds Strings List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); // No cast needed: get() returns String String first = names.get(0); // This would NOT compile: // names.add(42); <-- compile error! // Enhanced for loop: element type is known for (String name : names) { System.out.println(name); }

Example 2: Map<String, Integer>

// A map from student names to their scores Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.put("Bob", 87); scores.put("Charlie", 92); // get() returns Integer (auto-unboxed to int) int aliceScore = scores.get("Alice"); // 95 // Iterate over entries for (Map.Entry<String, Integer> e : scores.entrySet()) { System.out.println(e.getKey() + ": " + e.getValue()); }

Example 3: Nested Generics

// A list of lists: each inner list holds Integers List<List<Integer>> matrix = new ArrayList<>(); // Build a row List<Integer> row1 = new ArrayList<>(); row1.add(1); row1.add(2); row1.add(3); matrix.add(row1); // Map with List values Map<String, List<String>> courseRoster = new HashMap<>();

Writing Your Own Generic Class

public class Pair<A, B> { private A first; private B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } } // Usage: Pair<String, Integer> p = new Pair<>("age", 17); String key = p.getFirst(); // "age" int val = p.getSecond(); // 17

You can define multiple type parameters separated by commas. Here, A and B can be any two reference types, even the same type.

Generic Methods

// The <T> before the return type makes this a generic method public static <T> List<T> singletonList(T item) { List<T> list = new ArrayList<>(); list.add(item); return list; } // The compiler infers T from the argument List<String> a = singletonList("hi"); List<Integer> b = singletonList(42);

Bounded Type Parameters

// T must be a subtype of Comparable<T> public static <T extends Comparable<T>> T findMax(List<T> items) { T max = items.get(0); for (T item : items) { if (item.compareTo(max) > 0) { max = item; } } return max; }
<T extends X>
T must be X or a subclass of X. Gives you access to X's methods inside the generic code.
<T extends X & Y>
T must implement multiple interfaces. Use & to separate bounds (not commas).

Common Mistakes

✕ Using Primitives
List<int> won't compile. Use the wrapper: List<Integer>. Generics only work with reference types.
✕ Raw Types
Writing List items instead of List<String> items. This compiles but gives "unchecked" warnings and loses all type safety.
✕ new T()
You cannot instantiate a type parameter directly. new T() is illegal due to type erasure. Use a factory or supplier instead.
✕ Ignoring Warnings
Suppressing "unchecked" warnings with @SuppressWarnings hides bugs. Fix the root cause: add proper type parameters.

Summary Reference

Pattern Syntax Example
Single param List<E> List<String>
Two params Map<K, V> Map<String, Integer>
Diamond new Type<>() new ArrayList<>()
Bounded <T extends X> <T extends Comparable<T>>
Generic method <T> ReturnType name(T arg) <T> List<T> of(T item)
Nested Type<Type<E>> List<List<Integer>>

Question 1 of 5

Which declaration correctly creates a List that can only hold String objects?

Question 2 of 5

What is the main advantage of using generic types over raw types?

Question 3 of 5

Given Map<String, List<Integer>> data, what type does data.get("scores") return?

Question 4 of 5

Which line will cause a compile-time error?

List<Integer> nums = new ArrayList<>(); nums.add(10); // Line A nums.add("ten"); // Line B int x = nums.get(0); // Line C nums.add(20); // Line D

Question 5 of 5

What does <T extends Comparable<T>> mean in a method signature?