32.96K

Generics_Presentation

1.

Generics in Java
• Why They Exist and How They Make Code
Safer

2.

The Problem Before Generics
• • Collections stored only Object
• • Any type could be added
• • Casting required
• • Errors at runtime

3.

What Generics Fix
• • Compile-time type safety
• • No manual casting
• • Cleaner code
• • Reusable algorithms

4.

Compile-Time Safety
• list.add(10); // compile error
• String s = list.get(0);

5.

Generic Methods
• <T> void printArray(T[] array) {
• for (T el : array)
System.out.println(el);
• }

6.

How Generics Work Internally
• • Type erasure
• • <T> removed
• • Replaced with Object or bounds
• • No generics in bytecode

7.

Summary
• Generics provide:
• • Type safety
• • No casts
• • Reusable code
• • Efficiency via erasure
English     Русский Правила