Java Generics Example in Java
On this page (7sections)
Introduction
Generics let you write classes, interfaces and methods that operate on types specified by the caller. They eliminate unsafe casts and make collection code clearer.
Example Program
import java.util.*;
class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
@Override
public String toString() {
return "Box holds: " + value + " (" + value.getClass().getSimpleName() + ")";
}
}
public class GenericsDemo {
public static void main(String[] args) {
Box<String> message = new Box<>();
message.set("Hello Generics");
System.out.println(message);
Box<Integer> number = new Box<>();
number.set(42);
System.out.println(number);
List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Kotlin");
// languages.add(10); // Compile error — type-safe
for (String lang : languages) {
System.out.println(lang.toUpperCase());
}
}
}
Sample Output
Box holds: Hello Generics (String)
Box holds: 42 (Integer)
JAVA
KOTLIN
How It Works
Box<T>declares a type parameterTreplaced at compile time with a concrete type.List<String>ensures only strings are added; the compiler rejects incompatible types.- Autoboxing allows
number.set(42)whereTisInteger.
Best Practices
- Always specify generic types on collections (
List<String>, not rawList). - Use bounded wildcards (
? extends Number) when writing flexible APIs. - Prefer generic methods when the type parameter is independent of the class.
Common Mistakes
- Using raw types and casting elements manually.
- Creating arrays of generic types directly (
new T[10]is not allowed).
Frequently Asked Questions
Why use generics instead of Object?
Generics provide compile-time type checking. You avoid ClassCastException at runtime because the compiler verifies that you store and retrieve the correct type.
Can primitives be used with generics?
No. Use wrapper classes such as Integer, Double and Boolean, or autoboxing converts between primitive and wrapper automatically.