Lesson 33
Generics
Generics let code work with multiple data types safely. One method handles integers, strings, objects and more.
Java Track
Save progress as you learn.
61 lessons
Lesson content
Generics allow reusable code across different data types with compile-time safety.
Key Terms
- Generics: Work with different types while maintaining safety.
- Type Parameter: Placeholder representing a data type.
- Compile-Time Safety: Errors caught before runtime.
- Generic Method: Uses type parameters for multiple types.
Generic Method Syntax
public <T> void methodName(T parameter) {
// method body
}Example: Generic Method to Print Arrays
package com.Genric;
public class GenericMethods {
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"one", "two", "three", "four", "five"};
GenericMethods genericMethods = new GenericMethods();
genericMethods.printArray(intArray);
genericMethods.printArray(stringArray);
}
}Output
1 2 3 4 5
one two three four fiveCommon Type Parameter Names
- T — Type
- E — Element
- K — Key
- V — Value
- N — Number
Real-World Uses
// Collections
List<String> names;
ArrayList<Integer> numbers;
HashMap<String, Integer> marks;
// Generic class
class Box<T> {
T value;
}
// Generic interface
interface Data<T> {
void display(T value);
}FAQ
1. What are Generics?
Feature allowing classes and methods to work with multiple types safely.
2. What does <T> mean?
Placeholder for a data type. Replaced at compile time.
3. Why use Generics?
Type safety, less code, early error detection.
Where Java is used
Java in real-world development
Type Parameter <T>
Placeholder replaced at compile time. Works with any data type.
Generic Method
Declare <T> before return type. Method handles multiple types.
Type Safety
Compiler checks types early. Fewer runtime errors.
Collections
List<String>, ArrayList<Integer>, HashMap<K,V> all use generics.
Generic Class
class Box<T> { T value; } Works with any wrapped type.
Best Practice
Use List<String> not raw List. Always specify the type argument.