Interview question
What is type erasure in Java Generics? Java Generics में type erasure क्या है?
Answer
Type erasure means generic type information exists only at COMPILE time - the compiler uses it for type checking, then removes (erases) it, replacing type parameters with their bounds (or Object) in the compiled bytecode.
List<String> stringList = new ArrayList<>();
List<Integer> intList = new ArrayList<>();
// At RUNTIME, both have the SAME class - generic type info is erased
System.out.println(stringList.getClass() == intList.getClass()); // true
System.out.println(stringList.getClass()); // class java.util.ArrayList (no <String>)
// Consequences of type erasure:
// 1. Cannot create an instance of a type parameter
class Box<T> {
// T item = new T(); // COMPILE ERROR - T is erased, no info at runtime
}
// 2. Cannot use instanceof with a parameterized type
// if (list instanceof List<String>) { } // COMPILE ERROR
if (stringList instanceof List<?>) { } // OK - unbounded wildcard works
// 3. Cannot create generic arrays directly
// T[] array = new T[10]; // COMPILE ERROR
// 4. Static context cannot use a class's type parameter
class Container<T> {
// static T value; // COMPILE ERROR - static members don't have T
}
// Why erasure exists: for BACKWARD COMPATIBILITY with pre-Java 5
// code that used raw types - the bytecode format didn't change,
// generics are purely a compile-time / source-level featureType erasure का मतलब है generic type information सिर्फ COMPILE time पर मौजूद है - compiler इसे type checking के लिए use करता है, फिर erase करके compiled bytecode में type parameters की जगह bounds (या Object) डाल देता है।
List<String> stringList = new ArrayList<>();
List<Integer> intList = new ArrayList<>();
// Runtime पर दोनों की same class है - generic info erase हो जाती है
System.out.println(stringList.getClass() == intList.getClass()); // true
System.out.println(stringList.getClass()); // class java.util.ArrayList
// Type erasure के परिणाम:
// 1. Type parameter का instance नहीं बना सकते
class Box<T> {
// T item = new T(); // COMPILE ERROR
}
// 2. Parameterized type के साथ instanceof नहीं
// if (list instanceof List<String>) { } // COMPILE ERROR
if (stringList instanceof List<?>) { } // ठीक है
// 3. Generic arrays directly नहीं बना सकते
// T[] array = new T[10]; // COMPILE ERROR
// 4. Static context में class के type parameter का उपयोग नहीं
class Container<T> {
// static T value; // COMPILE ERROR
}
// Erasure क्यों है: pre-Java 5 code के साथ backward compatibility के लिएWas this answer clear?