Difference between revisions of "Generics"
From Suhrid.net Wiki
Jump to navigationJump to searchLine 1: | Line 1: | ||
* Generics is a way to enforce '''ONLY compile-time''' type safety. | * Generics is a way to enforce '''ONLY compile-time''' type safety. | ||
* All the type information is not present at run-time. The compiler strips out type information from the bytecode using a process called type erasure. | * All the type information is not present at run-time. The compiler strips out type information from the bytecode using a process called type erasure. | ||
+ | * '''WHY Type erasure ?''' To ensure backward compatibility with legacy code. | ||
+ | * This compile-time safety is broken when generic and non-generic legacy code are mixed up. | ||
+ | * Watch out when autoboxing is involved with legacy code. | ||
+ | |||
+ | <syntaxhighlight lang="java"> | ||
+ | List l = new ArrayList(); | ||
+ | l.add(123); //Auto-boxing happens. | ||
+ | int i = l.get(0); //Compile-time error. Autounboxing cant work because get() returns Object and not Integer. | ||
+ | </syntaxhighlight> | ||
[[Category:OCPJP]] | [[Category:OCPJP]] |
Revision as of 04:17, 25 May 2011
- Generics is a way to enforce ONLY compile-time type safety.
- All the type information is not present at run-time. The compiler strips out type information from the bytecode using a process called type erasure.
- WHY Type erasure ? To ensure backward compatibility with legacy code.
- This compile-time safety is broken when generic and non-generic legacy code are mixed up.
- Watch out when autoboxing is involved with legacy code.
List l = new ArrayList();
l.add(123); //Auto-boxing happens.
int i = l.get(0); //Compile-time error. Autounboxing cant work because get() returns Object and not Integer.