ConceptDifficulty: Intermediate1 min

Moving a Cast From the Moment It Runs to the Moment It Compiles

Before generics, every collection held Object. Taking something out meant casting it back, and the cast was a promise nobody checked until the line ran.

java
List refs = new ArrayList();
refs.add("AB-1");
refs.add(42);

String first = (String) refs.get(1);
compiles cleanly, throws on line 5

A type parameter moves that failure forward. List<String> tells the compiler what belongs in the list, and it refuses the line that put the wrong thing in rather than the line that took it out.

java
List<String> refs = new ArrayList<>();
refs.add("AB-1");
refs.add(42);

String first = refs.get(0);
line 3 no longer compiles, and line 5 needs no cast
What changes when the type is a parameter
Compared onListList<String>
Wrong thing addedAcceptedRefused by the compiler
Taking something outNeeds a castNeeds nothing
Where a mistake is foundAt the line that reads itAt the line that wrote it

So generics do not make anything faster and do not change what is stored. They move a failure from the machine of whoever runs your code to the machine of whoever writes it, which is the only place a failure is cheap.