What Are Generics in Java: Simple Explanation and Examples
generics allow you to write classes, interfaces, and methods that work with any data type while providing type safety. They help catch errors at compile time by specifying the type of objects a collection or method can work with, avoiding the need for casting.How It Works
Generics in Java work like a recipe that can be used with different ingredients. Instead of writing separate code for each data type, you write one generic code that can handle many types safely. This means you tell Java what type to expect, and it checks your code to make sure you only use that type.
Imagine a box that can hold only one kind of item at a time. With generics, you label the box for a specific item, like "Books" or "Toys," so you don’t accidentally put the wrong thing inside. This helps prevent mistakes before you even run your program.
Example
This example shows a generic class that holds a single item of any type. It safely stores and returns the item without casting.
public class Box<T> { private T item; public void setItem(T item) { this.item = item; } public T getItem() { return item; } public static void main(String[] args) { Box<String> stringBox = new Box<>(); stringBox.setItem("Hello Generics"); System.out.println(stringBox.getItem()); Box<Integer> intBox = new Box<>(); intBox.setItem(123); System.out.println(intBox.getItem()); } }
When to Use
Use generics when you want to create flexible and reusable code that works with different types but still keeps type safety. They are especially useful for collections like lists, sets, and maps, where you want to store objects of a specific type without casting.
For example, if you write a method to process a list of any kind of objects, generics let you write it once and use it for lists of strings, numbers, or custom objects. This reduces bugs and makes your code easier to read and maintain.
Key Points
- Generics enable type-safe code that works with any data type.
- They help catch errors at compile time, avoiding runtime mistakes.
- Generics improve code reusability and readability.
- Commonly used with collections to specify the type of elements.
- Syntax uses angle brackets, e.g.,
<T>, to define type parameters.