Skip to content
Veltoryx Technologies
ProLesson 6.1Intermediate2 min readUpdated 30 October 2026

Why generics

See the bugs generics prevent, read the angle brackets in List<String>, and understand the type safety they give you at compile time.

Every time you write List<String> or Map<String, Integer>, you're using generics. They let a class or method work with many types while the compiler still checks that you use the right one.

01Life before generics

Before Java 5, collections held plain Objects. You could put anything in, and you had to cast when taking things out:

BeforeGenerics.java
import java.util.ArrayList;
import java.util.List;

public class BeforeGenerics {
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void main(String[] args) {
        List names = new ArrayList();      // raw type: no type information
        names.add("Asha");
        names.add(42);                     // oops, compiles fine
        try {
            for (Object o : names) {
                String name = (String) o;  // cast needed
                System.out.println(name.toUpperCase());
            }
        } catch (ClassCastException e) {
            System.out.println("Crash at run time: " + e.getClass().getSimpleName());
        }
    }
}
Expected output
ASHA
Crash at run time: ClassCastException

The bug, an Integer in a list of names, was only discovered when the program ran.

Loading the rest of the lesson…