Card 01/ 09
All 9 cards
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.
List refs = new ArrayList();
refs.add("AB-1");
refs.add(42);
String first = (String) refs.get(1);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.
List<String> refs = new ArrayList<>();
refs.add("AB-1");
refs.add(42);
String first = refs.get(0);| Compared on | List | List<String> |
|---|---|---|
| Wrong thing added | Accepted | Refused by the compiler |
| Taking something out | Needs a cast | Needs nothing |
| Where a mistake is found | At the line that reads it | At 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.