Raw collections to generic types
Replace raw collection types and retrieval casts with compile-time generic type safety.
Code Comparison
✕ Java 1.4
List names = new ArrayList();
names.add("Duke");
String name = (String) names.get(0);
✓ Java 5+
List<String> names = new ArrayList();
names.add("Duke");
String name = names.get(0);
See a problem with this code? Let us know.
Why the modern way wins
Compile-time safety
Invalid element types fail during compilation rather than at runtime.
No retrieval casts
Values retain their declared element type.
Self-documenting APIs
Collection declarations state exactly what they contain.
Old Approach
Raw collections
Modern Approach
Generic collections
Since JDK
5
Difficulty
Beginner
JDK Support
Raw collections to generic types
Available
Generics have been available since JDK 5 (September 2004).
How it works
Raw collections accept arbitrary object types and defer type errors until a cast executes. Generic type arguments let the compiler validate writes and reads, remove casts, improve IDE assistance, and make API contracts explicit. Raw types should normally remain only at carefully isolated legacy interoperability boundaries.
Related Documentation
Proof