Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 10 of 10 · Java Generics & Type Safety
Interview question

How do generics improve type safety in the Java Collections Framework? Generics Java Collections Framework में type safety कैसे बेहतर बनाते हैं?

Answer

Before generics (pre-Java 5), collections stored Object references, requiring manual casts and risking ClassCastException at runtime. Generics let the compiler enforce type consistency, catching mismatches before the program ever runs.

// BEFORE generics - unsafe, error discovered at RUNTIME
List list = new ArrayList();
list.add('John');
list.add(25);  // accidentally added an Integer instead of a String

for (Object o : list) {
    String name = (String) o;  // ClassCastException when it hits the Integer!
    System.out.println(name.toUpperCase());
}

// WITH generics - unsafe operation caught at COMPILE time
List<String> names = new ArrayList<>();
names.add('John');
// names.add(25);  // COMPILE ERROR - caught immediately, before running

for (String name : names) {
    System.out.println(name.toUpperCase());  // guaranteed to be a String
}

// Generics also improve API clarity and self-documentation
Map<String, List<Order>> ordersByCustomer = new HashMap<>();
// Immediately clear: keys are customer names (String), values are
// lists of Order objects - no need to check documentation or guess

// Generic methods in the Collections API enforce type-safe algorithms
List<Integer> numbers = List.of(5, 3, 8, 1);
Integer max = Collections.max(numbers);  // type-safe, returns Integer directly

// Comparator<T> ensures sort logic matches the collection's element type
List<String> words = new ArrayList<>(List.of('banana', 'apple'));
words.sort(Comparator.naturalOrder());  // compiler verifies String is Comparable

Generics से पहले (pre-Java 5), collections Object references store करती थीं, manual casts चाहिए होते थे और runtime पर ClassCastException का खतरा रहता था। Generics compiler को type consistency enforce करने देते हैं।

// Generics से पहले - unsafe, error RUNTIME पर मिलती है
List list = new ArrayList();
list.add('John');
list.add(25);  // गलती से Integer add हो गया

for (Object o : list) {
    String name = (String) o;  // Integer पर पहुंचते ही ClassCastException!
    System.out.println(name.toUpperCase());
}

// Generics के साथ - COMPILE time पर पकड़ा जाता है
List<String> names = new ArrayList<>();
names.add('John');
// names.add(25);  // COMPILE ERROR

for (String name : names) {
    System.out.println(name.toUpperCase());  // guaranteed String
}

// Generics API clarity भी बेहतर बनाते हैं
Map<String, List<Order>> ordersByCustomer = new HashMap<>();
// तुरंत साफ़: keys customer names हैं, values Order lists हैं

List<Integer> numbers = List.of(5, 3, 8, 1);
Integer max = Collections.max(numbers);  // type-safe

List<String> words = new ArrayList<>(List.of('banana', 'apple'));
words.sort(Comparator.naturalOrder());

Was this answer clear?