- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Type Erasure in Java
To support generic programming, as well as perform a stricter type check, Java implements type erasure.
All type parameters in generic types are replaced with the bound (if unbounded) or object type. This way, the bytecode will only contain classes, methods, and interfaces.
Type casts to preserve the type.
Bridge methods are generated so as to preserve the polymorphism concept in extended generic types.
Example
import java.io.PrintStream; import java.util.*; public class Demo{ public Demo(){ } public static void main(String args[]){ List my_list = new ArrayList(); my_list.add("Hi there"); String my_str; for (Iterator iter = my_list.iterator(); iter.hasNext(); System.out.println(my_str)) my_str = (String)iter.next(); } }
Output
Hi there
A class named Demo contains a constructor that basically has no body defined inside it. In the main function, a new array list is created, and elements are added into it using the ‘add’ function. An iterator is defined, and a string is defined. An iterator iterates over the elements in the string using the ‘hasNext’ function that checks if there is an element and then moves over to it. The output is printed on the screen.