|
| 1 | +--- |
| 2 | +id: 81fd0ae3-6d56-412a-a085-90d87c84f6fe |
| 3 | +slug: "raw-collections-to-generics" |
| 4 | +title: "Raw collections to generic types" |
| 5 | +category: "language" |
| 6 | +difficulty: "beginner" |
| 7 | +jdkVersion: "5" |
| 8 | +oldLabel: "Java 1.4" |
| 9 | +modernLabel: "Java 5+" |
| 10 | +oldApproach: "Raw collections" |
| 11 | +modernApproach: "Generic collections" |
| 12 | +oldCode: |- |
| 13 | + List names = new ArrayList(); |
| 14 | + names.add("Duke"); |
| 15 | +
|
| 16 | + String name = (String) names.get(0); |
| 17 | +modernCode: |- |
| 18 | + List<String> names = new ArrayList<>(); |
| 19 | + names.add("Duke"); |
| 20 | +
|
| 21 | + String name = names.getFirst(); |
| 22 | +summary: "Replace raw collection types and retrieval casts with compile-time generic type safety." |
| 23 | +explanation: "Raw collections accept arbitrary object types and defer type errors until a cast executes.\ |
| 24 | + \ Generic type arguments let the compiler validate writes and reads, remove casts, improve IDE assistance,\ |
| 25 | + \ and make API contracts explicit. Raw types should normally remain only at carefully isolated legacy\ |
| 26 | + \ interoperability boundaries." |
| 27 | +whyModernWins: |
| 28 | +- icon: "🔒" |
| 29 | + title: "Compile-time safety" |
| 30 | + desc: "Invalid element types fail during compilation rather than at runtime." |
| 31 | +- icon: "🧹" |
| 32 | + title: "No retrieval casts" |
| 33 | + desc: "Values retain their declared element type." |
| 34 | +- icon: "📖" |
| 35 | + title: "Self-documenting APIs" |
| 36 | + desc: "Collection declarations state exactly what they contain." |
| 37 | +support: |
| 38 | + state: "available" |
| 39 | + description: "Generics have been available since JDK 5 (September 2004)." |
| 40 | +prev: "language/diamond-operator" |
| 41 | +next: "language/private-interface-methods" |
| 42 | +related: |
| 43 | +- "language/diamond-operator" |
| 44 | +- "language/type-inference-with-var" |
| 45 | +- "collections/immutable-list-creation" |
| 46 | +tags: |
| 47 | +- generics |
| 48 | +- collections |
| 49 | +docs: |
| 50 | +- title: "Generics (The Java Tutorials)" |
| 51 | + href: "https://docs.oracle.com/javase/tutorial/java/generics/index.html" |
0 commit comments