Interview question
What are Generics in Java and why were they introduced? Java में Generics क्या हैं और इन्हें क्यों introduce किया गया?
Answer
Generics allow classes, interfaces, and methods to operate on a type specified at compile time, providing compile-time type safety and eliminating the need for manual casting.
// BEFORE generics (Java 1.4 and earlier) - raw types, unsafe
List list = new ArrayList();
list.add('Hello');
list.add(42); // no compile-time check - mixing types allowed
String s = (String) list.get(0); // manual cast required
String s2 = (String) list.get(1); // ClassCastException at RUNTIME! 42 isn't a String
// WITH generics (Java 5+) - type-safe
List<String> typedList = new ArrayList<>();
typedList.add('Hello');
// typedList.add(42); // COMPILE ERROR - caught immediately, not at runtime
String value = typedList.get(0); // no cast needed, compiler knows the type
| Benefit | Explanation |
|---|---|
| Compile-time type checking | Type errors caught before running the program |
| No explicit casting | Compiler inserts casts automatically and safely |
| Generic algorithms | Write one method that works for multiple types |
Generics classes, interfaces, methods को compile time पर specified type पर operate करने देते हैं, compile-time type safety देते हैं और manual casting की ज़रूरत खत्म करते हैं।
// Generics से पहले (Java 1.4) - raw types, unsafe
List list = new ArrayList();
list.add('Hello');
list.add(42); // कोई compile-time check नहीं
String s = (String) list.get(0);
String s2 = (String) list.get(1); // ClassCastException runtime पर!
// Generics के साथ (Java 5+) - type-safe
List<String> typedList = new ArrayList<>();
typedList.add('Hello');
// typedList.add(42); // COMPILE ERROR - तुरंत पकड़ा जाता है
String value = typedList.get(0); // cast की ज़रूरत नहीं| फायदा | विवरण |
|---|---|
| Compile-time type checking | Errors program चलने से पहले पकड़े जाते हैं |
| Explicit casting नहीं | Compiler automatically cast करता है |
Was this answer clear?